wininet: Support the Cache-Control max-age directive for setting url cache entry...
[wine/testsucceed.git] / dlls / winex11.drv / clipboard.c
blob1a3704d7f9f40b0eb3f8dae3e78a314593c26be6
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 UINT wFlags;
118 DRVIMPORTFUNC lpDrvImportFunc;
119 DRVEXPORTFUNC lpDrvExportFunc;
120 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
122 typedef struct tagWINE_CLIPDATA {
123 struct list entry;
124 UINT wFormatID;
125 HANDLE hData;
126 UINT wFlags;
127 UINT drvData;
128 LPWINE_CLIPFORMAT lpFormat;
129 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
131 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
132 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
133 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
134 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
136 static int selectionAcquired = 0; /* Contains the current selection masks */
137 static Window selectionWindow = None; /* The top level X window which owns the selection */
138 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
140 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned);
141 void CDECL X11DRV_EndClipboardUpdate(void);
142 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
143 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
144 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
145 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
146 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
147 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
148 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
149 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
150 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
151 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
152 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
153 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
154 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
155 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
156 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
157 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
158 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
159 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
160 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
161 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
162 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
163 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
164 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(UINT id, Atom prop);
165 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
166 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
167 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
168 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
169 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
170 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
171 unsigned char** data, unsigned long* datasize);
172 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
173 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
174 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
175 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
176 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
177 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
178 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display);
179 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
181 /* Clipboard formats */
183 static const struct
185 UINT id;
186 UINT data;
187 DRVIMPORTFUNC import;
188 DRVEXPORTFUNC export;
189 } builtin_formats[] =
191 { CF_TEXT, XA_STRING, X11DRV_CLIPBOARD_ImportXAString, X11DRV_CLIPBOARD_ExportString},
192 { CF_BITMAP, XATOM_WCF_BITMAP, X11DRV_CLIPBOARD_ImportClipboardData, NULL},
193 { CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, X11DRV_CLIPBOARD_ImportMetaFilePict, X11DRV_CLIPBOARD_ExportMetaFilePict },
194 { CF_SYLK, XATOM_WCF_SYLK, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
195 { CF_DIF, XATOM_WCF_DIF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
196 { CF_TIFF, XATOM_WCF_TIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
197 { CF_OEMTEXT, XATOM_WCF_OEMTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
198 { CF_DIB, XA_PIXMAP, X11DRV_CLIPBOARD_ImportXAPIXMAP, X11DRV_CLIPBOARD_ExportXAPIXMAP },
199 { CF_PALETTE, XATOM_WCF_PALETTE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
200 { CF_PENDATA, XATOM_WCF_PENDATA, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
201 { CF_RIFF, XATOM_WCF_RIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
202 { CF_WAVE, XATOM_WCF_WAVE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
203 { CF_UNICODETEXT, XATOM_UTF8_STRING, X11DRV_CLIPBOARD_ImportUTF8, X11DRV_CLIPBOARD_ExportString },
204 /* If UTF8_STRING is not available, attempt COMPOUND_TEXT */
205 { CF_UNICODETEXT, XATOM_COMPOUND_TEXT, X11DRV_CLIPBOARD_ImportCompoundText, X11DRV_CLIPBOARD_ExportString },
206 { CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, X11DRV_CLIPBOARD_ImportEnhMetaFile, X11DRV_CLIPBOARD_ExportEnhMetaFile },
207 { CF_HDROP, XATOM_WCF_HDROP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
208 { CF_LOCALE, XATOM_WCF_LOCALE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
209 { CF_DIBV5, XATOM_WCF_DIBV5, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
210 { CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
211 { CF_DSPTEXT, XATOM_WCF_DSPTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
212 { CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
213 { CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
214 { CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
215 { CF_DIB, XATOM_image_bmp, X11DRV_CLIPBOARD_ImportImageBmp, X11DRV_CLIPBOARD_ExportImageBmp },
218 static struct list format_list = LIST_INIT( format_list );
220 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
222 /* Maps X properties to Windows formats */
223 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
224 static const WCHAR wszGIF[] = {'G','I','F',0};
225 static const WCHAR wszJFIF[] = {'J','F','I','F',0};
226 static const WCHAR wszPNG[] = {'P','N','G',0};
227 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
228 static const struct
230 LPCWSTR lpszFormat;
231 UINT prop;
232 } PropertyFormatMap[] =
234 { wszRichTextFormat, XATOM_text_rtf },
235 { wszRichTextFormat, XATOM_text_richtext },
236 { wszGIF, XATOM_image_gif },
237 { wszJFIF, XATOM_image_jpeg },
238 { wszPNG, XATOM_image_png },
239 { wszHTMLFormat, XATOM_HTML_Format }, /* prefer this to text/html */
244 * Cached clipboard data.
246 static struct list data_list = LIST_INIT( data_list );
247 static UINT ClipDataCount = 0;
250 * Clipboard sequence number
252 static UINT wSeqNo = 0;
254 /**************************************************************************
255 * Internal Clipboard implementation methods
256 **************************************************************************/
258 static Window thread_selection_wnd(void)
260 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
261 Window w = thread_data->selection_wnd;
263 if (!w)
265 XSetWindowAttributes attr;
267 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
268 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
270 wine_tsx11_lock();
271 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
272 InputOutput, CopyFromParent, CWEventMask, &attr);
273 wine_tsx11_unlock();
275 if (w)
276 thread_data->selection_wnd = w;
277 else
278 FIXME("Failed to create window. Fetching selection data will fail.\n");
281 return w;
284 static const char *debugstr_format( UINT id )
286 WCHAR buffer[256];
288 if (GetClipboardFormatNameW( id, buffer, 256 ))
289 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
291 switch (id)
293 #define BUILTIN(id) case id: return #id;
294 BUILTIN(CF_TEXT)
295 BUILTIN(CF_BITMAP)
296 BUILTIN(CF_METAFILEPICT)
297 BUILTIN(CF_SYLK)
298 BUILTIN(CF_DIF)
299 BUILTIN(CF_TIFF)
300 BUILTIN(CF_OEMTEXT)
301 BUILTIN(CF_DIB)
302 BUILTIN(CF_PALETTE)
303 BUILTIN(CF_PENDATA)
304 BUILTIN(CF_RIFF)
305 BUILTIN(CF_WAVE)
306 BUILTIN(CF_UNICODETEXT)
307 BUILTIN(CF_ENHMETAFILE)
308 BUILTIN(CF_HDROP)
309 BUILTIN(CF_LOCALE)
310 BUILTIN(CF_DIBV5)
311 BUILTIN(CF_OWNERDISPLAY)
312 BUILTIN(CF_DSPTEXT)
313 BUILTIN(CF_DSPBITMAP)
314 BUILTIN(CF_DSPMETAFILEPICT)
315 BUILTIN(CF_DSPENHMETAFILE)
316 #undef BUILTIN
317 default: return wine_dbg_sprintf( "%04x", id );
321 /**************************************************************************
322 * X11DRV_InitClipboard
324 void X11DRV_InitClipboard(void)
326 UINT i;
327 WINE_CLIPFORMAT *format;
329 /* Register built-in formats */
330 for (i = 0; i < sizeof(builtin_formats)/sizeof(builtin_formats[0]); i++)
332 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format )))) break;
333 format->wFormatID = builtin_formats[i].id;
334 format->drvData = GET_ATOM(builtin_formats[i].data);
335 format->wFlags = CF_FLAG_BUILTINFMT;
336 format->lpDrvImportFunc = builtin_formats[i].import;
337 format->lpDrvExportFunc = builtin_formats[i].export;
338 list_add_tail( &format_list, &format->entry );
341 /* Register known mapping between window formats and X properties */
342 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
343 X11DRV_CLIPBOARD_InsertClipboardFormat( GlobalAddAtomW(PropertyFormatMap[i].lpszFormat),
344 GET_ATOM(PropertyFormatMap[i].prop));
346 /* Set up a conversion function from "HTML Format" to "text/html" */
347 format = X11DRV_CLIPBOARD_InsertClipboardFormat( GlobalAddAtomW(wszHTMLFormat),
348 GET_ATOM(XATOM_text_html));
349 format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
353 /**************************************************************************
354 * intern_atoms
356 * Intern atoms for formats that don't have one yet.
358 static void intern_atoms(void)
360 LPWINE_CLIPFORMAT format;
361 int i, count, len;
362 char **names;
363 Atom *atoms;
364 Display *display;
365 WCHAR buffer[256];
367 count = 0;
368 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
369 if (!format->drvData) count++;
370 if (!count) return;
372 display = thread_init_display();
374 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
375 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
377 i = 0;
378 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
379 if (!format->drvData) {
380 GetClipboardFormatNameW( format->wFormatID, buffer, 256 );
381 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
382 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
383 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
386 wine_tsx11_lock();
387 XInternAtoms( display, names, count, False, atoms );
388 wine_tsx11_unlock();
390 i = 0;
391 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
392 if (!format->drvData) {
393 HeapFree(GetProcessHeap(), 0, names[i]);
394 format->drvData = atoms[i++];
397 HeapFree( GetProcessHeap(), 0, names );
398 HeapFree( GetProcessHeap(), 0, atoms );
402 /**************************************************************************
403 * register_format
405 * Register a custom X clipboard format.
407 static WINE_CLIPFORMAT *register_format( UINT id, Atom prop )
409 LPWINE_CLIPFORMAT lpFormat;
411 /* walk format chain to see if it's already registered */
412 LIST_FOR_EACH_ENTRY( lpFormat, &format_list, WINE_CLIPFORMAT, entry )
413 if ((lpFormat->wFormatID == id) && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
414 return lpFormat;
416 return X11DRV_CLIPBOARD_InsertClipboardFormat(id, prop);
420 /**************************************************************************
421 * X11DRV_CLIPBOARD_LookupProperty
423 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
425 for (;;)
427 struct list *ptr = current ? &current->entry : &format_list;
428 BOOL need_intern = FALSE;
430 while ((ptr = list_next( &format_list, ptr )))
432 LPWINE_CLIPFORMAT lpFormat = LIST_ENTRY( ptr, WINE_CLIPFORMAT, entry );
433 if (lpFormat->drvData == drvData) return lpFormat;
434 if (!lpFormat->drvData) need_intern = TRUE;
436 if (!need_intern) return NULL;
437 intern_atoms();
438 /* restart the search for the new atoms */
443 /**************************************************************************
444 * X11DRV_CLIPBOARD_LookupData
446 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
448 WINE_CLIPDATA *data;
450 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
451 if (data->wFormatID == wID) return data;
453 return NULL;
457 /**************************************************************************
458 * InsertClipboardFormat
460 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat( UINT id, Atom prop )
462 LPWINE_CLIPFORMAT lpNewFormat;
464 /* allocate storage for new format entry */
465 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
467 if(lpNewFormat == NULL)
469 WARN("No more memory for a new format!\n");
470 return NULL;
472 lpNewFormat->wFlags = 0;
473 lpNewFormat->wFormatID = id;
474 lpNewFormat->drvData = prop;
475 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
476 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
478 list_add_tail( &format_list, &lpNewFormat->entry );
480 TRACE("Registering format %s drvData %d\n",
481 debugstr_format(lpNewFormat->wFormatID), lpNewFormat->drvData);
483 return lpNewFormat;
489 /**************************************************************************
490 * X11DRV_CLIPBOARD_GetClipboardInfo
492 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
494 BOOL bRet = FALSE;
496 SERVER_START_REQ( set_clipboard_info )
498 req->flags = 0;
500 if (wine_server_call_err( req ))
502 ERR("Failed to get clipboard owner.\n");
504 else
506 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
507 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
508 cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
509 cbInfo->seqno = reply->seqno;
510 cbInfo->flags = reply->flags;
512 bRet = TRUE;
515 SERVER_END_REQ;
517 return bRet;
521 /**************************************************************************
522 * X11DRV_CLIPBOARD_ReleaseOwnership
524 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
526 BOOL bRet = FALSE;
528 SERVER_START_REQ( set_clipboard_info )
530 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
532 if (wine_server_call_err( req ))
534 ERR("Failed to set clipboard.\n");
536 else
538 bRet = TRUE;
541 SERVER_END_REQ;
543 return bRet;
548 /**************************************************************************
549 * X11DRV_CLIPBOARD_InsertClipboardData
551 * Caller *must* have the clipboard open and be the owner.
553 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData, DWORD flags,
554 LPWINE_CLIPFORMAT lpFormat, BOOL override)
556 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
558 TRACE("format=%04x lpData=%p hData=%p flags=0x%08x lpFormat=%p override=%d\n",
559 wFormatID, lpData, hData, flags, lpFormat, override);
561 if (lpData && !override)
562 return TRUE;
564 if (lpData)
566 X11DRV_CLIPBOARD_FreeData(lpData);
568 lpData->hData = hData;
570 else
572 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
574 lpData->wFormatID = wFormatID;
575 lpData->hData = hData;
576 lpData->lpFormat = lpFormat;
577 lpData->drvData = 0;
579 list_add_tail( &data_list, &lpData->entry );
580 ClipDataCount++;
583 lpData->wFlags = flags;
585 return TRUE;
589 /**************************************************************************
590 * X11DRV_CLIPBOARD_FreeData
592 * Free clipboard data handle.
594 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
596 TRACE("%04x\n", lpData->wFormatID);
598 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
599 lpData->wFormatID <= CF_GDIOBJLAST) ||
600 lpData->wFormatID == CF_BITMAP ||
601 lpData->wFormatID == CF_DIB ||
602 lpData->wFormatID == CF_PALETTE)
604 if (lpData->hData)
605 DeleteObject(lpData->hData);
607 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
608 XFreePixmap(gdi_display, lpData->drvData);
610 else if (lpData->wFormatID == CF_METAFILEPICT)
612 if (lpData->hData)
614 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
615 GlobalFree(lpData->hData);
618 else if (lpData->wFormatID == CF_ENHMETAFILE)
620 if (lpData->hData)
621 DeleteEnhMetaFile(lpData->hData);
623 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
624 lpData->wFormatID > CF_PRIVATELAST)
626 if (lpData->hData)
627 GlobalFree(lpData->hData);
630 lpData->hData = 0;
631 lpData->drvData = 0;
635 /**************************************************************************
636 * X11DRV_CLIPBOARD_UpdateCache
638 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
640 BOOL bret = TRUE;
642 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
644 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
646 ERR("Failed to retrieve clipboard information.\n");
647 bret = FALSE;
649 else if (wSeqNo < lpcbinfo->seqno)
651 X11DRV_EmptyClipboard(TRUE);
653 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
655 ERR("Failed to cache clipboard data owned by another process.\n");
656 bret = FALSE;
658 else
660 X11DRV_EndClipboardUpdate();
663 wSeqNo = lpcbinfo->seqno;
667 return bret;
671 /**************************************************************************
672 * X11DRV_CLIPBOARD_RenderFormat
674 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
676 BOOL bret = TRUE;
678 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
680 if (lpData->hData) return bret; /* Already rendered */
682 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
683 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
684 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
686 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
688 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
689 lpData->wFormatID);
690 bret = FALSE;
693 else
695 CLIPBOARDINFO cbInfo;
697 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
699 /* Send a WM_RENDERFORMAT message to notify the owner to render the
700 * data requested into the clipboard.
702 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
703 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, lpData->wFormatID, 0);
705 if (!lpData->hData) bret = FALSE;
707 else
709 ERR("hWndClipOwner is lost!\n");
710 bret = FALSE;
714 return bret;
718 /**************************************************************************
719 * CLIPBOARD_ConvertText
720 * Returns number of required/converted characters - not bytes!
722 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
723 WORD dst_fmt, void *dst, INT dst_size)
725 UINT cp;
727 if(src_fmt == CF_UNICODETEXT)
729 switch(dst_fmt)
731 case CF_TEXT:
732 cp = CP_ACP;
733 break;
734 case CF_OEMTEXT:
735 cp = CP_OEMCP;
736 break;
737 default:
738 return 0;
740 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
743 if(dst_fmt == CF_UNICODETEXT)
745 switch(src_fmt)
747 case CF_TEXT:
748 cp = CP_ACP;
749 break;
750 case CF_OEMTEXT:
751 cp = CP_OEMCP;
752 break;
753 default:
754 return 0;
756 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
759 if(!dst_size) return src_size;
761 if(dst_size > src_size) dst_size = src_size;
763 if(src_fmt == CF_TEXT )
764 CharToOemBuffA(src, dst, dst_size);
765 else
766 OemToCharBuffA(src, dst, dst_size);
768 return dst_size;
772 /**************************************************************************
773 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
775 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
777 BOOL bret = FALSE;
779 TRACE("\n");
781 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
783 UINT wFormatID = lpData->wFormatID;
785 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
786 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
787 else
789 switch (wFormatID)
791 case CF_DIB:
792 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
793 break;
795 case CF_BITMAP:
796 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
797 break;
799 case CF_ENHMETAFILE:
800 bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
801 break;
803 case CF_METAFILEPICT:
804 FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
805 break;
807 default:
808 FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
809 break;
813 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
816 return bret;
820 /**************************************************************************
821 * X11DRV_CLIPBOARD_RenderSynthesizedText
823 * Renders synthesized text
825 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
827 LPCSTR lpstrS;
828 LPSTR lpstrT;
829 HANDLE hData;
830 INT src_chars, dst_chars, alloc_size;
831 LPWINE_CLIPDATA lpSource = NULL;
833 TRACE("%04x\n", wFormatID);
835 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
836 lpSource->hData)
837 return TRUE;
839 /* Look for rendered source or non-synthesized source */
840 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
841 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
843 TRACE("UNICODETEXT -> %04x\n", wFormatID);
845 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
846 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
848 TRACE("TEXT -> %04x\n", wFormatID);
850 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
851 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
853 TRACE("OEMTEXT -> %04x\n", wFormatID);
856 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
857 !lpSource->hData))
858 return FALSE;
860 /* Ask the clipboard owner to render the source text if necessary */
861 if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
862 return FALSE;
864 lpstrS = GlobalLock(lpSource->hData);
865 if (!lpstrS)
866 return FALSE;
868 /* Text always NULL terminated */
869 if(lpSource->wFormatID == CF_UNICODETEXT)
870 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
871 else
872 src_chars = strlen(lpstrS) + 1;
874 /* Calculate number of characters in the destination buffer */
875 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
876 src_chars, wFormatID, NULL, 0);
878 if (!dst_chars)
879 return FALSE;
881 TRACE("Converting from '%04x' to '%04x', %i chars\n",
882 lpSource->wFormatID, wFormatID, src_chars);
884 /* Convert characters to bytes */
885 if(wFormatID == CF_UNICODETEXT)
886 alloc_size = dst_chars * sizeof(WCHAR);
887 else
888 alloc_size = dst_chars;
890 hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
891 GMEM_DDESHARE, alloc_size);
893 lpstrT = GlobalLock(hData);
895 if (lpstrT)
897 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
898 wFormatID, lpstrT, dst_chars);
899 GlobalUnlock(hData);
902 GlobalUnlock(lpSource->hData);
904 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
908 /**************************************************************************
909 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
911 * Renders synthesized DIB
913 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
915 BOOL bret = FALSE;
916 LPWINE_CLIPDATA lpSource = NULL;
918 TRACE("\n");
920 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
922 bret = TRUE;
924 /* If we have a bitmap and it's not synthesized or it has been rendered */
925 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
926 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
928 /* Render source if required */
929 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
931 HDC hdc;
932 HGLOBAL hData;
934 hdc = GetDC(NULL);
935 hData = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData);
936 ReleaseDC(NULL, hdc);
938 if (hData)
940 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
941 bret = TRUE;
946 return bret;
950 /**************************************************************************
951 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
953 * Renders synthesized bitmap
955 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
957 BOOL bret = FALSE;
958 LPWINE_CLIPDATA lpSource = NULL;
960 TRACE("\n");
962 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
964 bret = TRUE;
966 /* If we have a dib and it's not synthesized or it has been rendered */
967 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
968 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
970 /* Render source if required */
971 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
973 HDC hdc;
974 HBITMAP hData = NULL;
975 unsigned int offset;
976 LPBITMAPINFOHEADER lpbmih;
978 hdc = GetDC(NULL);
979 lpbmih = GlobalLock(lpSource->hData);
980 if (lpbmih)
982 offset = sizeof(BITMAPINFOHEADER)
983 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
984 (1 << lpbmih->biBitCount)) : 0);
986 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
987 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
989 GlobalUnlock(lpSource->hData);
991 ReleaseDC(NULL, hdc);
993 if (hData)
995 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
996 bret = TRUE;
1001 return bret;
1005 /**************************************************************************
1006 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1008 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1010 LPWINE_CLIPDATA lpSource = NULL;
1012 TRACE("\n");
1014 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1015 return TRUE;
1016 /* If we have a MF pict and it's not synthesized or it has been rendered */
1017 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1018 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1020 /* Render source if required */
1021 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1023 METAFILEPICT *pmfp;
1024 HENHMETAFILE hData = NULL;
1026 pmfp = GlobalLock(lpSource->hData);
1027 if (pmfp)
1029 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1030 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1031 if (mf_bits)
1033 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1034 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1035 HeapFree(GetProcessHeap(), 0, mf_bits);
1037 GlobalUnlock(lpSource->hData);
1040 if (hData)
1042 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1043 return TRUE;
1048 return FALSE;
1052 /**************************************************************************
1053 * X11DRV_CLIPBOARD_ImportXAString
1055 * Import XA_STRING, converting the string to CF_TEXT.
1057 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1059 LPBYTE lpdata;
1060 unsigned long cbytes;
1061 LPSTR lpstr;
1062 unsigned long i, inlcount = 0;
1063 HANDLE hText = 0;
1065 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1066 return 0;
1068 for (i = 0; i <= cbytes; i++)
1070 if (lpdata[i] == '\n')
1071 inlcount++;
1074 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1076 lpstr = GlobalLock(hText);
1078 for (i = 0, inlcount = 0; i <= cbytes; i++)
1080 if (lpdata[i] == '\n')
1081 lpstr[inlcount++] = '\r';
1083 lpstr[inlcount++] = lpdata[i];
1086 GlobalUnlock(hText);
1089 /* Free the retrieved property data */
1090 HeapFree(GetProcessHeap(), 0, lpdata);
1092 return hText;
1096 /**************************************************************************
1097 * X11DRV_CLIPBOARD_ImportUTF8
1099 * Import XA_STRING, converting the string to CF_UNICODE.
1101 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1103 LPBYTE lpdata;
1104 unsigned long cbytes;
1105 LPSTR lpstr;
1106 unsigned long i, inlcount = 0;
1107 HANDLE hUnicodeText = 0;
1109 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1110 return 0;
1112 for (i = 0; i <= cbytes; i++)
1114 if (lpdata[i] == '\n')
1115 inlcount++;
1118 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1120 UINT count;
1122 for (i = 0, inlcount = 0; i <= cbytes; i++)
1124 if (lpdata[i] == '\n')
1125 lpstr[inlcount++] = '\r';
1127 lpstr[inlcount++] = lpdata[i];
1130 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1131 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1133 if (hUnicodeText)
1135 WCHAR *textW = GlobalLock(hUnicodeText);
1136 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1137 GlobalUnlock(hUnicodeText);
1140 HeapFree(GetProcessHeap(), 0, lpstr);
1143 /* Free the retrieved property data */
1144 HeapFree(GetProcessHeap(), 0, lpdata);
1146 return hUnicodeText;
1150 /**************************************************************************
1151 * X11DRV_CLIPBOARD_ImportCompoundText
1153 * Import COMPOUND_TEXT to CF_UNICODE
1155 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1157 int i, j, ret;
1158 char** srcstr;
1159 int count, lcount;
1160 int srclen, destlen;
1161 HANDLE hUnicodeText;
1162 XTextProperty txtprop;
1164 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1166 return 0;
1169 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1170 txtprop.format = 8;
1171 wine_tsx11_lock();
1172 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1173 wine_tsx11_unlock();
1174 HeapFree(GetProcessHeap(), 0, txtprop.value);
1175 if (ret != Success || !count) return 0;
1177 TRACE("Importing %d line(s)\n", count);
1179 /* Compute number of lines */
1180 srclen = strlen(srcstr[0]);
1181 for (i = 0, lcount = 0; i <= srclen; i++)
1183 if (srcstr[0][i] == '\n')
1184 lcount++;
1187 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1189 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1191 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1193 WCHAR *deststr = GlobalLock(hUnicodeText);
1194 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1196 if (lcount)
1198 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1200 deststr[j] = deststr[i];
1202 if (deststr[i] == '\n')
1203 deststr[--j] = '\r';
1207 GlobalUnlock(hUnicodeText);
1210 wine_tsx11_lock();
1211 XFreeStringList(srcstr);
1212 wine_tsx11_unlock();
1214 return hUnicodeText;
1218 /**************************************************************************
1219 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1221 * Import XA_PIXMAP, converting the image to CF_DIB.
1223 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1225 HWND hwnd;
1226 HDC hdc;
1227 LPBYTE lpdata;
1228 unsigned long cbytes;
1229 Pixmap *pPixmap;
1230 HANDLE hClipData = 0;
1232 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1234 pPixmap = (Pixmap *) lpdata;
1236 hwnd = GetOpenClipboardWindow();
1237 hdc = GetDC(hwnd);
1239 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1240 ReleaseDC(hwnd, hdc);
1242 /* Free the retrieved property data */
1243 HeapFree(GetProcessHeap(), 0, lpdata);
1246 return hClipData;
1250 /**************************************************************************
1251 * X11DRV_CLIPBOARD_ImportImageBmp
1253 * Import image/bmp, converting the image to CF_DIB.
1255 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1257 LPBYTE lpdata;
1258 unsigned long cbytes;
1259 HANDLE hClipData = 0;
1261 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1263 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1265 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1266 bfh->bfType == 0x4d42 /* "BM" */)
1268 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1269 HBITMAP hbmp;
1270 HDC hdc;
1272 hdc = GetDC(0);
1273 hbmp = CreateDIBitmap(
1274 hdc,
1275 &(bmi->bmiHeader),
1276 CBM_INIT,
1277 lpdata+bfh->bfOffBits,
1278 bmi,
1279 DIB_RGB_COLORS
1282 hClipData = X11DRV_DIB_CreateDIBFromBitmap(hdc, hbmp);
1284 DeleteObject(hbmp);
1285 ReleaseDC(0, hdc);
1288 /* Free the retrieved property data */
1289 HeapFree(GetProcessHeap(), 0, lpdata);
1292 return hClipData;
1296 /**************************************************************************
1297 * X11DRV_CLIPBOARD_ImportMetaFilePict
1299 * Import MetaFilePict.
1301 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1303 LPBYTE lpdata;
1304 unsigned long cbytes;
1305 HANDLE hClipData = 0;
1307 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1309 if (cbytes)
1310 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1312 /* Free the retrieved property data */
1313 HeapFree(GetProcessHeap(), 0, lpdata);
1316 return hClipData;
1320 /**************************************************************************
1321 * X11DRV_ImportEnhMetaFile
1323 * Import EnhMetaFile.
1325 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1327 LPBYTE lpdata;
1328 unsigned long cbytes;
1329 HANDLE hClipData = 0;
1331 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1333 if (cbytes)
1334 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1336 /* Free the retrieved property data */
1337 HeapFree(GetProcessHeap(), 0, lpdata);
1340 return hClipData;
1344 /**************************************************************************
1345 * X11DRV_ImportClipbordaData
1347 * Generic import clipboard data routine.
1349 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1351 LPVOID lpClipData;
1352 LPBYTE lpdata;
1353 unsigned long cbytes;
1354 HANDLE hClipData = 0;
1356 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1358 if (cbytes)
1360 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1361 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1362 if (hClipData == 0)
1363 return NULL;
1365 if ((lpClipData = GlobalLock(hClipData)))
1367 memcpy(lpClipData, lpdata, cbytes);
1368 GlobalUnlock(hClipData);
1370 else
1372 GlobalFree(hClipData);
1373 hClipData = 0;
1377 /* Free the retrieved property data */
1378 HeapFree(GetProcessHeap(), 0, lpdata);
1381 return hClipData;
1385 /**************************************************************************
1386 X11DRV_CLIPBOARD_ExportClipboardData
1388 * Generic export clipboard data routine.
1390 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1391 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1393 LPVOID lpClipData;
1394 UINT datasize = 0;
1395 HANDLE hClipData = 0;
1397 *lpBytes = 0; /* Assume failure */
1399 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1400 ERR("Failed to export %04x format\n", lpData->wFormatID);
1401 else
1403 datasize = GlobalSize(lpData->hData);
1405 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1406 if (hClipData == 0) return NULL;
1408 if ((lpClipData = GlobalLock(hClipData)))
1410 LPVOID lpdata = GlobalLock(lpData->hData);
1412 memcpy(lpClipData, lpdata, datasize);
1413 *lpBytes = datasize;
1415 GlobalUnlock(lpData->hData);
1416 GlobalUnlock(hClipData);
1417 } else {
1418 GlobalFree(hClipData);
1419 hClipData = 0;
1423 return hClipData;
1427 /**************************************************************************
1428 * X11DRV_CLIPBOARD_ExportXAString
1430 * Export CF_TEXT converting the string to XA_STRING.
1431 * Helper function for X11DRV_CLIPBOARD_ExportString.
1433 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1435 UINT i, j;
1436 UINT size;
1437 LPSTR text, lpstr = NULL;
1439 *lpBytes = 0; /* Assume return has zero bytes */
1441 text = GlobalLock(lpData->hData);
1442 size = strlen(text);
1444 /* remove carriage returns */
1445 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1446 if (lpstr == NULL)
1447 goto done;
1449 for (i = 0,j = 0; i < size && text[i]; i++)
1451 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1452 continue;
1453 lpstr[j++] = text[i];
1456 lpstr[j]='\0';
1457 *lpBytes = j; /* Number of bytes in string */
1459 done:
1460 GlobalUnlock(lpData->hData);
1462 return lpstr;
1466 /**************************************************************************
1467 * X11DRV_CLIPBOARD_ExportUTF8String
1469 * Export CF_UNICODE converting the string to UTF8.
1470 * Helper function for X11DRV_CLIPBOARD_ExportString.
1472 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1474 UINT i, j;
1475 UINT size;
1476 LPWSTR uni_text;
1477 LPSTR text, lpstr = NULL;
1479 *lpBytes = 0; /* Assume return has zero bytes */
1481 uni_text = GlobalLock(lpData->hData);
1483 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1485 text = HeapAlloc(GetProcessHeap(), 0, size);
1486 if (!text)
1487 goto done;
1488 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1490 /* remove carriage returns */
1491 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1492 if (lpstr == NULL)
1493 goto done;
1495 for (i = 0,j = 0; i < size && text[i]; i++)
1497 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1498 continue;
1499 lpstr[j++] = text[i];
1501 lpstr[j]='\0';
1503 *lpBytes = j; /* Number of bytes in string */
1505 done:
1506 HeapFree(GetProcessHeap(), 0, text);
1507 GlobalUnlock(lpData->hData);
1509 return lpstr;
1514 /**************************************************************************
1515 * X11DRV_CLIPBOARD_ExportCompoundText
1517 * Export CF_UNICODE to COMPOUND_TEXT
1518 * Helper function for X11DRV_CLIPBOARD_ExportString.
1520 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1521 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1523 char* lpstr = 0;
1524 XTextProperty prop;
1525 XICCEncodingStyle style;
1526 UINT i, j;
1527 UINT size;
1528 LPWSTR uni_text;
1530 uni_text = GlobalLock(lpData->hData);
1532 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1533 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1534 if (!lpstr)
1535 return 0;
1537 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1539 /* remove carriage returns */
1540 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1542 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1543 continue;
1544 lpstr[j++] = lpstr[i];
1546 lpstr[j]='\0';
1548 GlobalUnlock(lpData->hData);
1550 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1551 style = XCompoundTextStyle;
1552 else
1553 style = XStdICCTextStyle;
1555 /* Update the X property */
1556 wine_tsx11_lock();
1557 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1559 XSetTextProperty(display, requestor, &prop, rprop);
1560 XFree(prop.value);
1562 wine_tsx11_unlock();
1564 HeapFree(GetProcessHeap(), 0, lpstr);
1566 return 0;
1569 /**************************************************************************
1570 * X11DRV_CLIPBOARD_ExportString
1572 * Export string
1574 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1575 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1577 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1579 if (aTarget == XA_STRING)
1580 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1581 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1582 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1583 rprop, lpData, lpBytes);
1584 else
1586 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1587 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1590 else
1591 ERR("Failed to render %04x format\n", lpData->wFormatID);
1593 return 0;
1597 /**************************************************************************
1598 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1600 * Export CF_DIB to XA_PIXMAP.
1602 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1603 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1605 HDC hdc;
1606 HANDLE hData;
1607 unsigned char* lpData;
1609 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1611 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1612 return 0;
1615 if (!lpdata->drvData) /* If not already rendered */
1617 /* For convert from packed DIB to Pixmap */
1618 hdc = GetDC(0);
1619 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData, hdc);
1620 ReleaseDC(0, hdc);
1623 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1625 /* Wrap pixmap so we can return a handle */
1626 hData = GlobalAlloc(0, *lpBytes);
1627 lpData = GlobalLock(hData);
1628 memcpy(lpData, &lpdata->drvData, *lpBytes);
1629 GlobalUnlock(hData);
1631 return hData;
1635 /**************************************************************************
1636 * X11DRV_CLIPBOARD_ExportImageBmp
1638 * Export CF_DIB to image/bmp.
1640 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1641 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1643 HANDLE hpackeddib;
1644 LPBYTE dibdata;
1645 UINT bmpsize;
1646 HANDLE hbmpdata;
1647 LPBYTE bmpdata;
1648 BITMAPFILEHEADER *bfh;
1650 *lpBytes = 0;
1652 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1654 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1655 return 0;
1658 hpackeddib = lpdata->hData;
1660 dibdata = GlobalLock(hpackeddib);
1661 if (!dibdata)
1663 ERR("Failed to lock packed DIB\n");
1664 return 0;
1667 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1669 hbmpdata = GlobalAlloc(0, bmpsize);
1671 if (hbmpdata)
1673 bmpdata = GlobalLock(hbmpdata);
1675 if (!bmpdata)
1677 GlobalFree(hbmpdata);
1678 GlobalUnlock(hpackeddib);
1679 return 0;
1682 /* bitmap file header */
1683 bfh = (BITMAPFILEHEADER*)bmpdata;
1684 bfh->bfType = 0x4d42; /* "BM" */
1685 bfh->bfSize = bmpsize;
1686 bfh->bfReserved1 = 0;
1687 bfh->bfReserved2 = 0;
1688 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1690 /* rest of bitmap is the same as the packed dib */
1691 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1693 *lpBytes = bmpsize;
1695 GlobalUnlock(hbmpdata);
1698 GlobalUnlock(hpackeddib);
1700 return hbmpdata;
1704 /**************************************************************************
1705 * X11DRV_CLIPBOARD_ExportMetaFilePict
1707 * Export MetaFilePict.
1709 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1710 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1712 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1714 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1715 return 0;
1718 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
1722 /**************************************************************************
1723 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1725 * Export EnhMetaFile.
1727 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1728 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1730 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1732 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1733 return 0;
1736 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
1740 /**************************************************************************
1741 * get_html_description_field
1743 * Find the value of a field in an HTML Format description.
1745 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1747 LPCSTR pos=data;
1749 while (pos && *pos && *pos != '<')
1751 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1752 return pos+strlen(keyword);
1754 pos = strchr(pos, '\n');
1755 if (pos) pos++;
1758 return NULL;
1762 /**************************************************************************
1763 * X11DRV_CLIPBOARD_ExportTextHtml
1765 * Export HTML Format to text/html.
1767 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1769 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
1770 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1772 HANDLE hdata;
1773 LPCSTR data, field_value;
1774 UINT fragmentstart, fragmentend, htmlsize;
1775 HANDLE hhtmldata=NULL;
1776 LPSTR htmldata;
1778 *lpBytes = 0;
1780 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1782 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1783 return 0;
1786 hdata = lpdata->hData;
1788 data = GlobalLock(hdata);
1789 if (!data)
1791 ERR("Failed to lock HTML Format data\n");
1792 return 0;
1795 /* read the important fields */
1796 field_value = get_html_description_field(data, "StartFragment:");
1797 if (!field_value)
1799 ERR("Couldn't find StartFragment value\n");
1800 goto end;
1802 fragmentstart = atoi(field_value);
1804 field_value = get_html_description_field(data, "EndFragment:");
1805 if (!field_value)
1807 ERR("Couldn't find EndFragment value\n");
1808 goto end;
1810 fragmentend = atoi(field_value);
1812 /* export only the fragment */
1813 htmlsize = fragmentend - fragmentstart + 1;
1815 hhtmldata = GlobalAlloc(0, htmlsize);
1817 if (hhtmldata)
1819 htmldata = GlobalLock(hhtmldata);
1821 if (!htmldata)
1823 GlobalFree(hhtmldata);
1824 htmldata = NULL;
1825 goto end;
1828 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1829 htmldata[htmlsize-1] = '\0';
1831 *lpBytes = htmlsize;
1833 GlobalUnlock(htmldata);
1836 end:
1838 GlobalUnlock(hdata);
1840 return hhtmldata;
1844 /**************************************************************************
1845 * X11DRV_CLIPBOARD_QueryTargets
1847 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1848 Atom target, XEvent *xe)
1850 INT i;
1851 Bool res;
1853 wine_tsx11_lock();
1854 XConvertSelection(display, selection, target,
1855 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1856 wine_tsx11_unlock();
1859 * Wait until SelectionNotify is received
1861 for (i = 0; i < SELECTION_RETRIES; i++)
1863 wine_tsx11_lock();
1864 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1865 wine_tsx11_unlock();
1866 if (res && xe->xselection.selection == selection) break;
1868 usleep(SELECTION_WAIT);
1871 if (i == SELECTION_RETRIES)
1873 ERR("Timed out waiting for SelectionNotify event\n");
1874 return FALSE;
1876 /* Verify that the selection returned a valid TARGETS property */
1877 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1879 /* Selection owner failed to respond or we missed the SelectionNotify */
1880 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1881 return FALSE;
1884 return TRUE;
1888 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1890 return (event->error_code == BadAtom);
1893 /**************************************************************************
1894 * X11DRV_CLIPBOARD_InsertSelectionProperties
1896 * Mark properties available for future retrieval.
1898 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1900 UINT i, nb_atoms = 0;
1901 Atom *atoms = NULL;
1903 /* Cache these formats in the clipboard cache */
1904 for (i = 0; i < count; i++)
1906 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1908 if (lpFormat)
1910 /* We found at least one Window's format that mapps to the property.
1911 * Continue looking for more.
1913 * If more than one property map to a Window's format then we use the first
1914 * one and ignore the rest.
1916 while (lpFormat)
1918 TRACE("Atom#%d Property(%d): --> Format %s\n",
1919 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
1920 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
1921 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1924 else if (properties[i])
1926 /* add it to the list of atoms that we don't know about yet */
1927 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1928 (count - i) * sizeof(*atoms) );
1929 if (atoms) atoms[nb_atoms++] = properties[i];
1933 /* query all unknown atoms in one go */
1934 if (atoms)
1936 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1937 if (names)
1939 X11DRV_expect_error( display, is_atom_error, NULL );
1940 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1941 if (X11DRV_check_error())
1943 WARN( "got some bad atoms, ignoring\n" );
1944 nb_atoms = 0;
1946 for (i = 0; i < nb_atoms; i++)
1948 WINE_CLIPFORMAT *lpFormat;
1949 LPWSTR wname;
1950 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1951 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1952 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1954 lpFormat = register_format( GlobalAddAtomW(wname), atoms[i] );
1955 HeapFree(GetProcessHeap(), 0, wname);
1956 if (!lpFormat)
1958 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1959 continue;
1961 TRACE("Atom#%d Property(%d): --> Format %s\n",
1962 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
1963 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
1965 wine_tsx11_lock();
1966 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1967 wine_tsx11_unlock();
1968 HeapFree( GetProcessHeap(), 0, names );
1970 HeapFree( GetProcessHeap(), 0, atoms );
1975 /**************************************************************************
1976 * X11DRV_CLIPBOARD_QueryAvailableData
1978 * Caches the list of data formats available from the current selection.
1979 * This queries the selection owner for the TARGETS property and saves all
1980 * reported property types.
1982 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1984 XEvent xe;
1985 Atom atype=AnyPropertyType;
1986 int aformat;
1987 unsigned long remain;
1988 Atom* targetList=NULL;
1989 Window w;
1990 unsigned long cSelectionTargets = 0;
1992 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1994 ERR("Received request to cache selection but process is owner=(%08x)\n",
1995 (unsigned) selectionWindow);
1996 return -1; /* Prevent self request */
1999 w = thread_selection_wnd();
2000 if (!w)
2002 ERR("No window available to retrieve selection!\n");
2003 return -1;
2007 * Query the selection owner for the TARGETS property
2009 wine_tsx11_lock();
2010 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2011 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2013 wine_tsx11_unlock();
2014 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2015 selectionCacheSrc = XA_PRIMARY;
2016 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2017 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2018 else
2020 Atom xstr = XA_STRING;
2022 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2023 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2025 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2026 selectionCacheSrc = XA_PRIMARY;
2027 return 1;
2029 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2031 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2032 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2033 return 1;
2035 else
2037 WARN("Failed to query selection owner for available data.\n");
2038 return -1;
2042 else /* No selection owner so report 0 targets available */
2044 wine_tsx11_unlock();
2045 return 0;
2048 /* Read the TARGETS property contents */
2049 wine_tsx11_lock();
2050 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2051 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2052 &remain, (unsigned char**)&targetList) != Success)
2054 wine_tsx11_unlock();
2055 WARN("Failed to read TARGETS property\n");
2057 else
2059 wine_tsx11_unlock();
2060 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2061 atype, aformat, cSelectionTargets, remain);
2063 * The TARGETS property should have returned us a list of atoms
2064 * corresponding to each selection target format supported.
2066 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2068 if (aformat == 32)
2070 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2072 else if (aformat == 8) /* work around quartz-wm brain damage */
2074 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2075 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2076 for (i = 0; i < count; i++)
2077 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2078 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2079 HeapFree( GetProcessHeap(), 0, atoms );
2083 /* Free the list of targets */
2084 wine_tsx11_lock();
2085 XFree(targetList);
2086 wine_tsx11_unlock();
2089 return cSelectionTargets;
2093 /**************************************************************************
2094 * X11DRV_CLIPBOARD_ReadSelectionData
2096 * This method is invoked only when we DO NOT own the X selection
2098 * We always get the data from the selection client each time,
2099 * since we have no way of determining if the data in our cache is stale.
2101 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2103 Bool res;
2104 DWORD i;
2105 XEvent xe;
2106 BOOL bRet = FALSE;
2108 TRACE("%04x\n", lpData->wFormatID);
2110 if (!lpData->lpFormat)
2112 ERR("Requesting format %04x but no source format linked to data.\n",
2113 lpData->wFormatID);
2114 return FALSE;
2117 if (!selectionAcquired)
2119 Window w = thread_selection_wnd();
2120 if(!w)
2122 ERR("No window available to read selection data!\n");
2123 return FALSE;
2126 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2127 debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2128 (UINT)selectionCacheSrc);
2130 wine_tsx11_lock();
2131 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2132 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2133 wine_tsx11_unlock();
2135 /* wait until SelectionNotify is received */
2136 for (i = 0; i < SELECTION_RETRIES; i++)
2138 wine_tsx11_lock();
2139 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2140 wine_tsx11_unlock();
2141 if (res && xe.xselection.selection == selectionCacheSrc) break;
2143 usleep(SELECTION_WAIT);
2146 if (i == SELECTION_RETRIES)
2148 ERR("Timed out waiting for SelectionNotify event\n");
2150 /* Verify that the selection returned a valid TARGETS property */
2151 else if (xe.xselection.property != None)
2154 * Read the contents of the X selection property
2155 * into WINE's clipboard cache and converting the
2156 * data format if necessary.
2158 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2159 xe.xselection.property);
2161 if (hData)
2162 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2163 else
2164 TRACE("Import function failed\n");
2166 else
2168 TRACE("Failed to convert selection\n");
2171 else
2173 ERR("Received request to cache selection data but process is owner\n");
2176 TRACE("Returning %d\n", bRet);
2178 return bRet;
2182 /**************************************************************************
2183 * X11DRV_CLIPBOARD_GetProperty
2184 * Gets type, data and size.
2186 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2187 Atom *atype, unsigned char** data, unsigned long* datasize)
2189 int aformat;
2190 unsigned long pos = 0, nitems, remain, count;
2191 unsigned char *val = NULL, *buffer;
2193 TRACE("Reading property %lu from X window %lx\n", prop, w);
2195 for (;;)
2197 wine_tsx11_lock();
2198 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2199 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2201 wine_tsx11_unlock();
2202 WARN("Failed to read property\n");
2203 HeapFree( GetProcessHeap(), 0, val );
2204 return FALSE;
2207 count = get_property_size( aformat, nitems );
2208 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2209 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2211 if (!*data)
2213 XFree( buffer );
2214 wine_tsx11_unlock();
2215 HeapFree( GetProcessHeap(), 0, val );
2216 return FALSE;
2218 val = *data;
2219 memcpy( (int *)val + pos, buffer, count );
2220 XFree( buffer );
2221 wine_tsx11_unlock();
2222 if (!remain)
2224 *datasize = pos * sizeof(int) + count;
2225 val[*datasize] = 0;
2226 break;
2228 pos += count / sizeof(int);
2231 /* Delete the property on the window now that we are done
2232 * This will send a PropertyNotify event to the selection owner. */
2233 wine_tsx11_lock();
2234 XDeleteProperty(display, w, prop);
2235 wine_tsx11_unlock();
2236 return TRUE;
2240 /**************************************************************************
2241 * X11DRV_CLIPBOARD_ReadProperty
2242 * Reads the contents of the X selection property.
2244 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2245 unsigned char** data, unsigned long* datasize)
2247 Atom atype;
2248 XEvent xe;
2250 if (prop == None)
2251 return FALSE;
2253 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2254 return FALSE;
2256 wine_tsx11_lock();
2257 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2259 wine_tsx11_unlock();
2261 if (atype == x11drv_atom(INCR))
2263 unsigned char *buf = *data;
2264 unsigned long bufsize = 0;
2266 for (;;)
2268 int i;
2269 unsigned char *prop_data, *tmp;
2270 unsigned long prop_size;
2272 /* Wait until PropertyNotify is received */
2273 for (i = 0; i < SELECTION_RETRIES; i++)
2275 Bool res;
2277 wine_tsx11_lock();
2278 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2279 wine_tsx11_unlock();
2280 if (res && xe.xproperty.atom == prop &&
2281 xe.xproperty.state == PropertyNewValue)
2282 break;
2283 usleep(SELECTION_WAIT);
2286 if (i >= SELECTION_RETRIES ||
2287 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2289 HeapFree(GetProcessHeap(), 0, buf);
2290 return FALSE;
2293 /* Retrieved entire data. */
2294 if (prop_size == 0)
2296 HeapFree(GetProcessHeap(), 0, prop_data);
2297 *data = buf;
2298 *datasize = bufsize;
2299 return TRUE;
2302 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2303 if (!tmp)
2305 HeapFree(GetProcessHeap(), 0, buf);
2306 return FALSE;
2309 buf = tmp;
2310 memcpy(buf + bufsize, prop_data, prop_size + 1);
2311 bufsize += prop_size;
2312 HeapFree(GetProcessHeap(), 0, prop_data);
2316 return TRUE;
2320 /**************************************************************************
2321 * CLIPBOARD_SerializeMetafile
2323 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2325 HANDLE h = 0;
2327 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2329 if (out) /* Serialize out, caller should free memory */
2331 *lpcbytes = 0; /* Assume failure */
2333 if (wformat == CF_METAFILEPICT)
2335 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2336 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2338 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2339 if (h)
2341 char *pdata = GlobalLock(h);
2343 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2344 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2346 *lpcbytes = size + sizeof(METAFILEPICT);
2348 GlobalUnlock(h);
2351 GlobalUnlock(hdata);
2353 else if (wformat == CF_ENHMETAFILE)
2355 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2357 h = GlobalAlloc(0, size);
2358 if (h)
2360 LPVOID pdata = GlobalLock(h);
2362 GetEnhMetaFileBits(hdata, size, pdata);
2363 *lpcbytes = size;
2365 GlobalUnlock(h);
2369 else
2371 if (wformat == CF_METAFILEPICT)
2373 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2374 if (h)
2376 unsigned int wiresize;
2377 LPMETAFILEPICT lpmfp = GlobalLock(h);
2379 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2380 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2381 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2382 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2383 GlobalUnlock(h);
2386 else if (wformat == CF_ENHMETAFILE)
2388 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2392 return h;
2396 /**************************************************************************
2397 * X11DRV_CLIPBOARD_ReleaseSelection
2399 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2401 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2403 /* w is the window that lost the selection
2405 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2406 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2408 if (selectionAcquired && (w == selectionWindow))
2410 CLIPBOARDINFO cbinfo;
2412 /* completely give up the selection */
2413 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2415 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2417 if (cbinfo.flags & CB_PROCESS)
2419 /* Since we're still the owner, this wasn't initiated by
2420 another Wine process */
2421 if (OpenClipboard(hwnd))
2423 /* Destroy private objects */
2424 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2426 /* Give up ownership of the windows clipboard */
2427 X11DRV_CLIPBOARD_ReleaseOwnership();
2428 CloseClipboard();
2432 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2434 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2436 wine_tsx11_lock();
2437 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2439 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2440 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2442 else
2443 TRACE("We no longer own PRIMARY\n");
2444 wine_tsx11_unlock();
2446 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2448 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2450 wine_tsx11_lock();
2451 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2453 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2454 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2456 else
2457 TRACE("We no longer own CLIPBOARD\n");
2458 wine_tsx11_unlock();
2461 selectionWindow = None;
2463 X11DRV_EmptyClipboard(FALSE);
2465 /* Reset the selection flags now that we are done */
2466 selectionAcquired = S_NOSELECTION;
2471 /**************************************************************************
2472 * IsSelectionOwner (X11DRV.@)
2474 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2476 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2478 return selectionAcquired;
2482 /**************************************************************************
2483 * X11DRV Clipboard Exports
2484 **************************************************************************/
2487 /**************************************************************************
2488 * RegisterClipboardFormat (X11DRV.@)
2490 * Registers a custom X clipboard format
2491 * Returns: Format id or 0 on failure
2493 UINT CDECL X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2495 UINT id = GlobalAddAtomW( FormatName );
2497 if (!id) return 0;
2498 if (!register_format( id, 0 )) return 0;
2499 return id;
2503 static void selection_acquire(void)
2505 Window owner;
2506 Display *display;
2508 owner = thread_selection_wnd();
2509 display = thread_display();
2511 wine_tsx11_lock();
2513 selectionAcquired = 0;
2514 selectionWindow = 0;
2516 /* Grab PRIMARY selection if not owned */
2517 if (use_primary_selection)
2518 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2520 /* Grab CLIPBOARD selection if not owned */
2521 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2523 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2524 selectionAcquired |= S_PRIMARY;
2526 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2527 selectionAcquired |= S_CLIPBOARD;
2529 wine_tsx11_unlock();
2531 if (selectionAcquired)
2533 selectionWindow = owner;
2534 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2538 static DWORD WINAPI selection_thread_proc(LPVOID p)
2540 HANDLE event = p;
2542 TRACE("\n");
2544 selection_acquire();
2545 SetEvent(event);
2547 while (selectionAcquired)
2549 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2552 return 0;
2555 /**************************************************************************
2556 * AcquireClipboard (X11DRV.@)
2558 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2560 DWORD procid;
2561 HANDLE selectionThread;
2563 TRACE(" %p\n", hWndClipWindow);
2566 * It's important that the selection get acquired from the thread
2567 * that owns the clipboard window. The primary reason is that we know
2568 * it is running a message loop and therefore can process the
2569 * X selection events.
2571 if (hWndClipWindow &&
2572 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2574 if (procid != GetCurrentProcessId())
2576 WARN("Setting clipboard owner to other process is not supported\n");
2577 hWndClipWindow = NULL;
2579 else
2581 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2582 GetCurrentThreadId(),
2583 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2585 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2589 if (hWndClipWindow)
2591 selection_acquire();
2593 else
2595 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2596 selectionThread = CreateThread(NULL, 0, &selection_thread_proc, event, 0, NULL);
2598 if (!selectionThread)
2600 WARN("Could not start clipboard thread\n");
2601 return 0;
2604 WaitForSingleObject(event, INFINITE);
2605 CloseHandle(event);
2606 CloseHandle(selectionThread);
2609 return 1;
2613 /**************************************************************************
2614 * X11DRV_EmptyClipboard
2616 * Empty cached clipboard data.
2618 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2620 WINE_CLIPDATA *data, *next;
2622 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2624 if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2625 list_remove( &data->entry );
2626 X11DRV_CLIPBOARD_FreeData( data );
2627 HeapFree( GetProcessHeap(), 0, data );
2628 ClipDataCount--;
2631 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2636 /**************************************************************************
2637 * X11DRV_SetClipboardData
2639 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2641 DWORD flags = 0;
2642 BOOL bResult = TRUE;
2644 /* If it's not owned, data can only be set if the format data is not already owned
2645 and its rendering is not delayed */
2646 if (!owner)
2648 CLIPBOARDINFO cbinfo;
2649 LPWINE_CLIPDATA lpRender;
2651 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2653 if (!hData ||
2654 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2655 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2656 bResult = FALSE;
2657 else
2658 flags = CF_FLAG_UNOWNED;
2661 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
2663 return bResult;
2667 /**************************************************************************
2668 * CountClipboardFormats
2670 INT CDECL X11DRV_CountClipboardFormats(void)
2672 CLIPBOARDINFO cbinfo;
2674 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2676 TRACE(" count=%d\n", ClipDataCount);
2678 return ClipDataCount;
2682 /**************************************************************************
2683 * X11DRV_EnumClipboardFormats
2685 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2687 CLIPBOARDINFO cbinfo;
2688 struct list *ptr = NULL;
2690 TRACE("(%04X)\n", wFormat);
2692 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2694 if (!wFormat)
2696 ptr = list_head( &data_list );
2698 else
2700 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2701 if (lpData) ptr = list_next( &data_list, &lpData->entry );
2704 if (!ptr) return 0;
2705 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2709 /**************************************************************************
2710 * X11DRV_IsClipboardFormatAvailable
2712 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2714 BOOL bRet = FALSE;
2715 CLIPBOARDINFO cbinfo;
2717 TRACE("(%04X)\n", wFormat);
2719 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2721 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2722 bRet = TRUE;
2724 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2726 return bRet;
2730 /**************************************************************************
2731 * GetClipboardData (USER.142)
2733 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2735 CLIPBOARDINFO cbinfo;
2736 LPWINE_CLIPDATA lpRender;
2738 TRACE("(%04X)\n", wFormat);
2740 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2742 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2744 if ( !lpRender->hData )
2745 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2747 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2748 return lpRender->hData;
2751 return 0;
2755 /**************************************************************************
2756 * ResetSelectionOwner
2758 * Called when the thread owning the selection is destroyed and we need to
2759 * preserve the selection ownership. We look for another top level window
2760 * in this process and send it a message to acquire the selection.
2762 void X11DRV_ResetSelectionOwner(void)
2764 HWND hwnd;
2765 DWORD procid;
2767 TRACE("\n");
2769 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2770 return;
2772 selectionAcquired = S_NOSELECTION;
2773 selectionWindow = 0;
2775 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2778 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2780 if (GetCurrentProcessId() == procid)
2782 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2783 return;
2786 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2788 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2790 X11DRV_CLIPBOARD_ReleaseOwnership();
2791 X11DRV_EmptyClipboard(FALSE);
2795 /**************************************************************************
2796 * X11DRV_CLIPBOARD_SynthesizeData
2798 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2800 BOOL bsyn = TRUE;
2801 LPWINE_CLIPDATA lpSource = NULL;
2803 TRACE(" %04x\n", wFormatID);
2805 /* Don't need to synthesize if it already exists */
2806 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2807 return TRUE;
2809 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2811 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2812 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2813 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2814 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2815 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2816 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2818 else if (wFormatID == CF_ENHMETAFILE)
2820 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2821 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2823 else if (wFormatID == CF_METAFILEPICT)
2825 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2826 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2828 else if (wFormatID == CF_DIB)
2830 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2831 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2833 else if (wFormatID == CF_BITMAP)
2835 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2836 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2839 if (bsyn)
2840 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2842 return bsyn;
2847 /**************************************************************************
2848 * X11DRV_EndClipboardUpdate
2849 * TODO:
2850 * Add locale if it hasn't already been added
2852 void CDECL X11DRV_EndClipboardUpdate(void)
2854 INT count = ClipDataCount;
2856 /* Do Unicode <-> Text <-> OEM mapping */
2857 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2858 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2859 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2861 /* Enhmetafile <-> MetafilePict mapping */
2862 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2863 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2865 /* DIB <-> Bitmap mapping */
2866 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2867 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2869 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2873 /***********************************************************************
2874 * X11DRV_SelectionRequest_TARGETS
2875 * Service a TARGETS selection request event
2877 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2878 Atom target, Atom rprop )
2880 UINT i;
2881 Atom* targets;
2882 ULONG cTargets;
2883 LPWINE_CLIPFORMAT format;
2884 LPWINE_CLIPDATA lpData;
2886 /* Create X atoms for any clipboard types which don't have atoms yet.
2887 * This avoids sending bogus zero atoms.
2888 * Without this, copying might not have access to all clipboard types.
2889 * FIXME: is it safe to call this here?
2891 intern_atoms();
2894 * Count the number of items we wish to expose as selection targets.
2896 cTargets = 1; /* Include TARGETS */
2898 if (!list_head( &data_list )) return None;
2900 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2901 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2902 if ((format->wFormatID == lpData->wFormatID) &&
2903 format->lpDrvExportFunc && format->drvData)
2904 cTargets++;
2906 TRACE(" found %d formats\n", cTargets);
2908 /* Allocate temp buffer */
2909 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2910 if(targets == NULL)
2911 return None;
2913 i = 0;
2914 targets[i++] = x11drv_atom(TARGETS);
2916 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2917 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2918 if ((format->wFormatID == lpData->wFormatID) &&
2919 format->lpDrvExportFunc && format->drvData)
2920 targets[i++] = format->drvData;
2922 wine_tsx11_lock();
2924 if (TRACE_ON(clipboard))
2926 unsigned int i;
2927 for ( i = 0; i < cTargets; i++)
2929 char *itemFmtName = XGetAtomName(display, targets[i]);
2930 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2931 XFree(itemFmtName);
2935 /* We may want to consider setting the type to xaTargets instead,
2936 * in case some apps expect this instead of XA_ATOM */
2937 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2938 PropModeReplace, (unsigned char *)targets, cTargets);
2939 wine_tsx11_unlock();
2941 HeapFree(GetProcessHeap(), 0, targets);
2943 return rprop;
2947 /***********************************************************************
2948 * X11DRV_SelectionRequest_MULTIPLE
2949 * Service a MULTIPLE selection request event
2950 * rprop contains a list of (target,property) atom pairs.
2951 * The first atom names a target and the second names a property.
2952 * The effect is as if we have received a sequence of SelectionRequest events
2953 * (one for each atom pair) except that:
2954 * 1. We reply with a SelectionNotify only when all the requested conversions
2955 * have been performed.
2956 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2957 * we replace the atom in the property by None.
2959 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2961 Display *display = pevent->display;
2962 Atom rprop;
2963 Atom atype=AnyPropertyType;
2964 int aformat;
2965 unsigned long remain;
2966 Atom* targetPropList=NULL;
2967 unsigned long cTargetPropList = 0;
2969 /* If the specified property is None the requestor is an obsolete client.
2970 * We support these by using the specified target atom as the reply property.
2972 rprop = pevent->property;
2973 if( rprop == None )
2974 rprop = pevent->target;
2975 if (!rprop)
2976 return 0;
2978 /* Read the MULTIPLE property contents. This should contain a list of
2979 * (target,property) atom pairs.
2981 wine_tsx11_lock();
2982 if(XGetWindowProperty(display, pevent->requestor, rprop,
2983 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2984 &cTargetPropList, &remain,
2985 (unsigned char**)&targetPropList) != Success)
2987 wine_tsx11_unlock();
2988 TRACE("\tCouldn't read MULTIPLE property\n");
2990 else
2992 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2993 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2994 wine_tsx11_unlock();
2997 * Make sure we got what we expect.
2998 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2999 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3000 * However some X apps(such as XPaint) are not compliant with this and return
3001 * a user defined atom in atype when XGetWindowProperty is called.
3002 * The data *is* an atom pair but is not denoted as such.
3004 if(aformat == 32 /* atype == xAtomPair */ )
3006 unsigned int i;
3008 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3009 * for each (target,property) pair */
3011 for (i = 0; i < cTargetPropList; i+=2)
3013 XSelectionRequestEvent event;
3015 if (TRACE_ON(clipboard))
3017 char *targetName, *propName;
3018 wine_tsx11_lock();
3019 targetName = XGetAtomName(display, targetPropList[i]);
3020 propName = XGetAtomName(display, targetPropList[i+1]);
3021 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3022 i/2, targetName, propName);
3023 XFree(targetName);
3024 XFree(propName);
3025 wine_tsx11_unlock();
3028 /* We must have a non "None" property to service a MULTIPLE target atom */
3029 if ( !targetPropList[i+1] )
3031 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3032 continue;
3035 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3036 event = *pevent;
3037 event.target = targetPropList[i];
3038 event.property = targetPropList[i+1];
3040 /* Fire a SelectionRequest, informing the handler that we are processing
3041 * a MULTIPLE selection request event.
3043 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3047 /* Free the list of targets/properties */
3048 wine_tsx11_lock();
3049 XFree(targetPropList);
3050 wine_tsx11_unlock();
3053 return rprop;
3057 /***********************************************************************
3058 * X11DRV_HandleSelectionRequest
3059 * Process an event selection request event.
3060 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3061 * recursively while servicing a "MULTIPLE" selection target.
3063 * Note: We only receive this event when WINE owns the X selection
3065 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3067 Display *display = event->display;
3068 XSelectionEvent result;
3069 Atom rprop = None;
3070 Window request = event->requestor;
3072 TRACE("\n");
3075 * We can only handle the selection request if :
3076 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3077 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3078 * since this has been already done.
3080 if ( !bIsMultiple )
3082 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3083 goto END;
3086 /* If the specified property is None the requestor is an obsolete client.
3087 * We support these by using the specified target atom as the reply property.
3089 rprop = event->property;
3090 if( rprop == None )
3091 rprop = event->target;
3093 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3095 /* TARGETS selection request */
3096 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3098 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3100 /* MULTIPLE selection request */
3101 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3103 else
3105 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3107 if (lpFormat && lpFormat->lpDrvExportFunc)
3109 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3111 if (lpData)
3113 unsigned char* lpClipData;
3114 DWORD cBytes;
3115 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3116 rprop, lpData, &cBytes);
3118 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3120 int mode = PropModeReplace;
3122 TRACE("\tUpdating property %s, %d bytes\n",
3123 debugstr_format(lpFormat->wFormatID), cBytes);
3124 wine_tsx11_lock();
3127 int nelements = min(cBytes, 65536);
3128 XChangeProperty(display, request, rprop, event->target,
3129 8, mode, lpClipData, nelements);
3130 mode = PropModeAppend;
3131 cBytes -= nelements;
3132 lpClipData += nelements;
3133 } while (cBytes > 0);
3134 wine_tsx11_unlock();
3136 GlobalUnlock(hClipData);
3137 GlobalFree(hClipData);
3143 END:
3144 /* reply to sender
3145 * SelectionNotify should be sent only at the end of a MULTIPLE request
3147 if ( !bIsMultiple )
3149 result.type = SelectionNotify;
3150 result.display = display;
3151 result.requestor = request;
3152 result.selection = event->selection;
3153 result.property = rprop;
3154 result.target = event->target;
3155 result.time = event->time;
3156 TRACE("Sending SelectionNotify event...\n");
3157 wine_tsx11_lock();
3158 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3159 wine_tsx11_unlock();
3164 /***********************************************************************
3165 * X11DRV_SelectionRequest
3167 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3169 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3173 /***********************************************************************
3174 * X11DRV_SelectionClear
3176 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3178 XSelectionClearEvent *event = &xev->xselectionclear;
3179 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3180 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3181 event->window, hWnd, event->time );
3184 /***********************************************************************
3185 * X11DRV_Clipboard_Cleanup
3187 void X11DRV_Clipboard_Cleanup(void)
3189 selectionAcquired = S_NOSELECTION;
3191 X11DRV_EmptyClipboard(FALSE);