winex11.drv: Implement synthesizing the CF_ENHMETAFILE clipboard format from CF_METAF...
[wine.git] / dlls / winex11.drv / clipboard.c
blobc3f1b55877bc23e7f489c677f683ba0fc7659d96
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/debug.h"
83 #include "wine/unicode.h"
84 #include "wine/server.h"
86 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
88 /* Maximum wait time for selection notify */
89 #define SELECTION_RETRIES 500 /* wait for .1 seconds */
90 #define SELECTION_WAIT 1000 /* us */
91 /* Minimum seconds that must lapse between owner queries */
92 #define OWNERQUERYLAPSETIME 1
94 /* Selection masks */
95 #define S_NOSELECTION 0
96 #define S_PRIMARY 1
97 #define S_CLIPBOARD 2
99 typedef struct
101 HWND hWndOpen;
102 HWND hWndOwner;
103 HWND hWndViewer;
104 UINT seqno;
105 UINT flags;
106 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
108 struct tagWINE_CLIPDATA; /* Forward */
110 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
111 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
112 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
114 typedef struct tagWINE_CLIPFORMAT {
115 UINT wFormatID;
116 LPCWSTR Name;
117 UINT drvData;
118 UINT wFlags;
119 DRVIMPORTFUNC lpDrvImportFunc;
120 DRVEXPORTFUNC lpDrvExportFunc;
121 struct tagWINE_CLIPFORMAT *PrevFormat;
122 struct tagWINE_CLIPFORMAT *NextFormat;
123 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
125 typedef struct tagWINE_CLIPDATA {
126 UINT wFormatID;
127 HANDLE hData;
128 UINT wFlags;
129 UINT drvData;
130 LPWINE_CLIPFORMAT lpFormat;
131 struct tagWINE_CLIPDATA *PrevData;
132 struct tagWINE_CLIPDATA *NextData;
133 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
135 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
136 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
137 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
138 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
140 static int selectionAcquired = 0; /* Contains the current selection masks */
141 static Window selectionWindow = None; /* The top level X window which owns the selection */
142 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
144 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned);
145 void CDECL X11DRV_EndClipboardUpdate(void);
146 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
147 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
148 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
149 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
150 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
155 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
156 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
157 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
158 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
159 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
160 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
161 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
162 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
163 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
164 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
166 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
167 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
168 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
169 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
170 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
171 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
172 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
173 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
174 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
175 unsigned char** data, unsigned long* datasize);
176 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
177 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
178 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
180 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
181 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
182 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display);
183 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
185 /* Clipboard formats
186 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
187 * declared in clipboard.h
189 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
190 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
191 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
192 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
193 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
194 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
195 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
196 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
197 static const WCHAR wszIMAGEBMP[] = {'i','m','a','g','e','/','b','m','p',0};
198 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
199 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
200 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
201 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
202 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
203 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
204 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
205 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
206 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
207 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
208 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
209 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
210 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
211 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
212 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
214 static WINE_CLIPFORMAT ClipFormats[] =
216 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
217 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
219 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
220 NULL, &ClipFormats[0], &ClipFormats[2]},
222 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
223 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
225 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
226 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
228 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
229 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
231 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
232 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
234 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
235 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
237 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
238 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
240 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
241 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
243 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
244 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
246 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
247 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
249 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
250 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
252 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
253 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
255 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
256 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
257 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
259 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
260 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
262 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
263 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
265 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
266 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
268 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
269 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
271 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
272 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
274 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
275 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
277 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
278 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
280 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
281 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
283 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
284 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], &ClipFormats[23]},
286 { CF_DIB, wszIMAGEBMP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportImageBmp,
287 X11DRV_CLIPBOARD_ExportImageBmp, &ClipFormats[22], NULL},
290 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
292 /* Maps X properties to Windows formats */
293 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
294 static const WCHAR wszGIF[] = {'G','I','F',0};
295 static const WCHAR wszJFIF[] = {'J','F','I','F',0};
296 static const WCHAR wszPNG[] = {'P','N','G',0};
297 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
298 static const struct
300 LPCWSTR lpszFormat;
301 UINT prop;
302 } PropertyFormatMap[] =
304 { wszRichTextFormat, XATOM_text_rtf },
305 { wszRichTextFormat, XATOM_text_richtext },
306 { wszGIF, XATOM_image_gif },
307 { wszJFIF, XATOM_image_jpeg },
308 { wszPNG, XATOM_image_png },
309 { wszHTMLFormat, XATOM_HTML_Format }, /* prefer this to text/html */
314 * Cached clipboard data.
316 static LPWINE_CLIPDATA ClipData = NULL;
317 static UINT ClipDataCount = 0;
320 * Clipboard sequence number
322 static UINT wSeqNo = 0;
324 /**************************************************************************
325 * Internal Clipboard implementation methods
326 **************************************************************************/
328 static Window thread_selection_wnd(void)
330 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
331 Window w = thread_data->selection_wnd;
333 if (!w)
335 XSetWindowAttributes attr;
337 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
338 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
340 wine_tsx11_lock();
341 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
342 InputOutput, CopyFromParent, CWEventMask, &attr);
343 wine_tsx11_unlock();
345 if (w)
346 thread_data->selection_wnd = w;
347 else
348 FIXME("Failed to create window. Fetching selection data will fail.\n");
351 return w;
354 /**************************************************************************
355 * X11DRV_InitClipboard
357 void X11DRV_InitClipboard(void)
359 UINT i;
360 WINE_CLIPFORMAT *format;
362 /* Register known mapping between window formats and X properties */
363 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
364 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
366 /* Set up a conversion function from "HTML Format" to "text/html" */
367 format = X11DRV_CLIPBOARD_InsertClipboardFormat(wszHTMLFormat, GET_ATOM(XATOM_text_html));
368 format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
372 /**************************************************************************
373 * intern_atoms
375 * Intern atoms for formats that don't have one yet.
377 static void intern_atoms(void)
379 LPWINE_CLIPFORMAT format;
380 int i, count, len;
381 char **names;
382 Atom *atoms;
383 Display *display;
385 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
386 if (!format->drvData) count++;
387 if (!count) return;
389 display = thread_init_display();
391 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
392 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
394 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
395 if (!format->drvData) {
396 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
397 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
398 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
402 wine_tsx11_lock();
403 XInternAtoms( display, names, count, False, atoms );
404 wine_tsx11_unlock();
406 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
407 if (!format->drvData) {
408 HeapFree(GetProcessHeap(), 0, names[i]);
409 format->drvData = atoms[i++];
413 HeapFree( GetProcessHeap(), 0, names );
414 HeapFree( GetProcessHeap(), 0, atoms );
418 /**************************************************************************
419 * register_format
421 * Register a custom X clipboard format.
423 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
425 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
427 TRACE("%s\n", debugstr_w(FormatName));
429 /* walk format chain to see if it's already registered */
430 while (lpFormat)
432 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
433 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
434 return lpFormat;
435 lpFormat = lpFormat->NextFormat;
438 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
442 /**************************************************************************
443 * X11DRV_CLIPBOARD_LookupFormat
445 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
447 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
449 while(lpFormat)
451 if (lpFormat->wFormatID == wID)
452 break;
454 lpFormat = lpFormat->NextFormat;
456 if (lpFormat && !lpFormat->drvData) intern_atoms();
457 return lpFormat;
461 /**************************************************************************
462 * X11DRV_CLIPBOARD_LookupProperty
464 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
466 for (;;)
468 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
469 BOOL need_intern = FALSE;
471 if (current)
472 lpFormat = current->NextFormat;
474 while(lpFormat)
476 if (lpFormat->drvData == drvData) return lpFormat;
477 if (!lpFormat->drvData) need_intern = TRUE;
478 lpFormat = lpFormat->NextFormat;
480 if (!need_intern) return NULL;
481 intern_atoms();
482 /* restart the search for the new atoms */
487 /**************************************************************************
488 * X11DRV_CLIPBOARD_LookupData
490 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
492 LPWINE_CLIPDATA lpData = ClipData;
494 if (lpData)
498 if (lpData->wFormatID == wID)
499 break;
501 lpData = lpData->NextData;
503 while(lpData != ClipData);
505 if (lpData->wFormatID != wID)
506 lpData = NULL;
509 return lpData;
513 /**************************************************************************
514 * InsertClipboardFormat
516 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
518 LPWINE_CLIPFORMAT lpFormat;
519 LPWINE_CLIPFORMAT lpNewFormat;
520 LPWSTR new_name;
522 /* allocate storage for new format entry */
523 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
525 if(lpNewFormat == NULL)
527 WARN("No more memory for a new format!\n");
528 return NULL;
531 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
533 WARN("No more memory for the new format name!\n");
534 HeapFree(GetProcessHeap(), 0, lpNewFormat);
535 return NULL;
538 lpNewFormat->Name = strcpyW(new_name, FormatName);
539 lpNewFormat->wFlags = 0;
540 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
541 lpNewFormat->drvData = prop;
542 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
543 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
545 /* Link Format */
546 lpFormat = ClipFormats;
548 while(lpFormat->NextFormat) /* Move to last entry */
549 lpFormat = lpFormat->NextFormat;
551 lpNewFormat->NextFormat = NULL;
552 lpFormat->NextFormat = lpNewFormat;
553 lpNewFormat->PrevFormat = lpFormat;
555 TRACE("Registering format(%04x): %s drvData %d\n",
556 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
558 return lpNewFormat;
564 /**************************************************************************
565 * X11DRV_CLIPBOARD_GetClipboardInfo
567 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
569 BOOL bRet = FALSE;
571 SERVER_START_REQ( set_clipboard_info )
573 req->flags = 0;
575 if (wine_server_call_err( req ))
577 ERR("Failed to get clipboard owner.\n");
579 else
581 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
582 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
583 cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
584 cbInfo->seqno = reply->seqno;
585 cbInfo->flags = reply->flags;
587 bRet = TRUE;
590 SERVER_END_REQ;
592 return bRet;
596 /**************************************************************************
597 * X11DRV_CLIPBOARD_ReleaseOwnership
599 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
601 BOOL bRet = FALSE;
603 SERVER_START_REQ( set_clipboard_info )
605 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
607 if (wine_server_call_err( req ))
609 ERR("Failed to set clipboard.\n");
611 else
613 bRet = TRUE;
616 SERVER_END_REQ;
618 return bRet;
623 /**************************************************************************
624 * X11DRV_CLIPBOARD_InsertClipboardData
626 * Caller *must* have the clipboard open and be the owner.
628 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData, DWORD flags,
629 LPWINE_CLIPFORMAT lpFormat, BOOL override)
631 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
633 TRACE("format=%04x lpData=%p hData=%p flags=0x%08x lpFormat=%p override=%d\n",
634 wFormatID, lpData, hData, flags, lpFormat, override);
636 if (lpData && !override)
637 return TRUE;
639 if (lpData)
641 X11DRV_CLIPBOARD_FreeData(lpData);
643 lpData->hData = hData;
645 else
647 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
649 lpData->wFormatID = wFormatID;
650 lpData->hData = hData;
651 lpData->lpFormat = lpFormat;
652 lpData->drvData = 0;
654 if (ClipData)
656 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
658 lpData->PrevData = lpPrevData;
659 lpData->NextData = ClipData;
661 lpPrevData->NextData = lpData;
662 ClipData->PrevData = lpData;
664 else
666 lpData->NextData = lpData;
667 lpData->PrevData = lpData;
668 ClipData = lpData;
671 ClipDataCount++;
674 lpData->wFlags = flags;
676 return TRUE;
680 /**************************************************************************
681 * X11DRV_CLIPBOARD_FreeData
683 * Free clipboard data handle.
685 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
687 TRACE("%04x\n", lpData->wFormatID);
689 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
690 lpData->wFormatID <= CF_GDIOBJLAST) ||
691 lpData->wFormatID == CF_BITMAP ||
692 lpData->wFormatID == CF_DIB ||
693 lpData->wFormatID == CF_PALETTE)
695 if (lpData->hData)
696 DeleteObject(lpData->hData);
698 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
699 XFreePixmap(gdi_display, lpData->drvData);
701 else if (lpData->wFormatID == CF_METAFILEPICT)
703 if (lpData->hData)
705 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
706 GlobalFree(lpData->hData);
709 else if (lpData->wFormatID == CF_ENHMETAFILE)
711 if (lpData->hData)
712 DeleteEnhMetaFile(lpData->hData);
714 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
715 lpData->wFormatID > CF_PRIVATELAST)
717 if (lpData->hData)
718 GlobalFree(lpData->hData);
721 lpData->hData = 0;
722 lpData->drvData = 0;
726 /**************************************************************************
727 * X11DRV_CLIPBOARD_UpdateCache
729 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
731 BOOL bret = TRUE;
733 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
735 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
737 ERR("Failed to retrieve clipboard information.\n");
738 bret = FALSE;
740 else if (wSeqNo < lpcbinfo->seqno)
742 X11DRV_EmptyClipboard(TRUE);
744 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
746 ERR("Failed to cache clipboard data owned by another process.\n");
747 bret = FALSE;
749 else
751 X11DRV_EndClipboardUpdate();
754 wSeqNo = lpcbinfo->seqno;
758 return bret;
762 /**************************************************************************
763 * X11DRV_CLIPBOARD_RenderFormat
765 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
767 BOOL bret = TRUE;
769 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
771 if (lpData->hData) return bret; /* Already rendered */
773 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
774 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
775 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
777 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
779 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
780 lpData->wFormatID);
781 bret = FALSE;
784 else
786 CLIPBOARDINFO cbInfo;
788 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
790 /* Send a WM_RENDERFORMAT message to notify the owner to render the
791 * data requested into the clipboard.
793 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
794 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, lpData->wFormatID, 0);
796 if (!lpData->hData) bret = FALSE;
798 else
800 ERR("hWndClipOwner is lost!\n");
801 bret = FALSE;
805 return bret;
809 /**************************************************************************
810 * CLIPBOARD_ConvertText
811 * Returns number of required/converted characters - not bytes!
813 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
814 WORD dst_fmt, void *dst, INT dst_size)
816 UINT cp;
818 if(src_fmt == CF_UNICODETEXT)
820 switch(dst_fmt)
822 case CF_TEXT:
823 cp = CP_ACP;
824 break;
825 case CF_OEMTEXT:
826 cp = CP_OEMCP;
827 break;
828 default:
829 return 0;
831 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
834 if(dst_fmt == CF_UNICODETEXT)
836 switch(src_fmt)
838 case CF_TEXT:
839 cp = CP_ACP;
840 break;
841 case CF_OEMTEXT:
842 cp = CP_OEMCP;
843 break;
844 default:
845 return 0;
847 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
850 if(!dst_size) return src_size;
852 if(dst_size > src_size) dst_size = src_size;
854 if(src_fmt == CF_TEXT )
855 CharToOemBuffA(src, dst, dst_size);
856 else
857 OemToCharBuffA(src, dst, dst_size);
859 return dst_size;
863 /**************************************************************************
864 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
866 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
868 BOOL bret = FALSE;
870 TRACE("\n");
872 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
874 UINT wFormatID = lpData->wFormatID;
876 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
877 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
878 else
880 switch (wFormatID)
882 case CF_DIB:
883 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
884 break;
886 case CF_BITMAP:
887 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
888 break;
890 case CF_ENHMETAFILE:
891 bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
892 break;
894 case CF_METAFILEPICT:
895 FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
896 break;
898 default:
899 FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
900 break;
904 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
907 return bret;
911 /**************************************************************************
912 * X11DRV_CLIPBOARD_RenderSynthesizedText
914 * Renders synthesized text
916 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
918 LPCSTR lpstrS;
919 LPSTR lpstrT;
920 HANDLE hData;
921 INT src_chars, dst_chars, alloc_size;
922 LPWINE_CLIPDATA lpSource = NULL;
924 TRACE("%04x\n", wFormatID);
926 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
927 lpSource->hData)
928 return TRUE;
930 /* Look for rendered source or non-synthesized source */
931 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
932 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
934 TRACE("UNICODETEXT -> %04x\n", wFormatID);
936 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
937 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
939 TRACE("TEXT -> %04x\n", wFormatID);
941 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
942 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
944 TRACE("OEMTEXT -> %04x\n", wFormatID);
947 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
948 !lpSource->hData))
949 return FALSE;
951 /* Ask the clipboard owner to render the source text if necessary */
952 if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
953 return FALSE;
955 lpstrS = GlobalLock(lpSource->hData);
956 if (!lpstrS)
957 return FALSE;
959 /* Text always NULL terminated */
960 if(lpSource->wFormatID == CF_UNICODETEXT)
961 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
962 else
963 src_chars = strlen(lpstrS) + 1;
965 /* Calculate number of characters in the destination buffer */
966 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
967 src_chars, wFormatID, NULL, 0);
969 if (!dst_chars)
970 return FALSE;
972 TRACE("Converting from '%04x' to '%04x', %i chars\n",
973 lpSource->wFormatID, wFormatID, src_chars);
975 /* Convert characters to bytes */
976 if(wFormatID == CF_UNICODETEXT)
977 alloc_size = dst_chars * sizeof(WCHAR);
978 else
979 alloc_size = dst_chars;
981 hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
982 GMEM_DDESHARE, alloc_size);
984 lpstrT = GlobalLock(hData);
986 if (lpstrT)
988 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
989 wFormatID, lpstrT, dst_chars);
990 GlobalUnlock(hData);
993 GlobalUnlock(lpSource->hData);
995 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
999 /**************************************************************************
1000 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1002 * Renders synthesized DIB
1004 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1006 BOOL bret = FALSE;
1007 LPWINE_CLIPDATA lpSource = NULL;
1009 TRACE("\n");
1011 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
1013 bret = TRUE;
1015 /* If we have a bitmap and it's not synthesized or it has been rendered */
1016 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1017 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1019 /* Render source if required */
1020 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1022 HDC hdc;
1023 HGLOBAL hData;
1025 hdc = GetDC(NULL);
1026 hData = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData);
1027 ReleaseDC(NULL, hdc);
1029 if (hData)
1031 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
1032 bret = TRUE;
1037 return bret;
1041 /**************************************************************************
1042 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1044 * Renders synthesized bitmap
1046 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1048 BOOL bret = FALSE;
1049 LPWINE_CLIPDATA lpSource = NULL;
1051 TRACE("\n");
1053 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
1055 bret = TRUE;
1057 /* If we have a dib and it's not synthesized or it has been rendered */
1058 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1059 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1061 /* Render source if required */
1062 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1064 HDC hdc;
1065 HBITMAP hData;
1066 unsigned int offset;
1067 LPBITMAPINFOHEADER lpbmih;
1069 hdc = GetDC(NULL);
1070 lpbmih = GlobalLock(lpSource->hData);
1072 offset = sizeof(BITMAPINFOHEADER)
1073 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1074 (1 << lpbmih->biBitCount)) : 0);
1076 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1077 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1079 GlobalUnlock(lpSource->hData);
1080 ReleaseDC(NULL, hdc);
1082 if (hData)
1084 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
1085 bret = TRUE;
1090 return bret;
1094 /**************************************************************************
1095 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1097 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1099 LPWINE_CLIPDATA lpSource = NULL;
1101 TRACE("\n");
1103 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1104 return TRUE;
1105 /* If we have a MF pict and it's not synthesized or it has been rendered */
1106 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1107 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1109 /* Render source if required */
1110 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1112 METAFILEPICT *pmfp;
1113 HENHMETAFILE hData = NULL;
1115 pmfp = GlobalLock(lpSource->hData);
1116 if (pmfp)
1118 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1119 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1120 if (mf_bits)
1122 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1123 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1124 HeapFree(GetProcessHeap(), 0, mf_bits);
1126 GlobalUnlock(lpSource->hData);
1129 if (hData)
1131 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1132 return TRUE;
1137 return FALSE;
1141 /**************************************************************************
1142 * X11DRV_CLIPBOARD_ImportXAString
1144 * Import XA_STRING, converting the string to CF_TEXT.
1146 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1148 LPBYTE lpdata;
1149 unsigned long cbytes;
1150 LPSTR lpstr;
1151 unsigned long i, inlcount = 0;
1152 HANDLE hText = 0;
1154 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1155 return 0;
1157 for (i = 0; i <= cbytes; i++)
1159 if (lpdata[i] == '\n')
1160 inlcount++;
1163 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1165 lpstr = GlobalLock(hText);
1167 for (i = 0, inlcount = 0; i <= cbytes; i++)
1169 if (lpdata[i] == '\n')
1170 lpstr[inlcount++] = '\r';
1172 lpstr[inlcount++] = lpdata[i];
1175 GlobalUnlock(hText);
1178 /* Free the retrieved property data */
1179 HeapFree(GetProcessHeap(), 0, lpdata);
1181 return hText;
1185 /**************************************************************************
1186 * X11DRV_CLIPBOARD_ImportUTF8
1188 * Import XA_STRING, converting the string to CF_UNICODE.
1190 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1192 LPBYTE lpdata;
1193 unsigned long cbytes;
1194 LPSTR lpstr;
1195 unsigned long i, inlcount = 0;
1196 HANDLE hUnicodeText = 0;
1198 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1199 return 0;
1201 for (i = 0; i <= cbytes; i++)
1203 if (lpdata[i] == '\n')
1204 inlcount++;
1207 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1209 UINT count;
1211 for (i = 0, inlcount = 0; i <= cbytes; i++)
1213 if (lpdata[i] == '\n')
1214 lpstr[inlcount++] = '\r';
1216 lpstr[inlcount++] = lpdata[i];
1219 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1220 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1222 if (hUnicodeText)
1224 WCHAR *textW = GlobalLock(hUnicodeText);
1225 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1226 GlobalUnlock(hUnicodeText);
1229 HeapFree(GetProcessHeap(), 0, lpstr);
1232 /* Free the retrieved property data */
1233 HeapFree(GetProcessHeap(), 0, lpdata);
1235 return hUnicodeText;
1239 /**************************************************************************
1240 * X11DRV_CLIPBOARD_ImportCompoundText
1242 * Import COMPOUND_TEXT to CF_UNICODE
1244 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1246 int i, j, ret;
1247 char** srcstr;
1248 int count, lcount;
1249 int srclen, destlen;
1250 HANDLE hUnicodeText;
1251 XTextProperty txtprop;
1253 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1255 return 0;
1258 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1259 txtprop.format = 8;
1260 wine_tsx11_lock();
1261 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1262 wine_tsx11_unlock();
1263 HeapFree(GetProcessHeap(), 0, txtprop.value);
1264 if (ret != Success || !count) return 0;
1266 TRACE("Importing %d line(s)\n", count);
1268 /* Compute number of lines */
1269 srclen = strlen(srcstr[0]);
1270 for (i = 0, lcount = 0; i <= srclen; i++)
1272 if (srcstr[0][i] == '\n')
1273 lcount++;
1276 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1278 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1280 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1282 WCHAR *deststr = GlobalLock(hUnicodeText);
1283 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1285 if (lcount)
1287 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1289 deststr[j] = deststr[i];
1291 if (deststr[i] == '\n')
1292 deststr[--j] = '\r';
1296 GlobalUnlock(hUnicodeText);
1299 wine_tsx11_lock();
1300 XFreeStringList(srcstr);
1301 wine_tsx11_unlock();
1303 return hUnicodeText;
1307 /**************************************************************************
1308 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1310 * Import XA_PIXMAP, converting the image to CF_DIB.
1312 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1314 HWND hwnd;
1315 HDC hdc;
1316 LPBYTE lpdata;
1317 unsigned long cbytes;
1318 Pixmap *pPixmap;
1319 HANDLE hClipData = 0;
1321 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1323 pPixmap = (Pixmap *) lpdata;
1325 hwnd = GetOpenClipboardWindow();
1326 hdc = GetDC(hwnd);
1328 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1329 ReleaseDC(hwnd, hdc);
1331 /* Free the retrieved property data */
1332 HeapFree(GetProcessHeap(), 0, lpdata);
1335 return hClipData;
1339 /**************************************************************************
1340 * X11DRV_CLIPBOARD_ImportImageBmp
1342 * Import image/bmp, converting the image to CF_DIB.
1344 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1346 LPBYTE lpdata;
1347 unsigned long cbytes;
1348 HANDLE hClipData = 0;
1350 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1352 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1354 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1355 bfh->bfType == 0x4d42 /* "BM" */)
1357 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1358 HBITMAP hbmp;
1359 HDC hdc;
1361 hdc = GetDC(0);
1362 hbmp = CreateDIBitmap(
1363 hdc,
1364 &(bmi->bmiHeader),
1365 CBM_INIT,
1366 lpdata+bfh->bfOffBits,
1367 bmi,
1368 DIB_RGB_COLORS
1371 hClipData = X11DRV_DIB_CreateDIBFromBitmap(hdc, hbmp);
1373 DeleteObject(hbmp);
1374 ReleaseDC(0, hdc);
1377 /* Free the retrieved property data */
1378 HeapFree(GetProcessHeap(), 0, lpdata);
1381 return hClipData;
1385 /**************************************************************************
1386 * X11DRV_CLIPBOARD_ImportMetaFilePict
1388 * Import MetaFilePict.
1390 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1392 LPBYTE lpdata;
1393 unsigned long cbytes;
1394 HANDLE hClipData = 0;
1396 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1398 if (cbytes)
1399 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1401 /* Free the retrieved property data */
1402 HeapFree(GetProcessHeap(), 0, lpdata);
1405 return hClipData;
1409 /**************************************************************************
1410 * X11DRV_ImportEnhMetaFile
1412 * Import EnhMetaFile.
1414 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1416 LPBYTE lpdata;
1417 unsigned long cbytes;
1418 HANDLE hClipData = 0;
1420 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1422 if (cbytes)
1423 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1425 /* Free the retrieved property data */
1426 HeapFree(GetProcessHeap(), 0, lpdata);
1429 return hClipData;
1433 /**************************************************************************
1434 * X11DRV_ImportClipbordaData
1436 * Generic import clipboard data routine.
1438 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1440 LPVOID lpClipData;
1441 LPBYTE lpdata;
1442 unsigned long cbytes;
1443 HANDLE hClipData = 0;
1445 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1447 if (cbytes)
1449 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1450 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1451 if (hClipData == 0)
1452 return NULL;
1454 if ((lpClipData = GlobalLock(hClipData)))
1456 memcpy(lpClipData, lpdata, cbytes);
1457 GlobalUnlock(hClipData);
1459 else
1461 GlobalFree(hClipData);
1462 hClipData = 0;
1466 /* Free the retrieved property data */
1467 HeapFree(GetProcessHeap(), 0, lpdata);
1470 return hClipData;
1474 /**************************************************************************
1475 X11DRV_CLIPBOARD_ExportClipboardData
1477 * Generic export clipboard data routine.
1479 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1480 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1482 LPVOID lpClipData;
1483 UINT datasize = 0;
1484 HANDLE hClipData = 0;
1486 *lpBytes = 0; /* Assume failure */
1488 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1489 ERR("Failed to export %04x format\n", lpData->wFormatID);
1490 else
1492 datasize = GlobalSize(lpData->hData);
1494 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1495 if (hClipData == 0) return NULL;
1497 if ((lpClipData = GlobalLock(hClipData)))
1499 LPVOID lpdata = GlobalLock(lpData->hData);
1501 memcpy(lpClipData, lpdata, datasize);
1502 *lpBytes = datasize;
1504 GlobalUnlock(lpData->hData);
1505 GlobalUnlock(hClipData);
1506 } else {
1507 GlobalFree(hClipData);
1508 hClipData = 0;
1512 return hClipData;
1516 /**************************************************************************
1517 * X11DRV_CLIPBOARD_ExportXAString
1519 * Export CF_TEXT converting the string to XA_STRING.
1520 * Helper function for X11DRV_CLIPBOARD_ExportString.
1522 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1524 UINT i, j;
1525 UINT size;
1526 LPSTR text, lpstr = NULL;
1528 *lpBytes = 0; /* Assume return has zero bytes */
1530 text = GlobalLock(lpData->hData);
1531 size = strlen(text);
1533 /* remove carriage returns */
1534 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1535 if (lpstr == NULL)
1536 goto done;
1538 for (i = 0,j = 0; i < size && text[i]; i++)
1540 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1541 continue;
1542 lpstr[j++] = text[i];
1545 lpstr[j]='\0';
1546 *lpBytes = j; /* Number of bytes in string */
1548 done:
1549 HeapFree(GetProcessHeap(), 0, text);
1550 GlobalUnlock(lpData->hData);
1552 return lpstr;
1556 /**************************************************************************
1557 * X11DRV_CLIPBOARD_ExportUTF8String
1559 * Export CF_UNICODE converting the string to UTF8.
1560 * Helper function for X11DRV_CLIPBOARD_ExportString.
1562 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1564 UINT i, j;
1565 UINT size;
1566 LPWSTR uni_text;
1567 LPSTR text, lpstr = NULL;
1569 *lpBytes = 0; /* Assume return has zero bytes */
1571 uni_text = GlobalLock(lpData->hData);
1573 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1575 text = HeapAlloc(GetProcessHeap(), 0, size);
1576 if (!text)
1577 goto done;
1578 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1580 /* remove carriage returns */
1581 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1582 if (lpstr == NULL)
1583 goto done;
1585 for (i = 0,j = 0; i < size && text[i]; i++)
1587 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1588 continue;
1589 lpstr[j++] = text[i];
1591 lpstr[j]='\0';
1593 *lpBytes = j; /* Number of bytes in string */
1595 done:
1596 HeapFree(GetProcessHeap(), 0, text);
1597 GlobalUnlock(lpData->hData);
1599 return lpstr;
1604 /**************************************************************************
1605 * X11DRV_CLIPBOARD_ExportCompoundText
1607 * Export CF_UNICODE to COMPOUND_TEXT
1608 * Helper function for X11DRV_CLIPBOARD_ExportString.
1610 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1611 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1613 char* lpstr = 0;
1614 XTextProperty prop;
1615 XICCEncodingStyle style;
1616 UINT i, j;
1617 UINT size;
1618 LPWSTR uni_text;
1620 uni_text = GlobalLock(lpData->hData);
1622 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1623 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1624 if (!lpstr)
1625 return 0;
1627 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1629 /* remove carriage returns */
1630 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1632 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1633 continue;
1634 lpstr[j++] = lpstr[i];
1636 lpstr[j]='\0';
1638 GlobalUnlock(lpData->hData);
1640 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1641 style = XCompoundTextStyle;
1642 else
1643 style = XStdICCTextStyle;
1645 /* Update the X property */
1646 wine_tsx11_lock();
1647 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1649 XSetTextProperty(display, requestor, &prop, rprop);
1650 XFree(prop.value);
1652 wine_tsx11_unlock();
1654 HeapFree(GetProcessHeap(), 0, lpstr);
1656 return 0;
1659 /**************************************************************************
1660 * X11DRV_CLIPBOARD_ExportString
1662 * Export string
1664 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1665 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1667 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1669 if (aTarget == XA_STRING)
1670 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1671 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1672 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1673 rprop, lpData, lpBytes);
1674 else
1676 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1677 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1680 else
1681 ERR("Failed to render %04x format\n", lpData->wFormatID);
1683 return 0;
1687 /**************************************************************************
1688 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1690 * Export CF_DIB to XA_PIXMAP.
1692 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1693 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1695 HDC hdc;
1696 HANDLE hData;
1697 unsigned char* lpData;
1699 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1701 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1702 return 0;
1705 if (!lpdata->drvData) /* If not already rendered */
1707 /* For convert from packed DIB to Pixmap */
1708 hdc = GetDC(0);
1709 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData, hdc);
1710 ReleaseDC(0, hdc);
1713 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1715 /* Wrap pixmap so we can return a handle */
1716 hData = GlobalAlloc(0, *lpBytes);
1717 lpData = GlobalLock(hData);
1718 memcpy(lpData, &lpdata->drvData, *lpBytes);
1719 GlobalUnlock(hData);
1721 return hData;
1725 /**************************************************************************
1726 * X11DRV_CLIPBOARD_ExportImageBmp
1728 * Export CF_DIB to image/bmp.
1730 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1731 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1733 HANDLE hpackeddib;
1734 LPBYTE dibdata;
1735 UINT bmpsize;
1736 HANDLE hbmpdata;
1737 LPBYTE bmpdata;
1738 BITMAPFILEHEADER *bfh;
1740 *lpBytes = 0;
1742 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1744 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1745 return 0;
1748 hpackeddib = lpdata->hData;
1750 dibdata = GlobalLock(hpackeddib);
1751 if (!dibdata)
1753 ERR("Failed to lock packed DIB\n");
1754 return 0;
1757 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1759 hbmpdata = GlobalAlloc(0, bmpsize);
1761 if (hbmpdata)
1763 bmpdata = GlobalLock(hbmpdata);
1765 if (!bmpdata)
1767 GlobalFree(hbmpdata);
1768 GlobalUnlock(hpackeddib);
1769 return 0;
1772 /* bitmap file header */
1773 bfh = (BITMAPFILEHEADER*)bmpdata;
1774 bfh->bfType = 0x4d42; /* "BM" */
1775 bfh->bfSize = bmpsize;
1776 bfh->bfReserved1 = 0;
1777 bfh->bfReserved2 = 0;
1778 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1780 /* rest of bitmap is the same as the packed dib */
1781 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1783 *lpBytes = bmpsize;
1785 GlobalUnlock(hbmpdata);
1788 GlobalUnlock(hpackeddib);
1790 return hbmpdata;
1794 /**************************************************************************
1795 * X11DRV_CLIPBOARD_ExportMetaFilePict
1797 * Export MetaFilePict.
1799 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1800 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1802 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1804 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1805 return 0;
1808 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
1812 /**************************************************************************
1813 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1815 * Export EnhMetaFile.
1817 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1818 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1820 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1822 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1823 return 0;
1826 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
1830 /**************************************************************************
1831 * get_html_description_field
1833 * Find the value of a field in an HTML Format description.
1835 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1837 LPCSTR pos=data;
1839 while (pos && *pos && *pos != '<')
1841 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1842 return pos+strlen(keyword);
1844 pos = strchr(pos, '\n');
1845 if (pos) pos++;
1848 return NULL;
1852 /**************************************************************************
1853 * X11DRV_CLIPBOARD_ExportTextHtml
1855 * Export HTML Format to text/html.
1857 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1859 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
1860 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1862 HANDLE hdata;
1863 LPCSTR data, field_value;
1864 UINT fragmentstart, fragmentend, htmlsize;
1865 HANDLE hhtmldata=NULL;
1866 LPSTR htmldata;
1868 *lpBytes = 0;
1870 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1872 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1873 return 0;
1876 hdata = lpdata->hData;
1878 data = GlobalLock(hdata);
1879 if (!data)
1881 ERR("Failed to lock HTML Format data\n");
1882 return 0;
1885 /* read the important fields */
1886 field_value = get_html_description_field(data, "StartFragment:");
1887 if (!field_value)
1889 ERR("Couldn't find StartFragment value\n");
1890 goto end;
1892 fragmentstart = atoi(field_value);
1894 field_value = get_html_description_field(data, "EndFragment:");
1895 if (!field_value)
1897 ERR("Couldn't find EndFragment value\n");
1898 goto end;
1900 fragmentend = atoi(field_value);
1902 /* export only the fragment */
1903 htmlsize = fragmentend - fragmentstart + 1;
1905 hhtmldata = GlobalAlloc(0, htmlsize);
1907 if (hhtmldata)
1909 htmldata = GlobalLock(hhtmldata);
1911 if (!htmldata)
1913 GlobalFree(hhtmldata);
1914 htmldata = NULL;
1915 goto end;
1918 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1919 htmldata[htmlsize-1] = '\0';
1921 *lpBytes = htmlsize;
1923 GlobalUnlock(htmldata);
1926 end:
1928 GlobalUnlock(hdata);
1930 return hhtmldata;
1934 /**************************************************************************
1935 * X11DRV_CLIPBOARD_QueryTargets
1937 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1938 Atom target, XEvent *xe)
1940 INT i;
1941 Bool res;
1943 wine_tsx11_lock();
1944 XConvertSelection(display, selection, target,
1945 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1946 wine_tsx11_unlock();
1949 * Wait until SelectionNotify is received
1951 for (i = 0; i < SELECTION_RETRIES; i++)
1953 wine_tsx11_lock();
1954 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1955 wine_tsx11_unlock();
1956 if (res && xe->xselection.selection == selection) break;
1958 usleep(SELECTION_WAIT);
1961 if (i == SELECTION_RETRIES)
1963 ERR("Timed out waiting for SelectionNotify event\n");
1964 return FALSE;
1966 /* Verify that the selection returned a valid TARGETS property */
1967 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1969 /* Selection owner failed to respond or we missed the SelectionNotify */
1970 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1971 return FALSE;
1974 return TRUE;
1978 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1980 return (event->error_code == BadAtom);
1983 /**************************************************************************
1984 * X11DRV_CLIPBOARD_InsertSelectionProperties
1986 * Mark properties available for future retrieval.
1988 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1990 UINT i, nb_atoms = 0;
1991 Atom *atoms = NULL;
1993 /* Cache these formats in the clipboard cache */
1994 for (i = 0; i < count; i++)
1996 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1998 if (lpFormat)
2000 /* We found at least one Window's format that mapps to the property.
2001 * Continue looking for more.
2003 * If more than one property map to a Window's format then we use the first
2004 * one and ignore the rest.
2006 while (lpFormat)
2008 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
2009 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
2010 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2011 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2014 else if (properties[i])
2016 /* add it to the list of atoms that we don't know about yet */
2017 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2018 (count - i) * sizeof(*atoms) );
2019 if (atoms) atoms[nb_atoms++] = properties[i];
2023 /* query all unknown atoms in one go */
2024 if (atoms)
2026 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2027 if (names)
2029 X11DRV_expect_error( display, is_atom_error, NULL );
2030 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2031 if (X11DRV_check_error())
2033 WARN( "got some bad atoms, ignoring\n" );
2034 nb_atoms = 0;
2036 for (i = 0; i < nb_atoms; i++)
2038 WINE_CLIPFORMAT *lpFormat;
2039 LPWSTR wname;
2040 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2041 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2042 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2044 lpFormat = register_format( wname, atoms[i] );
2045 HeapFree(GetProcessHeap(), 0, wname);
2046 if (!lpFormat)
2048 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2049 continue;
2051 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
2052 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
2053 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2055 wine_tsx11_lock();
2056 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2057 wine_tsx11_unlock();
2058 HeapFree( GetProcessHeap(), 0, names );
2060 HeapFree( GetProcessHeap(), 0, atoms );
2065 /**************************************************************************
2066 * X11DRV_CLIPBOARD_QueryAvailableData
2068 * Caches the list of data formats available from the current selection.
2069 * This queries the selection owner for the TARGETS property and saves all
2070 * reported property types.
2072 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
2074 XEvent xe;
2075 Atom atype=AnyPropertyType;
2076 int aformat;
2077 unsigned long remain;
2078 Atom* targetList=NULL;
2079 Window w;
2080 unsigned long cSelectionTargets = 0;
2082 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2084 ERR("Received request to cache selection but process is owner=(%08x)\n",
2085 (unsigned) selectionWindow);
2086 return -1; /* Prevent self request */
2089 w = thread_selection_wnd();
2090 if (!w)
2092 ERR("No window available to retrieve selection!\n");
2093 return -1;
2097 * Query the selection owner for the TARGETS property
2099 wine_tsx11_lock();
2100 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2101 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2103 wine_tsx11_unlock();
2104 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2105 selectionCacheSrc = XA_PRIMARY;
2106 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2107 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2108 else
2110 Atom xstr = XA_STRING;
2112 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2113 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2115 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2116 selectionCacheSrc = XA_PRIMARY;
2117 return 1;
2119 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2121 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2122 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2123 return 1;
2125 else
2127 WARN("Failed to query selection owner for available data.\n");
2128 return -1;
2132 else /* No selection owner so report 0 targets available */
2134 wine_tsx11_unlock();
2135 return 0;
2138 /* Read the TARGETS property contents */
2139 wine_tsx11_lock();
2140 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2141 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2142 &remain, (unsigned char**)&targetList) != Success)
2144 wine_tsx11_unlock();
2145 WARN("Failed to read TARGETS property\n");
2147 else
2149 wine_tsx11_unlock();
2150 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2151 atype, aformat, cSelectionTargets, remain);
2153 * The TARGETS property should have returned us a list of atoms
2154 * corresponding to each selection target format supported.
2156 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2158 if (aformat == 32)
2160 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2162 else if (aformat == 8) /* work around quartz-wm brain damage */
2164 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2165 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2166 for (i = 0; i < count; i++)
2167 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2168 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2169 HeapFree( GetProcessHeap(), 0, atoms );
2173 /* Free the list of targets */
2174 wine_tsx11_lock();
2175 XFree(targetList);
2176 wine_tsx11_unlock();
2179 return cSelectionTargets;
2183 /**************************************************************************
2184 * X11DRV_CLIPBOARD_ReadSelectionData
2186 * This method is invoked only when we DO NOT own the X selection
2188 * We always get the data from the selection client each time,
2189 * since we have no way of determining if the data in our cache is stale.
2191 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2193 Bool res;
2194 DWORD i;
2195 XEvent xe;
2196 BOOL bRet = FALSE;
2198 TRACE("%04x\n", lpData->wFormatID);
2200 if (!lpData->lpFormat)
2202 ERR("Requesting format %04x but no source format linked to data.\n",
2203 lpData->wFormatID);
2204 return FALSE;
2207 if (!selectionAcquired)
2209 Window w = thread_selection_wnd();
2210 if(!w)
2212 ERR("No window available to read selection data!\n");
2213 return FALSE;
2216 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2217 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
2219 wine_tsx11_lock();
2220 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2221 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2222 wine_tsx11_unlock();
2224 /* wait until SelectionNotify is received */
2225 for (i = 0; i < SELECTION_RETRIES; i++)
2227 wine_tsx11_lock();
2228 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2229 wine_tsx11_unlock();
2230 if (res && xe.xselection.selection == selectionCacheSrc) break;
2232 usleep(SELECTION_WAIT);
2235 if (i == SELECTION_RETRIES)
2237 ERR("Timed out waiting for SelectionNotify event\n");
2239 /* Verify that the selection returned a valid TARGETS property */
2240 else if (xe.xselection.property != None)
2243 * Read the contents of the X selection property
2244 * into WINE's clipboard cache and converting the
2245 * data format if necessary.
2247 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2248 xe.xselection.property);
2250 if (hData)
2251 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2252 else
2253 TRACE("Import function failed\n");
2255 else
2257 TRACE("Failed to convert selection\n");
2260 else
2262 ERR("Received request to cache selection data but process is owner\n");
2265 TRACE("Returning %d\n", bRet);
2267 return bRet;
2271 /**************************************************************************
2272 * X11DRV_CLIPBOARD_GetProperty
2273 * Gets type, data and size.
2275 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2276 Atom *atype, unsigned char** data, unsigned long* datasize)
2278 int aformat;
2279 unsigned long pos = 0, nitems, remain, count;
2280 unsigned char *val = NULL, *buffer;
2282 TRACE("Reading property %lu from X window %lx\n", prop, w);
2284 for (;;)
2286 wine_tsx11_lock();
2287 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2288 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2290 wine_tsx11_unlock();
2291 WARN("Failed to read property\n");
2292 HeapFree( GetProcessHeap(), 0, val );
2293 return FALSE;
2296 count = get_property_size( aformat, nitems );
2297 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2298 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2300 if (!*data)
2302 XFree( buffer );
2303 wine_tsx11_unlock();
2304 HeapFree( GetProcessHeap(), 0, val );
2305 return FALSE;
2307 val = *data;
2308 memcpy( (int *)val + pos, buffer, count );
2309 XFree( buffer );
2310 wine_tsx11_unlock();
2311 if (!remain)
2313 *datasize = pos * sizeof(int) + count;
2314 val[*datasize] = 0;
2315 break;
2317 pos += count / sizeof(int);
2320 /* Delete the property on the window now that we are done
2321 * This will send a PropertyNotify event to the selection owner. */
2322 wine_tsx11_lock();
2323 XDeleteProperty(display, w, prop);
2324 wine_tsx11_unlock();
2325 return TRUE;
2329 /**************************************************************************
2330 * X11DRV_CLIPBOARD_ReadProperty
2331 * Reads the contents of the X selection property.
2333 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2334 unsigned char** data, unsigned long* datasize)
2336 Atom atype;
2337 XEvent xe;
2339 if (prop == None)
2340 return FALSE;
2342 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2343 return FALSE;
2345 wine_tsx11_lock();
2346 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2348 wine_tsx11_unlock();
2350 if (atype == x11drv_atom(INCR))
2352 unsigned char *buf = *data;
2353 unsigned long bufsize = 0;
2355 for (;;)
2357 int i;
2358 unsigned char *prop_data, *tmp;
2359 unsigned long prop_size;
2361 /* Wait until PropertyNotify is received */
2362 for (i = 0; i < SELECTION_RETRIES; i++)
2364 Bool res;
2366 wine_tsx11_lock();
2367 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2368 wine_tsx11_unlock();
2369 if (res && xe.xproperty.atom == prop &&
2370 xe.xproperty.state == PropertyNewValue)
2371 break;
2372 usleep(SELECTION_WAIT);
2375 if (i >= SELECTION_RETRIES ||
2376 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2378 HeapFree(GetProcessHeap(), 0, buf);
2379 return FALSE;
2382 /* Retrieved entire data. */
2383 if (prop_size == 0)
2385 HeapFree(GetProcessHeap(), 0, prop_data);
2386 *data = buf;
2387 *datasize = bufsize;
2388 return TRUE;
2391 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2392 if (!tmp)
2394 HeapFree(GetProcessHeap(), 0, buf);
2395 return FALSE;
2398 buf = tmp;
2399 memcpy(buf + bufsize, prop_data, prop_size + 1);
2400 bufsize += prop_size;
2401 HeapFree(GetProcessHeap(), 0, prop_data);
2405 return TRUE;
2409 /**************************************************************************
2410 * CLIPBOARD_SerializeMetafile
2412 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2414 HANDLE h = 0;
2416 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2418 if (out) /* Serialize out, caller should free memory */
2420 *lpcbytes = 0; /* Assume failure */
2422 if (wformat == CF_METAFILEPICT)
2424 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2425 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2427 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2428 if (h)
2430 char *pdata = GlobalLock(h);
2432 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2433 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2435 *lpcbytes = size + sizeof(METAFILEPICT);
2437 GlobalUnlock(h);
2440 GlobalUnlock(hdata);
2442 else if (wformat == CF_ENHMETAFILE)
2444 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2446 h = GlobalAlloc(0, size);
2447 if (h)
2449 LPVOID pdata = GlobalLock(h);
2451 GetEnhMetaFileBits(hdata, size, pdata);
2452 *lpcbytes = size;
2454 GlobalUnlock(h);
2458 else
2460 if (wformat == CF_METAFILEPICT)
2462 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2463 if (h)
2465 unsigned int wiresize;
2466 LPMETAFILEPICT lpmfp = GlobalLock(h);
2468 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2469 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2470 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2471 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2472 GlobalUnlock(h);
2475 else if (wformat == CF_ENHMETAFILE)
2477 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2481 return h;
2485 /**************************************************************************
2486 * X11DRV_CLIPBOARD_ReleaseSelection
2488 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2490 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2492 /* w is the window that lost the selection
2494 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2495 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2497 if (selectionAcquired && (w == selectionWindow))
2499 CLIPBOARDINFO cbinfo;
2501 /* completely give up the selection */
2502 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2504 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2506 if (cbinfo.flags & CB_PROCESS)
2508 /* Since we're still the owner, this wasn't initiated by
2509 another Wine process */
2510 if (OpenClipboard(hwnd))
2512 /* Destroy private objects */
2513 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2515 /* Give up ownership of the windows clipboard */
2516 X11DRV_CLIPBOARD_ReleaseOwnership();
2517 CloseClipboard();
2521 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2523 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2525 wine_tsx11_lock();
2526 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2528 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2529 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2531 else
2532 TRACE("We no longer own PRIMARY\n");
2533 wine_tsx11_unlock();
2535 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2537 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2539 wine_tsx11_lock();
2540 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2542 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2543 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2545 else
2546 TRACE("We no longer own CLIPBOARD\n");
2547 wine_tsx11_unlock();
2550 selectionWindow = None;
2552 X11DRV_EmptyClipboard(FALSE);
2554 /* Reset the selection flags now that we are done */
2555 selectionAcquired = S_NOSELECTION;
2560 /**************************************************************************
2561 * IsSelectionOwner (X11DRV.@)
2563 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2565 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2567 return selectionAcquired;
2571 /**************************************************************************
2572 * X11DRV Clipboard Exports
2573 **************************************************************************/
2576 /**************************************************************************
2577 * RegisterClipboardFormat (X11DRV.@)
2579 * Registers a custom X clipboard format
2580 * Returns: Format id or 0 on failure
2582 UINT CDECL X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2584 LPWINE_CLIPFORMAT lpFormat;
2586 if (FormatName == NULL) return 0;
2587 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2588 return lpFormat->wFormatID;
2592 /**************************************************************************
2593 * X11DRV_GetClipboardFormatName
2595 INT CDECL X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2597 LPWINE_CLIPFORMAT lpFormat;
2599 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2601 if (wFormat < 0xc000)
2603 SetLastError(ERROR_INVALID_PARAMETER);
2604 return 0;
2607 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2609 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2611 TRACE("Unknown format 0x%08x!\n", wFormat);
2612 SetLastError(ERROR_INVALID_HANDLE);
2613 return 0;
2616 lstrcpynW(retStr, lpFormat->Name, maxlen);
2618 return strlenW(retStr);
2621 static void selection_acquire(void)
2623 Window owner;
2624 Display *display;
2626 owner = thread_selection_wnd();
2627 display = thread_display();
2629 wine_tsx11_lock();
2631 selectionAcquired = 0;
2632 selectionWindow = 0;
2634 /* Grab PRIMARY selection if not owned */
2635 if (use_primary_selection)
2636 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2638 /* Grab CLIPBOARD selection if not owned */
2639 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2641 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2642 selectionAcquired |= S_PRIMARY;
2644 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2645 selectionAcquired |= S_CLIPBOARD;
2647 wine_tsx11_unlock();
2649 if (selectionAcquired)
2651 selectionWindow = owner;
2652 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2656 static DWORD WINAPI selection_thread_proc(LPVOID p)
2658 HANDLE event = p;
2660 TRACE("\n");
2662 selection_acquire();
2663 SetEvent(event);
2665 while (selectionAcquired)
2667 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2670 return 0;
2673 /**************************************************************************
2674 * AcquireClipboard (X11DRV.@)
2676 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2678 DWORD procid;
2679 HANDLE selectionThread;
2681 TRACE(" %p\n", hWndClipWindow);
2684 * It's important that the selection get acquired from the thread
2685 * that owns the clipboard window. The primary reason is that we know
2686 * it is running a message loop and therefore can process the
2687 * X selection events.
2689 if (hWndClipWindow &&
2690 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2692 if (procid != GetCurrentProcessId())
2694 WARN("Setting clipboard owner to other process is not supported\n");
2695 hWndClipWindow = NULL;
2697 else
2699 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2700 GetCurrentThreadId(),
2701 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2703 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2707 if (hWndClipWindow)
2709 selection_acquire();
2711 else
2713 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2714 selectionThread = CreateThread(NULL, 0, &selection_thread_proc, event, 0, NULL);
2716 if (!selectionThread)
2718 WARN("Could not start clipboard thread\n");
2719 return 0;
2722 WaitForSingleObject(event, INFINITE);
2723 CloseHandle(event);
2724 CloseHandle(selectionThread);
2727 return 1;
2731 /**************************************************************************
2732 * X11DRV_EmptyClipboard
2734 * Empty cached clipboard data.
2736 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2738 if (ClipData)
2740 LPWINE_CLIPDATA lpData, lpStart;
2741 LPWINE_CLIPDATA lpNext = ClipData;
2743 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2747 lpStart = ClipData;
2748 lpData = lpNext;
2749 lpNext = lpData->NextData;
2751 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2753 lpData->PrevData->NextData = lpData->NextData;
2754 lpData->NextData->PrevData = lpData->PrevData;
2756 if (lpData == ClipData)
2757 ClipData = lpNext != lpData ? lpNext : NULL;
2759 X11DRV_CLIPBOARD_FreeData(lpData);
2760 HeapFree(GetProcessHeap(), 0, lpData);
2762 ClipDataCount--;
2764 } while (lpNext != lpStart);
2767 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2772 /**************************************************************************
2773 * X11DRV_SetClipboardData
2775 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2777 DWORD flags = 0;
2778 BOOL bResult = TRUE;
2780 /* If it's not owned, data can only be set if the format data is not already owned
2781 and its rendering is not delayed */
2782 if (!owner)
2784 CLIPBOARDINFO cbinfo;
2785 LPWINE_CLIPDATA lpRender;
2787 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2789 if (!hData ||
2790 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2791 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2792 bResult = FALSE;
2793 else
2794 flags = CF_FLAG_UNOWNED;
2797 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
2799 return bResult;
2803 /**************************************************************************
2804 * CountClipboardFormats
2806 INT CDECL X11DRV_CountClipboardFormats(void)
2808 CLIPBOARDINFO cbinfo;
2810 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2812 TRACE(" count=%d\n", ClipDataCount);
2814 return ClipDataCount;
2818 /**************************************************************************
2819 * X11DRV_EnumClipboardFormats
2821 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2823 CLIPBOARDINFO cbinfo;
2824 UINT wNextFormat = 0;
2826 TRACE("(%04X)\n", wFormat);
2828 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2830 if (!wFormat)
2832 if (ClipData)
2833 wNextFormat = ClipData->wFormatID;
2835 else
2837 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2839 if (lpData && lpData->NextData != ClipData)
2840 wNextFormat = lpData->NextData->wFormatID;
2843 return wNextFormat;
2847 /**************************************************************************
2848 * X11DRV_IsClipboardFormatAvailable
2850 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2852 BOOL bRet = FALSE;
2853 CLIPBOARDINFO cbinfo;
2855 TRACE("(%04X)\n", wFormat);
2857 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2859 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2860 bRet = TRUE;
2862 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2864 return bRet;
2868 /**************************************************************************
2869 * GetClipboardData (USER.142)
2871 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2873 CLIPBOARDINFO cbinfo;
2874 LPWINE_CLIPDATA lpRender;
2876 TRACE("(%04X)\n", wFormat);
2878 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2880 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2882 if ( !lpRender->hData )
2883 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2885 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2886 return lpRender->hData;
2889 return 0;
2893 /**************************************************************************
2894 * ResetSelectionOwner
2896 * Called when the thread owning the selection is destroyed and we need to
2897 * preserve the selection ownership. We look for another top level window
2898 * in this process and send it a message to acquire the selection.
2900 void X11DRV_ResetSelectionOwner(void)
2902 HWND hwnd;
2903 DWORD procid;
2905 TRACE("\n");
2907 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2908 return;
2910 selectionAcquired = S_NOSELECTION;
2911 selectionWindow = 0;
2913 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2916 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2918 if (GetCurrentProcessId() == procid)
2920 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2921 return;
2924 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2926 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2928 X11DRV_CLIPBOARD_ReleaseOwnership();
2929 X11DRV_EmptyClipboard(FALSE);
2933 /**************************************************************************
2934 * X11DRV_CLIPBOARD_SynthesizeData
2936 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2938 BOOL bsyn = TRUE;
2939 LPWINE_CLIPDATA lpSource = NULL;
2941 TRACE(" %04x\n", wFormatID);
2943 /* Don't need to synthesize if it already exists */
2944 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2945 return TRUE;
2947 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2949 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2950 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2951 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2952 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2953 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2954 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2956 else if (wFormatID == CF_ENHMETAFILE)
2958 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2959 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2961 else if (wFormatID == CF_METAFILEPICT)
2963 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2964 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2966 else if (wFormatID == CF_DIB)
2968 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2969 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2971 else if (wFormatID == CF_BITMAP)
2973 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2974 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2977 if (bsyn)
2978 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2980 return bsyn;
2985 /**************************************************************************
2986 * X11DRV_EndClipboardUpdate
2987 * TODO:
2988 * Add locale if it hasn't already been added
2990 void CDECL X11DRV_EndClipboardUpdate(void)
2992 INT count = ClipDataCount;
2994 /* Do Unicode <-> Text <-> OEM mapping */
2995 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2996 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2997 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2999 /* Enhmetafile <-> MetafilePict mapping */
3000 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
3001 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
3003 /* DIB <-> Bitmap mapping */
3004 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
3005 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
3007 TRACE("%d formats added to cached data\n", ClipDataCount - count);
3011 /***********************************************************************
3012 * X11DRV_SelectionRequest_TARGETS
3013 * Service a TARGETS selection request event
3015 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
3016 Atom target, Atom rprop )
3018 UINT i;
3019 Atom* targets;
3020 ULONG cTargets;
3021 LPWINE_CLIPFORMAT lpFormats;
3022 LPWINE_CLIPDATA lpData;
3024 /* Create X atoms for any clipboard types which don't have atoms yet.
3025 * This avoids sending bogus zero atoms.
3026 * Without this, copying might not have access to all clipboard types.
3027 * FIXME: is it safe to call this here?
3029 intern_atoms();
3032 * Count the number of items we wish to expose as selection targets.
3034 cTargets = 1; /* Include TARGETS */
3036 if (!(lpData = ClipData)) return None;
3040 lpFormats = ClipFormats;
3042 while (lpFormats)
3044 if ((lpFormats->wFormatID == lpData->wFormatID) &&
3045 lpFormats->lpDrvExportFunc && lpFormats->drvData)
3046 cTargets++;
3048 lpFormats = lpFormats->NextFormat;
3051 lpData = lpData->NextData;
3053 while (lpData != ClipData);
3055 TRACE(" found %d formats\n", cTargets);
3057 /* Allocate temp buffer */
3058 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
3059 if(targets == NULL)
3060 return None;
3062 i = 0;
3063 lpData = ClipData;
3064 targets[i++] = x11drv_atom(TARGETS);
3068 lpFormats = ClipFormats;
3070 while (lpFormats)
3072 if ((lpFormats->wFormatID == lpData->wFormatID) &&
3073 lpFormats->lpDrvExportFunc && lpFormats->drvData)
3074 targets[i++] = lpFormats->drvData;
3076 lpFormats = lpFormats->NextFormat;
3079 lpData = lpData->NextData;
3081 while (lpData != ClipData);
3083 wine_tsx11_lock();
3085 if (TRACE_ON(clipboard))
3087 unsigned int i;
3088 for ( i = 0; i < cTargets; i++)
3090 char *itemFmtName = XGetAtomName(display, targets[i]);
3091 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3092 XFree(itemFmtName);
3096 /* We may want to consider setting the type to xaTargets instead,
3097 * in case some apps expect this instead of XA_ATOM */
3098 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3099 PropModeReplace, (unsigned char *)targets, cTargets);
3100 wine_tsx11_unlock();
3102 HeapFree(GetProcessHeap(), 0, targets);
3104 return rprop;
3108 /***********************************************************************
3109 * X11DRV_SelectionRequest_MULTIPLE
3110 * Service a MULTIPLE selection request event
3111 * rprop contains a list of (target,property) atom pairs.
3112 * The first atom names a target and the second names a property.
3113 * The effect is as if we have received a sequence of SelectionRequest events
3114 * (one for each atom pair) except that:
3115 * 1. We reply with a SelectionNotify only when all the requested conversions
3116 * have been performed.
3117 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3118 * we replace the atom in the property by None.
3120 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3122 Display *display = pevent->display;
3123 Atom rprop;
3124 Atom atype=AnyPropertyType;
3125 int aformat;
3126 unsigned long remain;
3127 Atom* targetPropList=NULL;
3128 unsigned long cTargetPropList = 0;
3130 /* If the specified property is None the requestor is an obsolete client.
3131 * We support these by using the specified target atom as the reply property.
3133 rprop = pevent->property;
3134 if( rprop == None )
3135 rprop = pevent->target;
3136 if (!rprop)
3137 return 0;
3139 /* Read the MULTIPLE property contents. This should contain a list of
3140 * (target,property) atom pairs.
3142 wine_tsx11_lock();
3143 if(XGetWindowProperty(display, pevent->requestor, rprop,
3144 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3145 &cTargetPropList, &remain,
3146 (unsigned char**)&targetPropList) != Success)
3148 wine_tsx11_unlock();
3149 TRACE("\tCouldn't read MULTIPLE property\n");
3151 else
3153 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3154 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
3155 wine_tsx11_unlock();
3158 * Make sure we got what we expect.
3159 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3160 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3161 * However some X apps(such as XPaint) are not compliant with this and return
3162 * a user defined atom in atype when XGetWindowProperty is called.
3163 * The data *is* an atom pair but is not denoted as such.
3165 if(aformat == 32 /* atype == xAtomPair */ )
3167 unsigned int i;
3169 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3170 * for each (target,property) pair */
3172 for (i = 0; i < cTargetPropList; i+=2)
3174 XSelectionRequestEvent event;
3176 if (TRACE_ON(clipboard))
3178 char *targetName, *propName;
3179 wine_tsx11_lock();
3180 targetName = XGetAtomName(display, targetPropList[i]);
3181 propName = XGetAtomName(display, targetPropList[i+1]);
3182 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3183 i/2, targetName, propName);
3184 XFree(targetName);
3185 XFree(propName);
3186 wine_tsx11_unlock();
3189 /* We must have a non "None" property to service a MULTIPLE target atom */
3190 if ( !targetPropList[i+1] )
3192 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3193 continue;
3196 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3197 event = *pevent;
3198 event.target = targetPropList[i];
3199 event.property = targetPropList[i+1];
3201 /* Fire a SelectionRequest, informing the handler that we are processing
3202 * a MULTIPLE selection request event.
3204 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3208 /* Free the list of targets/properties */
3209 wine_tsx11_lock();
3210 XFree(targetPropList);
3211 wine_tsx11_unlock();
3214 return rprop;
3218 /***********************************************************************
3219 * X11DRV_HandleSelectionRequest
3220 * Process an event selection request event.
3221 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3222 * recursively while servicing a "MULTIPLE" selection target.
3224 * Note: We only receive this event when WINE owns the X selection
3226 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3228 Display *display = event->display;
3229 XSelectionEvent result;
3230 Atom rprop = None;
3231 Window request = event->requestor;
3233 TRACE("\n");
3236 * We can only handle the selection request if :
3237 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3238 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3239 * since this has been already done.
3241 if ( !bIsMultiple )
3243 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3244 goto END;
3247 /* If the specified property is None the requestor is an obsolete client.
3248 * We support these by using the specified target atom as the reply property.
3250 rprop = event->property;
3251 if( rprop == None )
3252 rprop = event->target;
3254 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3256 /* TARGETS selection request */
3257 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3259 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3261 /* MULTIPLE selection request */
3262 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3264 else
3266 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3268 if (lpFormat && lpFormat->lpDrvExportFunc)
3270 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3272 if (lpData)
3274 unsigned char* lpClipData;
3275 DWORD cBytes;
3276 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3277 rprop, lpData, &cBytes);
3279 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3281 int mode = PropModeReplace;
3283 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
3285 wine_tsx11_lock();
3288 int nelements = min(cBytes, 65536);
3289 XChangeProperty(display, request, rprop, event->target,
3290 8, mode, lpClipData, nelements);
3291 mode = PropModeAppend;
3292 cBytes -= nelements;
3293 lpClipData += nelements;
3294 } while (cBytes > 0);
3295 wine_tsx11_unlock();
3297 GlobalUnlock(hClipData);
3298 GlobalFree(hClipData);
3304 END:
3305 /* reply to sender
3306 * SelectionNotify should be sent only at the end of a MULTIPLE request
3308 if ( !bIsMultiple )
3310 result.type = SelectionNotify;
3311 result.display = display;
3312 result.requestor = request;
3313 result.selection = event->selection;
3314 result.property = rprop;
3315 result.target = event->target;
3316 result.time = event->time;
3317 TRACE("Sending SelectionNotify event...\n");
3318 wine_tsx11_lock();
3319 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3320 wine_tsx11_unlock();
3325 /***********************************************************************
3326 * X11DRV_SelectionRequest
3328 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3330 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3334 /***********************************************************************
3335 * X11DRV_SelectionClear
3337 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3339 XSelectionClearEvent *event = &xev->xselectionclear;
3340 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3341 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3342 event->window, hWnd, event->time );
3345 /***********************************************************************
3346 * X11DRV_Clipboard_Cleanup
3348 void X11DRV_Clipboard_Cleanup(void)
3350 selectionAcquired = S_NOSELECTION;
3352 X11DRV_EmptyClipboard(FALSE);