push 149f0a5527ac85057a8ef03858d34d91c36f97e8
[wine/hacks.git] / dlls / winex11.drv / clipboard.c
blob3d9c153547788478e70a83131fa737cbc408f5bc
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 "wine/wingdi16.h"
82 #include "x11drv.h"
83 #include "wine/debug.h"
84 #include "wine/unicode.h"
85 #include "wine/server.h"
87 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
89 #define HGDIOBJ_32(handle16) ((HGDIOBJ)(ULONG_PTR)(handle16))
91 /* Maximum wait time for selection notify */
92 #define SELECTION_RETRIES 500 /* wait for .1 seconds */
93 #define SELECTION_WAIT 1000 /* us */
94 /* Minimum seconds that must lapse between owner queries */
95 #define OWNERQUERYLAPSETIME 1
97 /* Selection masks */
98 #define S_NOSELECTION 0
99 #define S_PRIMARY 1
100 #define S_CLIPBOARD 2
102 typedef struct
104 HWND hWndOpen;
105 HWND hWndOwner;
106 HWND hWndViewer;
107 UINT seqno;
108 UINT flags;
109 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
111 struct tagWINE_CLIPDATA; /* Forward */
113 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
114 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
115 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
117 typedef struct tagWINE_CLIPFORMAT {
118 UINT wFormatID;
119 LPCWSTR Name;
120 UINT drvData;
121 UINT wFlags;
122 DRVIMPORTFUNC lpDrvImportFunc;
123 DRVEXPORTFUNC lpDrvExportFunc;
124 struct tagWINE_CLIPFORMAT *PrevFormat;
125 struct tagWINE_CLIPFORMAT *NextFormat;
126 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
128 typedef struct tagWINE_CLIPDATA {
129 UINT wFormatID;
130 HANDLE16 hData16;
131 HANDLE hData32;
132 UINT wFlags;
133 UINT drvData;
134 LPWINE_CLIPFORMAT lpFormat;
135 struct tagWINE_CLIPDATA *PrevData;
136 struct tagWINE_CLIPDATA *NextData;
137 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
139 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
140 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
141 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
142 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
144 static int selectionAcquired = 0; /* Contains the current selection masks */
145 static Window selectionWindow = None; /* The top level X window which owns the selection */
146 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
148 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned);
149 void CDECL X11DRV_EndClipboardUpdate(void);
150 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
157 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
158 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
159 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
160 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
161 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
162 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
163 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
164 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
166 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
167 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
168 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
169 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
170 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
171 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
172 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
173 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
174 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
175 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
176 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
177 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
178 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
179 unsigned char** data, unsigned long* datasize);
180 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
181 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
182 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
183 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
184 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
185 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
186 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
188 /* Clipboard formats
189 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
190 * declared in clipboard.h
192 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
193 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
194 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
195 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
196 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
197 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
198 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
199 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
200 static const WCHAR wszIMAGEBMP[] = {'i','m','a','g','e','/','b','m','p',0};
201 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
202 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
203 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
204 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
205 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
206 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
207 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
208 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
209 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
210 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
211 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
212 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
213 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
214 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
215 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
217 static WINE_CLIPFORMAT ClipFormats[] =
219 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
220 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
222 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
223 NULL, &ClipFormats[0], &ClipFormats[2]},
225 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
226 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
228 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
229 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
231 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
232 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
234 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
235 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
237 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
238 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
240 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
241 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
243 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
244 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
246 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
247 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
249 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
250 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
252 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
253 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
255 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
256 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
258 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
259 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
260 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
262 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
263 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
265 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
266 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
268 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
269 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
271 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
272 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
274 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
275 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
277 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
278 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
280 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
281 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
283 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
284 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
286 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
287 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], &ClipFormats[23]},
289 { CF_DIB, wszIMAGEBMP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportImageBmp,
290 X11DRV_CLIPBOARD_ExportImageBmp, &ClipFormats[22], NULL},
293 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
295 /* Maps X properties to Windows formats */
296 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
297 static const WCHAR wszGIF[] = {'G','I','F',0};
298 static const WCHAR wszJFIF[] = {'J','F','I','F',0};
299 static const WCHAR wszPNG[] = {'P','N','G',0};
300 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
301 static const struct
303 LPCWSTR lpszFormat;
304 UINT prop;
305 } PropertyFormatMap[] =
307 { wszRichTextFormat, XATOM_text_rtf },
308 { wszRichTextFormat, XATOM_text_richtext },
309 { wszGIF, XATOM_image_gif },
310 { wszJFIF, XATOM_image_jpeg },
311 { wszPNG, XATOM_image_png },
312 { wszHTMLFormat, XATOM_HTML_Format }, /* prefer this to text/html */
317 * Cached clipboard data.
319 static LPWINE_CLIPDATA ClipData = NULL;
320 static UINT ClipDataCount = 0;
323 * Clipboard sequence number
325 static UINT wSeqNo = 0;
327 /**************************************************************************
328 * Internal Clipboard implementation methods
329 **************************************************************************/
331 static Window thread_selection_wnd(void)
333 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
334 Window w = thread_data->selection_wnd;
336 if (!w)
338 XSetWindowAttributes attr;
340 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
341 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
343 wine_tsx11_lock();
344 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
345 InputOutput, CopyFromParent, CWEventMask, &attr);
346 wine_tsx11_unlock();
348 if (w)
349 thread_data->selection_wnd = w;
350 else
351 FIXME("Failed to create window. Fetching selection data will fail.\n");
354 return w;
357 /**************************************************************************
358 * X11DRV_InitClipboard
360 void X11DRV_InitClipboard(void)
362 UINT i;
363 WINE_CLIPFORMAT *format;
365 /* Register known mapping between window formats and X properties */
366 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
367 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
369 /* Set up a conversion function from "HTML Format" to "text/html" */
370 format = X11DRV_CLIPBOARD_InsertClipboardFormat(wszHTMLFormat, GET_ATOM(XATOM_text_html));
371 format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
375 /**************************************************************************
376 * intern_atoms
378 * Intern atoms for formats that don't have one yet.
380 static void intern_atoms(void)
382 LPWINE_CLIPFORMAT format;
383 int i, count, len;
384 char **names;
385 Atom *atoms;
386 Display *display;
388 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
389 if (!format->drvData) count++;
390 if (!count) return;
392 display = thread_init_display();
394 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
395 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
397 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
398 if (!format->drvData) {
399 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
400 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
401 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
405 wine_tsx11_lock();
406 XInternAtoms( display, names, count, False, atoms );
407 wine_tsx11_unlock();
409 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
410 if (!format->drvData) {
411 HeapFree(GetProcessHeap(), 0, names[i]);
412 format->drvData = atoms[i++];
416 HeapFree( GetProcessHeap(), 0, names );
417 HeapFree( GetProcessHeap(), 0, atoms );
421 /**************************************************************************
422 * register_format
424 * Register a custom X clipboard format.
426 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
428 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
430 TRACE("%s\n", debugstr_w(FormatName));
432 /* walk format chain to see if it's already registered */
433 while (lpFormat)
435 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
436 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
437 return lpFormat;
438 lpFormat = lpFormat->NextFormat;
441 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
445 /**************************************************************************
446 * X11DRV_CLIPBOARD_LookupFormat
448 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
450 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
452 while(lpFormat)
454 if (lpFormat->wFormatID == wID)
455 break;
457 lpFormat = lpFormat->NextFormat;
459 if (lpFormat && !lpFormat->drvData) intern_atoms();
460 return lpFormat;
464 /**************************************************************************
465 * X11DRV_CLIPBOARD_LookupProperty
467 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
469 for (;;)
471 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
472 BOOL need_intern = FALSE;
474 if (current)
475 lpFormat = current->NextFormat;
477 while(lpFormat)
479 if (lpFormat->drvData == drvData) return lpFormat;
480 if (!lpFormat->drvData) need_intern = TRUE;
481 lpFormat = lpFormat->NextFormat;
483 if (!need_intern) return NULL;
484 intern_atoms();
485 /* restart the search for the new atoms */
490 /**************************************************************************
491 * X11DRV_CLIPBOARD_LookupData
493 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
495 LPWINE_CLIPDATA lpData = ClipData;
497 if (lpData)
501 if (lpData->wFormatID == wID)
502 break;
504 lpData = lpData->NextData;
506 while(lpData != ClipData);
508 if (lpData->wFormatID != wID)
509 lpData = NULL;
512 return lpData;
516 /**************************************************************************
517 * InsertClipboardFormat
519 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
521 LPWINE_CLIPFORMAT lpFormat;
522 LPWINE_CLIPFORMAT lpNewFormat;
523 LPWSTR new_name;
525 /* allocate storage for new format entry */
526 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
528 if(lpNewFormat == NULL)
530 WARN("No more memory for a new format!\n");
531 return NULL;
534 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
536 WARN("No more memory for the new format name!\n");
537 HeapFree(GetProcessHeap(), 0, lpNewFormat);
538 return NULL;
541 lpNewFormat->Name = strcpyW(new_name, FormatName);
542 lpNewFormat->wFlags = 0;
543 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
544 lpNewFormat->drvData = prop;
545 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
546 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
548 /* Link Format */
549 lpFormat = ClipFormats;
551 while(lpFormat->NextFormat) /* Move to last entry */
552 lpFormat = lpFormat->NextFormat;
554 lpNewFormat->NextFormat = NULL;
555 lpFormat->NextFormat = lpNewFormat;
556 lpNewFormat->PrevFormat = lpFormat;
558 TRACE("Registering format(%04x): %s drvData %d\n",
559 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
561 return lpNewFormat;
567 /**************************************************************************
568 * X11DRV_CLIPBOARD_GetClipboardInfo
570 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
572 BOOL bRet = FALSE;
574 SERVER_START_REQ( set_clipboard_info )
576 req->flags = 0;
578 if (wine_server_call_err( req ))
580 ERR("Failed to get clipboard owner.\n");
582 else
584 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
585 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
586 cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
587 cbInfo->seqno = reply->seqno;
588 cbInfo->flags = reply->flags;
590 bRet = TRUE;
593 SERVER_END_REQ;
595 return bRet;
599 /**************************************************************************
600 * X11DRV_CLIPBOARD_ReleaseOwnership
602 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
604 BOOL bRet = FALSE;
606 SERVER_START_REQ( set_clipboard_info )
608 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
610 if (wine_server_call_err( req ))
612 ERR("Failed to set clipboard.\n");
614 else
616 bRet = TRUE;
619 SERVER_END_REQ;
621 return bRet;
626 /**************************************************************************
627 * X11DRV_CLIPBOARD_InsertClipboardData
629 * Caller *must* have the clipboard open and be the owner.
631 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
632 HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
634 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
636 TRACE("format=%04x lpData=%p hData16=%08x hData32=%p flags=0x%08x lpFormat=%p override=%d\n",
637 wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
639 if (lpData && !override)
640 return TRUE;
642 if (lpData)
644 X11DRV_CLIPBOARD_FreeData(lpData);
646 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
647 lpData->hData32 = hData32;
649 else
651 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
653 lpData->wFormatID = wFormatID;
654 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
655 lpData->hData32 = hData32;
656 lpData->lpFormat = lpFormat;
657 lpData->drvData = 0;
659 if (ClipData)
661 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
663 lpData->PrevData = lpPrevData;
664 lpData->NextData = ClipData;
666 lpPrevData->NextData = lpData;
667 ClipData->PrevData = lpData;
669 else
671 lpData->NextData = lpData;
672 lpData->PrevData = lpData;
673 ClipData = lpData;
676 ClipDataCount++;
679 lpData->wFlags = flags;
681 return TRUE;
685 /**************************************************************************
686 * X11DRV_CLIPBOARD_FreeData
688 * Free clipboard data handle.
690 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
692 TRACE("%04x\n", lpData->wFormatID);
694 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
695 lpData->wFormatID <= CF_GDIOBJLAST) ||
696 lpData->wFormatID == CF_BITMAP ||
697 lpData->wFormatID == CF_DIB ||
698 lpData->wFormatID == CF_PALETTE)
700 if (lpData->hData32)
701 DeleteObject(lpData->hData32);
703 if (lpData->hData16)
704 DeleteObject(HGDIOBJ_32(lpData->hData16));
706 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
707 XFreePixmap(gdi_display, lpData->drvData);
709 else if (lpData->wFormatID == CF_METAFILEPICT)
711 if (lpData->hData32)
713 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
714 GlobalFree(lpData->hData32);
716 if (lpData->hData16)
717 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
718 and a shallow copy is enough to share a METAFILEPICT
719 structure between 16bit and 32bit clipboards. The MetaFile
720 should of course only be deleted once. */
721 GlobalFree16(lpData->hData16);
724 if (lpData->hData16)
726 METAFILEPICT16* lpMetaPict = GlobalLock16(lpData->hData16);
728 if (lpMetaPict)
730 /* To delete 16-bit meta file, we just need to free the associated
731 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
732 GlobalFree16(lpMetaPict->hMF);
733 lpMetaPict->hMF = 0;
736 GlobalFree16(lpData->hData16);
739 else if (lpData->wFormatID == CF_ENHMETAFILE)
741 if (lpData->hData32)
742 DeleteEnhMetaFile(lpData->hData32);
744 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
745 lpData->wFormatID > CF_PRIVATELAST)
747 if (lpData->hData32)
748 GlobalFree(lpData->hData32);
750 if (lpData->hData16)
751 GlobalFree16(lpData->hData16);
754 lpData->hData16 = 0;
755 lpData->hData32 = 0;
756 lpData->drvData = 0;
760 /**************************************************************************
761 * X11DRV_CLIPBOARD_UpdateCache
763 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
765 BOOL bret = TRUE;
767 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
769 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
771 ERR("Failed to retrieve clipboard information.\n");
772 bret = FALSE;
774 else if (wSeqNo < lpcbinfo->seqno)
776 X11DRV_EmptyClipboard(TRUE);
778 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
780 ERR("Failed to cache clipboard data owned by another process.\n");
781 bret = FALSE;
783 else
785 X11DRV_EndClipboardUpdate();
788 wSeqNo = lpcbinfo->seqno;
792 return bret;
796 /**************************************************************************
797 * X11DRV_CLIPBOARD_RenderFormat
799 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
801 BOOL bret = TRUE;
803 TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
804 lpData->wFormatID, lpData->hData32, lpData->hData16);
806 if (lpData->hData32 || lpData->hData16)
807 return bret; /* Already rendered */
809 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
810 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
811 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
813 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
815 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
816 lpData->wFormatID);
817 bret = FALSE;
820 else
822 CLIPBOARDINFO cbInfo;
824 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
826 /* Send a WM_RENDERFORMAT message to notify the owner to render the
827 * data requested into the clipboard.
829 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
830 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
832 if (!lpData->hData32 && !lpData->hData16)
833 bret = FALSE;
835 else
837 ERR("hWndClipOwner is lost!\n");
838 bret = FALSE;
842 return bret;
846 /**************************************************************************
847 * CLIPBOARD_ConvertText
848 * Returns number of required/converted characters - not bytes!
850 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
851 WORD dst_fmt, void *dst, INT dst_size)
853 UINT cp;
855 if(src_fmt == CF_UNICODETEXT)
857 switch(dst_fmt)
859 case CF_TEXT:
860 cp = CP_ACP;
861 break;
862 case CF_OEMTEXT:
863 cp = CP_OEMCP;
864 break;
865 default:
866 return 0;
868 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
871 if(dst_fmt == CF_UNICODETEXT)
873 switch(src_fmt)
875 case CF_TEXT:
876 cp = CP_ACP;
877 break;
878 case CF_OEMTEXT:
879 cp = CP_OEMCP;
880 break;
881 default:
882 return 0;
884 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
887 if(!dst_size) return src_size;
889 if(dst_size > src_size) dst_size = src_size;
891 if(src_fmt == CF_TEXT )
892 CharToOemBuffA(src, dst, dst_size);
893 else
894 OemToCharBuffA(src, dst, dst_size);
896 return dst_size;
900 /**************************************************************************
901 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
903 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
905 BOOL bret = FALSE;
907 TRACE("\n");
909 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
911 UINT wFormatID = lpData->wFormatID;
913 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
914 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
915 else
917 switch (wFormatID)
919 case CF_DIB:
920 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
921 break;
923 case CF_BITMAP:
924 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
925 break;
927 case CF_ENHMETAFILE:
928 case CF_METAFILEPICT:
929 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
930 break;
932 default:
933 FIXME("Called to synthesize unknown format\n");
934 break;
938 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
941 return bret;
945 /**************************************************************************
946 * X11DRV_CLIPBOARD_RenderSynthesizedText
948 * Renders synthesized text
950 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
952 LPCSTR lpstrS;
953 LPSTR lpstrT;
954 HANDLE hData32;
955 INT src_chars, dst_chars, alloc_size;
956 LPWINE_CLIPDATA lpSource = NULL;
958 TRACE("%04x\n", wFormatID);
960 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
961 lpSource->hData32)
962 return TRUE;
964 /* Look for rendered source or non-synthesized source */
965 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
966 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
968 TRACE("UNICODETEXT -> %04x\n", wFormatID);
970 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
971 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
973 TRACE("TEXT -> %04x\n", wFormatID);
975 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
976 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
978 TRACE("OEMTEXT -> %04x\n", wFormatID);
981 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
982 !lpSource->hData32))
983 return FALSE;
985 /* Ask the clipboard owner to render the source text if necessary */
986 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
987 return FALSE;
989 if (lpSource->hData32)
991 lpstrS = GlobalLock(lpSource->hData32);
993 else
995 lpstrS = GlobalLock16(lpSource->hData16);
998 if (!lpstrS)
999 return FALSE;
1001 /* Text always NULL terminated */
1002 if(lpSource->wFormatID == CF_UNICODETEXT)
1003 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
1004 else
1005 src_chars = strlen(lpstrS) + 1;
1007 /* Calculate number of characters in the destination buffer */
1008 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
1009 src_chars, wFormatID, NULL, 0);
1011 if (!dst_chars)
1012 return FALSE;
1014 TRACE("Converting from '%04x' to '%04x', %i chars\n",
1015 lpSource->wFormatID, wFormatID, src_chars);
1017 /* Convert characters to bytes */
1018 if(wFormatID == CF_UNICODETEXT)
1019 alloc_size = dst_chars * sizeof(WCHAR);
1020 else
1021 alloc_size = dst_chars;
1023 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1024 GMEM_DDESHARE, alloc_size);
1026 lpstrT = GlobalLock(hData32);
1028 if (lpstrT)
1030 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1031 wFormatID, lpstrT, dst_chars);
1032 GlobalUnlock(hData32);
1035 /* Unlock source */
1036 if (lpSource->hData32)
1037 GlobalUnlock(lpSource->hData32);
1038 else
1039 GlobalUnlock16(lpSource->hData16);
1041 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1045 /**************************************************************************
1046 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1048 * Renders synthesized DIB
1050 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1052 BOOL bret = FALSE;
1053 LPWINE_CLIPDATA lpSource = NULL;
1055 TRACE("\n");
1057 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1059 bret = TRUE;
1061 /* If we have a bitmap and it's not synthesized or it has been rendered */
1062 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1063 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1065 /* Render source if required */
1066 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1068 HDC hdc;
1069 HGLOBAL hData32;
1071 hdc = GetDC(NULL);
1072 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1073 ReleaseDC(NULL, hdc);
1075 if (hData32)
1077 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1078 bret = TRUE;
1083 return bret;
1087 /**************************************************************************
1088 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1090 * Renders synthesized bitmap
1092 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1094 BOOL bret = FALSE;
1095 LPWINE_CLIPDATA lpSource = NULL;
1097 TRACE("\n");
1099 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1101 bret = TRUE;
1103 /* If we have a dib and it's not synthesized or it has been rendered */
1104 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1105 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1107 /* Render source if required */
1108 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1110 HDC hdc;
1111 HBITMAP hData32;
1112 unsigned int offset;
1113 LPBITMAPINFOHEADER lpbmih;
1115 hdc = GetDC(NULL);
1116 lpbmih = GlobalLock(lpSource->hData32);
1118 offset = sizeof(BITMAPINFOHEADER)
1119 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1120 (1 << lpbmih->biBitCount)) : 0);
1122 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1123 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1125 GlobalUnlock(lpSource->hData32);
1126 ReleaseDC(NULL, hdc);
1128 if (hData32)
1130 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1131 bret = TRUE;
1136 return bret;
1140 /**************************************************************************
1141 * X11DRV_CLIPBOARD_ImportXAString
1143 * Import XA_STRING, converting the string to CF_TEXT.
1145 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1147 LPBYTE lpdata;
1148 unsigned long cbytes;
1149 LPSTR lpstr;
1150 unsigned long i, inlcount = 0;
1151 HANDLE hText = 0;
1153 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1154 return 0;
1156 for (i = 0; i <= cbytes; i++)
1158 if (lpdata[i] == '\n')
1159 inlcount++;
1162 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1164 lpstr = GlobalLock(hText);
1166 for (i = 0, inlcount = 0; i <= cbytes; i++)
1168 if (lpdata[i] == '\n')
1169 lpstr[inlcount++] = '\r';
1171 lpstr[inlcount++] = lpdata[i];
1174 GlobalUnlock(hText);
1177 /* Free the retrieved property data */
1178 HeapFree(GetProcessHeap(), 0, lpdata);
1180 return hText;
1184 /**************************************************************************
1185 * X11DRV_CLIPBOARD_ImportUTF8
1187 * Import XA_STRING, converting the string to CF_UNICODE.
1189 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1191 LPBYTE lpdata;
1192 unsigned long cbytes;
1193 LPSTR lpstr;
1194 unsigned long i, inlcount = 0;
1195 HANDLE hUnicodeText = 0;
1197 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1198 return 0;
1200 for (i = 0; i <= cbytes; i++)
1202 if (lpdata[i] == '\n')
1203 inlcount++;
1206 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1208 UINT count;
1210 for (i = 0, inlcount = 0; i <= cbytes; i++)
1212 if (lpdata[i] == '\n')
1213 lpstr[inlcount++] = '\r';
1215 lpstr[inlcount++] = lpdata[i];
1218 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1219 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1221 if (hUnicodeText)
1223 WCHAR *textW = GlobalLock(hUnicodeText);
1224 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1225 GlobalUnlock(hUnicodeText);
1228 HeapFree(GetProcessHeap(), 0, lpstr);
1231 /* Free the retrieved property data */
1232 HeapFree(GetProcessHeap(), 0, lpdata);
1234 return hUnicodeText;
1238 /**************************************************************************
1239 * X11DRV_CLIPBOARD_ImportCompoundText
1241 * Import COMPOUND_TEXT to CF_UNICODE
1243 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1245 int i, j, ret;
1246 char** srcstr;
1247 int count, lcount;
1248 int srclen, destlen;
1249 HANDLE hUnicodeText;
1250 XTextProperty txtprop;
1252 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1254 return 0;
1257 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1258 txtprop.format = 8;
1259 wine_tsx11_lock();
1260 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1261 wine_tsx11_unlock();
1262 HeapFree(GetProcessHeap(), 0, txtprop.value);
1263 if (ret != Success || !count) return 0;
1265 TRACE("Importing %d line(s)\n", count);
1267 /* Compute number of lines */
1268 srclen = strlen(srcstr[0]);
1269 for (i = 0, lcount = 0; i <= srclen; i++)
1271 if (srcstr[0][i] == '\n')
1272 lcount++;
1275 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1277 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1279 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1281 WCHAR *deststr = GlobalLock(hUnicodeText);
1282 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1284 if (lcount)
1286 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1288 deststr[j] = deststr[i];
1290 if (deststr[i] == '\n')
1291 deststr[--j] = '\r';
1295 GlobalUnlock(hUnicodeText);
1298 wine_tsx11_lock();
1299 XFreeStringList(srcstr);
1300 wine_tsx11_unlock();
1302 return hUnicodeText;
1306 /**************************************************************************
1307 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1309 * Import XA_PIXMAP, converting the image to CF_DIB.
1311 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1313 HWND hwnd;
1314 HDC hdc;
1315 LPBYTE lpdata;
1316 unsigned long cbytes;
1317 Pixmap *pPixmap;
1318 HANDLE hClipData = 0;
1320 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1322 pPixmap = (Pixmap *) lpdata;
1324 hwnd = GetOpenClipboardWindow();
1325 hdc = GetDC(hwnd);
1327 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1328 ReleaseDC(hwnd, hdc);
1330 /* Free the retrieved property data */
1331 HeapFree(GetProcessHeap(), 0, lpdata);
1334 return hClipData;
1338 /**************************************************************************
1339 * X11DRV_CLIPBOARD_ImportImageBmp
1341 * Import image/bmp, converting the image to CF_DIB.
1343 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1345 LPBYTE lpdata;
1346 unsigned long cbytes;
1347 HANDLE hClipData = 0;
1349 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1351 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1353 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1354 bfh->bfType == 0x4d42 /* "BM" */)
1356 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1357 HBITMAP hbmp;
1358 HDC hdc;
1360 hdc = GetDC(0);
1361 hbmp = CreateDIBitmap(
1362 hdc,
1363 &(bmi->bmiHeader),
1364 CBM_INIT,
1365 lpdata+bfh->bfOffBits,
1366 bmi,
1367 DIB_RGB_COLORS
1370 hClipData = X11DRV_DIB_CreateDIBFromBitmap(hdc, hbmp);
1372 DeleteObject(hbmp);
1373 ReleaseDC(0, hdc);
1376 /* Free the retrieved property data */
1377 HeapFree(GetProcessHeap(), 0, lpdata);
1380 return hClipData;
1384 /**************************************************************************
1385 * X11DRV_CLIPBOARD_ImportMetaFilePict
1387 * Import MetaFilePict.
1389 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1391 LPBYTE lpdata;
1392 unsigned long cbytes;
1393 HANDLE hClipData = 0;
1395 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1397 if (cbytes)
1398 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1400 /* Free the retrieved property data */
1401 HeapFree(GetProcessHeap(), 0, lpdata);
1404 return hClipData;
1408 /**************************************************************************
1409 * X11DRV_ImportEnhMetaFile
1411 * Import EnhMetaFile.
1413 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1415 LPBYTE lpdata;
1416 unsigned long cbytes;
1417 HANDLE hClipData = 0;
1419 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1421 if (cbytes)
1422 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1424 /* Free the retrieved property data */
1425 HeapFree(GetProcessHeap(), 0, lpdata);
1428 return hClipData;
1432 /**************************************************************************
1433 * X11DRV_ImportClipbordaData
1435 * Generic import clipboard data routine.
1437 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1439 LPVOID lpClipData;
1440 LPBYTE lpdata;
1441 unsigned long cbytes;
1442 HANDLE hClipData = 0;
1444 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1446 if (cbytes)
1448 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1449 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1450 if (hClipData == 0)
1451 return NULL;
1453 if ((lpClipData = GlobalLock(hClipData)))
1455 memcpy(lpClipData, lpdata, cbytes);
1456 GlobalUnlock(hClipData);
1458 else
1460 GlobalFree(hClipData);
1461 hClipData = 0;
1465 /* Free the retrieved property data */
1466 HeapFree(GetProcessHeap(), 0, lpdata);
1469 return hClipData;
1473 /**************************************************************************
1474 X11DRV_CLIPBOARD_ExportClipboardData
1476 * Generic export clipboard data routine.
1478 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1479 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1481 LPVOID lpClipData;
1482 UINT datasize = 0;
1483 HANDLE hClipData = 0;
1485 *lpBytes = 0; /* Assume failure */
1487 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1488 ERR("Failed to export %04x format\n", lpData->wFormatID);
1489 else
1491 datasize = GlobalSize(lpData->hData32);
1493 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1494 if (hClipData == 0) return NULL;
1496 if ((lpClipData = GlobalLock(hClipData)))
1498 LPVOID lpdata = GlobalLock(lpData->hData32);
1500 memcpy(lpClipData, lpdata, datasize);
1501 *lpBytes = datasize;
1503 GlobalUnlock(lpData->hData32);
1504 GlobalUnlock(hClipData);
1505 } else {
1506 GlobalFree(hClipData);
1507 hClipData = 0;
1511 return hClipData;
1515 /**************************************************************************
1516 * X11DRV_CLIPBOARD_ExportXAString
1518 * Export CF_TEXT converting the string to XA_STRING.
1519 * Helper function for X11DRV_CLIPBOARD_ExportString.
1521 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1523 UINT i, j;
1524 UINT size;
1525 LPSTR text, lpstr = NULL;
1527 *lpBytes = 0; /* Assume return has zero bytes */
1529 text = GlobalLock(lpData->hData32);
1530 size = strlen(text);
1532 /* remove carriage returns */
1533 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1534 if (lpstr == NULL)
1535 goto done;
1537 for (i = 0,j = 0; i < size && text[i]; i++)
1539 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1540 continue;
1541 lpstr[j++] = text[i];
1544 lpstr[j]='\0';
1545 *lpBytes = j; /* Number of bytes in string */
1547 done:
1548 HeapFree(GetProcessHeap(), 0, text);
1549 GlobalUnlock(lpData->hData32);
1551 return lpstr;
1555 /**************************************************************************
1556 * X11DRV_CLIPBOARD_ExportUTF8String
1558 * Export CF_UNICODE converting the string to UTF8.
1559 * Helper function for X11DRV_CLIPBOARD_ExportString.
1561 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1563 UINT i, j;
1564 UINT size;
1565 LPWSTR uni_text;
1566 LPSTR text, lpstr = NULL;
1568 *lpBytes = 0; /* Assume return has zero bytes */
1570 uni_text = GlobalLock(lpData->hData32);
1572 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1574 text = HeapAlloc(GetProcessHeap(), 0, size);
1575 if (!text)
1576 goto done;
1577 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1579 /* remove carriage returns */
1580 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1581 if (lpstr == NULL)
1582 goto done;
1584 for (i = 0,j = 0; i < size && text[i]; i++)
1586 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1587 continue;
1588 lpstr[j++] = text[i];
1590 lpstr[j]='\0';
1592 *lpBytes = j; /* Number of bytes in string */
1594 done:
1595 HeapFree(GetProcessHeap(), 0, text);
1596 GlobalUnlock(lpData->hData32);
1598 return lpstr;
1603 /**************************************************************************
1604 * X11DRV_CLIPBOARD_ExportCompoundText
1606 * Export CF_UNICODE to COMPOUND_TEXT
1607 * Helper function for X11DRV_CLIPBOARD_ExportString.
1609 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1610 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1612 char* lpstr = 0;
1613 XTextProperty prop;
1614 XICCEncodingStyle style;
1615 UINT i, j;
1616 UINT size;
1617 LPWSTR uni_text;
1619 uni_text = GlobalLock(lpData->hData32);
1621 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1622 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1623 if (!lpstr)
1624 return 0;
1626 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1628 /* remove carriage returns */
1629 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1631 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1632 continue;
1633 lpstr[j++] = lpstr[i];
1635 lpstr[j]='\0';
1637 GlobalUnlock(lpData->hData32);
1639 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1640 style = XCompoundTextStyle;
1641 else
1642 style = XStdICCTextStyle;
1644 /* Update the X property */
1645 wine_tsx11_lock();
1646 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1648 XSetTextProperty(display, requestor, &prop, rprop);
1649 XFree(prop.value);
1651 wine_tsx11_unlock();
1653 HeapFree(GetProcessHeap(), 0, lpstr);
1655 return 0;
1658 /**************************************************************************
1659 * X11DRV_CLIPBOARD_ExportString
1661 * Export string
1663 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1664 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1666 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1668 if (aTarget == XA_STRING)
1669 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1670 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1671 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1672 rprop, lpData, lpBytes);
1673 else
1675 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1676 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1679 else
1680 ERR("Failed to render %04x format\n", lpData->wFormatID);
1682 return 0;
1686 /**************************************************************************
1687 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1689 * Export CF_DIB to XA_PIXMAP.
1691 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1692 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1694 HDC hdc;
1695 HANDLE hData;
1696 unsigned char* lpData;
1698 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1700 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1701 return 0;
1704 if (!lpdata->drvData) /* If not already rendered */
1706 /* For convert from packed DIB to Pixmap */
1707 hdc = GetDC(0);
1708 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1709 ReleaseDC(0, hdc);
1712 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1714 /* Wrap pixmap so we can return a handle */
1715 hData = GlobalAlloc(0, *lpBytes);
1716 lpData = GlobalLock(hData);
1717 memcpy(lpData, &lpdata->drvData, *lpBytes);
1718 GlobalUnlock(hData);
1720 return hData;
1724 /**************************************************************************
1725 * X11DRV_CLIPBOARD_ExportImageBmp
1727 * Export CF_DIB to image/bmp.
1729 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1730 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1732 HANDLE hpackeddib;
1733 LPBYTE dibdata;
1734 UINT bmpsize;
1735 HANDLE hbmpdata;
1736 LPBYTE bmpdata;
1737 BITMAPFILEHEADER *bfh;
1739 *lpBytes = 0;
1741 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1743 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1744 return 0;
1747 hpackeddib = lpdata->hData32;
1749 dibdata = GlobalLock(hpackeddib);
1750 if (!dibdata)
1752 ERR("Failed to lock packed DIB\n");
1753 return 0;
1756 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1758 hbmpdata = GlobalAlloc(0, bmpsize);
1760 if (hbmpdata)
1762 bmpdata = GlobalLock(hbmpdata);
1764 if (!bmpdata)
1766 GlobalFree(hbmpdata);
1767 GlobalUnlock(hpackeddib);
1768 return 0;
1771 /* bitmap file header */
1772 bfh = (BITMAPFILEHEADER*)bmpdata;
1773 bfh->bfType = 0x4d42; /* "BM" */
1774 bfh->bfSize = bmpsize;
1775 bfh->bfReserved1 = 0;
1776 bfh->bfReserved2 = 0;
1777 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1779 /* rest of bitmap is the same as the packed dib */
1780 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1782 *lpBytes = bmpsize;
1784 GlobalUnlock(hbmpdata);
1787 GlobalUnlock(hpackeddib);
1789 return hbmpdata;
1793 /**************************************************************************
1794 * X11DRV_CLIPBOARD_ExportMetaFilePict
1796 * Export MetaFilePict.
1798 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1799 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1801 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1803 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1804 return 0;
1807 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1811 /**************************************************************************
1812 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1814 * Export EnhMetaFile.
1816 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1817 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1819 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1821 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1822 return 0;
1825 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1829 /**************************************************************************
1830 * get_html_description_field
1832 * Find the value of a field in an HTML Format description.
1834 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1836 LPCSTR pos=data;
1838 while (pos && *pos && *pos != '<')
1840 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1841 return pos+strlen(keyword);
1843 pos = strchr(pos, '\n');
1844 if (pos) pos++;
1847 return NULL;
1851 /**************************************************************************
1852 * X11DRV_CLIPBOARD_ExportTextHtml
1854 * Export HTML Format to text/html.
1856 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1858 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
1859 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1861 HANDLE hdata;
1862 UINT datasize;
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->hData32;
1878 datasize = GlobalSize(hdata);
1880 data = GlobalLock(hdata);
1881 if (!data)
1883 ERR("Failed to lock HTML Format data\n");
1884 return 0;
1887 /* read the important fields */
1888 field_value = get_html_description_field(data, "StartFragment:");
1889 if (!field_value)
1891 ERR("Couldn't find StartFragment value\n");
1892 goto end;
1894 fragmentstart = atoi(field_value);
1896 field_value = get_html_description_field(data, "EndFragment:");
1897 if (!field_value)
1899 ERR("Couldn't find EndFragment value\n");
1900 goto end;
1902 fragmentend = atoi(field_value);
1904 /* export only the fragment */
1905 htmlsize = fragmentend - fragmentstart + 1;
1907 hhtmldata = GlobalAlloc(0, htmlsize);
1909 if (hhtmldata)
1911 htmldata = GlobalLock(hhtmldata);
1913 if (!htmldata)
1915 GlobalFree(hhtmldata);
1916 htmldata = NULL;
1917 goto end;
1920 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1921 htmldata[htmlsize-1] = '\0';
1923 *lpBytes = htmlsize;
1925 GlobalUnlock(htmldata);
1928 end:
1930 GlobalUnlock(hdata);
1932 return hhtmldata;
1936 /**************************************************************************
1937 * X11DRV_CLIPBOARD_QueryTargets
1939 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1940 Atom target, XEvent *xe)
1942 INT i;
1943 Bool res;
1945 wine_tsx11_lock();
1946 XConvertSelection(display, selection, target,
1947 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1948 wine_tsx11_unlock();
1951 * Wait until SelectionNotify is received
1953 for (i = 0; i < SELECTION_RETRIES; i++)
1955 wine_tsx11_lock();
1956 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1957 wine_tsx11_unlock();
1958 if (res && xe->xselection.selection == selection) break;
1960 usleep(SELECTION_WAIT);
1963 if (i == SELECTION_RETRIES)
1965 ERR("Timed out waiting for SelectionNotify event\n");
1966 return FALSE;
1968 /* Verify that the selection returned a valid TARGETS property */
1969 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1971 /* Selection owner failed to respond or we missed the SelectionNotify */
1972 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1973 return FALSE;
1976 return TRUE;
1980 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1982 return (event->error_code == BadAtom);
1985 /**************************************************************************
1986 * X11DRV_CLIPBOARD_InsertSelectionProperties
1988 * Mark properties available for future retrieval.
1990 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1992 UINT i, nb_atoms = 0;
1993 Atom *atoms = NULL;
1995 /* Cache these formats in the clipboard cache */
1996 for (i = 0; i < count; i++)
1998 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
2000 if (lpFormat)
2002 /* We found at least one Window's format that mapps to the property.
2003 * Continue looking for more.
2005 * If more than one property map to a Window's format then we use the first
2006 * one and ignore the rest.
2008 while (lpFormat)
2010 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
2011 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
2012 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
2013 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2016 else if (properties[i])
2018 /* add it to the list of atoms that we don't know about yet */
2019 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2020 (count - i) * sizeof(*atoms) );
2021 if (atoms) atoms[nb_atoms++] = properties[i];
2025 /* query all unknown atoms in one go */
2026 if (atoms)
2028 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2029 if (names)
2031 X11DRV_expect_error( display, is_atom_error, NULL );
2032 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2033 if (X11DRV_check_error())
2035 WARN( "got some bad atoms, ignoring\n" );
2036 nb_atoms = 0;
2038 for (i = 0; i < nb_atoms; i++)
2040 WINE_CLIPFORMAT *lpFormat;
2041 LPWSTR wname;
2042 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2043 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2044 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2046 lpFormat = register_format( wname, atoms[i] );
2047 HeapFree(GetProcessHeap(), 0, wname);
2048 if (!lpFormat)
2050 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2051 continue;
2053 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
2054 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
2055 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
2057 wine_tsx11_lock();
2058 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2059 wine_tsx11_unlock();
2060 HeapFree( GetProcessHeap(), 0, names );
2062 HeapFree( GetProcessHeap(), 0, atoms );
2067 /**************************************************************************
2068 * X11DRV_CLIPBOARD_QueryAvailableData
2070 * Caches the list of data formats available from the current selection.
2071 * This queries the selection owner for the TARGETS property and saves all
2072 * reported property types.
2074 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
2076 XEvent xe;
2077 Atom atype=AnyPropertyType;
2078 int aformat;
2079 unsigned long remain;
2080 Atom* targetList=NULL;
2081 Window w;
2082 unsigned long cSelectionTargets = 0;
2084 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2086 ERR("Received request to cache selection but process is owner=(%08x)\n",
2087 (unsigned) selectionWindow);
2088 return -1; /* Prevent self request */
2091 w = thread_selection_wnd();
2092 if (!w)
2094 ERR("No window available to retrieve selection!\n");
2095 return -1;
2099 * Query the selection owner for the TARGETS property
2101 wine_tsx11_lock();
2102 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2103 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2105 wine_tsx11_unlock();
2106 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2107 selectionCacheSrc = XA_PRIMARY;
2108 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2109 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2110 else
2112 Atom xstr = XA_STRING;
2114 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2115 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2117 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2118 selectionCacheSrc = XA_PRIMARY;
2119 return 1;
2121 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2123 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2124 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2125 return 1;
2127 else
2129 WARN("Failed to query selection owner for available data.\n");
2130 return -1;
2134 else /* No selection owner so report 0 targets available */
2136 wine_tsx11_unlock();
2137 return 0;
2140 /* Read the TARGETS property contents */
2141 wine_tsx11_lock();
2142 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2143 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2144 &remain, (unsigned char**)&targetList) != Success)
2146 wine_tsx11_unlock();
2147 WARN("Failed to read TARGETS property\n");
2149 else
2151 wine_tsx11_unlock();
2152 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2153 atype, aformat, cSelectionTargets, remain);
2155 * The TARGETS property should have returned us a list of atoms
2156 * corresponding to each selection target format supported.
2158 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2160 if (aformat == 32)
2162 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2164 else if (aformat == 8) /* work around quartz-wm brain damage */
2166 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2167 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2168 for (i = 0; i < count; i++)
2169 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2170 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2171 HeapFree( GetProcessHeap(), 0, atoms );
2175 /* Free the list of targets */
2176 wine_tsx11_lock();
2177 XFree(targetList);
2178 wine_tsx11_unlock();
2181 return cSelectionTargets;
2185 /**************************************************************************
2186 * X11DRV_CLIPBOARD_ReadSelectionData
2188 * This method is invoked only when we DO NOT own the X selection
2190 * We always get the data from the selection client each time,
2191 * since we have no way of determining if the data in our cache is stale.
2193 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2195 Bool res;
2196 DWORD i;
2197 XEvent xe;
2198 BOOL bRet = FALSE;
2200 TRACE("%04x\n", lpData->wFormatID);
2202 if (!lpData->lpFormat)
2204 ERR("Requesting format %04x but no source format linked to data.\n",
2205 lpData->wFormatID);
2206 return FALSE;
2209 if (!selectionAcquired)
2211 Window w = thread_selection_wnd();
2212 if(!w)
2214 ERR("No window available to read selection data!\n");
2215 return FALSE;
2218 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2219 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
2221 wine_tsx11_lock();
2222 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2223 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2224 wine_tsx11_unlock();
2226 /* wait until SelectionNotify is received */
2227 for (i = 0; i < SELECTION_RETRIES; i++)
2229 wine_tsx11_lock();
2230 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2231 wine_tsx11_unlock();
2232 if (res && xe.xselection.selection == selectionCacheSrc) break;
2234 usleep(SELECTION_WAIT);
2237 if (i == SELECTION_RETRIES)
2239 ERR("Timed out waiting for SelectionNotify event\n");
2241 /* Verify that the selection returned a valid TARGETS property */
2242 else if (xe.xselection.property != None)
2245 * Read the contents of the X selection property
2246 * into WINE's clipboard cache and converting the
2247 * data format if necessary.
2249 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2250 xe.xselection.property);
2252 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
2254 else
2256 TRACE("Failed to convert selection\n");
2259 else
2261 ERR("Received request to cache selection data but process is owner\n");
2264 TRACE("Returning %d\n", bRet);
2266 return bRet;
2270 /**************************************************************************
2271 * X11DRV_CLIPBOARD_GetProperty
2272 * Gets type, data and size.
2274 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2275 Atom *atype, unsigned char** data, unsigned long* datasize)
2277 int aformat;
2278 unsigned long pos = 0, nitems, remain, count;
2279 unsigned char *val = NULL, *buffer;
2281 TRACE("Reading property %lu from X window %lx\n", prop, w);
2283 for (;;)
2285 wine_tsx11_lock();
2286 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2287 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2289 wine_tsx11_unlock();
2290 WARN("Failed to read property\n");
2291 HeapFree( GetProcessHeap(), 0, val );
2292 return FALSE;
2295 count = get_property_size( aformat, nitems );
2296 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2297 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2299 if (!*data)
2301 XFree( buffer );
2302 wine_tsx11_unlock();
2303 HeapFree( GetProcessHeap(), 0, val );
2304 return FALSE;
2306 val = *data;
2307 memcpy( (int *)val + pos, buffer, count );
2308 XFree( buffer );
2309 wine_tsx11_unlock();
2310 if (!remain)
2312 *datasize = pos * sizeof(int) + count;
2313 val[*datasize] = 0;
2314 break;
2316 pos += count / sizeof(int);
2319 /* Delete the property on the window now that we are done
2320 * This will send a PropertyNotify event to the selection owner. */
2321 wine_tsx11_lock();
2322 XDeleteProperty(display, w, prop);
2323 wine_tsx11_unlock();
2324 return TRUE;
2328 /**************************************************************************
2329 * X11DRV_CLIPBOARD_ReadProperty
2330 * Reads the contents of the X selection property.
2332 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2333 unsigned char** data, unsigned long* datasize)
2335 Atom atype;
2336 XEvent xe;
2338 if (prop == None)
2339 return FALSE;
2341 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2342 return FALSE;
2344 wine_tsx11_lock();
2345 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2347 wine_tsx11_unlock();
2349 if (atype == x11drv_atom(INCR))
2351 unsigned char *buf = *data;
2352 unsigned long bufsize = 0;
2354 for (;;)
2356 int i;
2357 unsigned char *prop_data, *tmp;
2358 unsigned long prop_size;
2360 /* Wait until PropertyNotify is received */
2361 for (i = 0; i < SELECTION_RETRIES; i++)
2363 Bool res;
2365 wine_tsx11_lock();
2366 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2367 wine_tsx11_unlock();
2368 if (res && xe.xproperty.atom == prop &&
2369 xe.xproperty.state == PropertyNewValue)
2370 break;
2371 usleep(SELECTION_WAIT);
2374 if (i >= SELECTION_RETRIES ||
2375 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2377 HeapFree(GetProcessHeap(), 0, buf);
2378 return FALSE;
2381 /* Retrieved entire data. */
2382 if (prop_size == 0)
2384 HeapFree(GetProcessHeap(), 0, prop_data);
2385 *data = buf;
2386 *datasize = bufsize;
2387 return TRUE;
2390 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2391 if (!tmp)
2393 HeapFree(GetProcessHeap(), 0, buf);
2394 return FALSE;
2397 buf = tmp;
2398 memcpy(buf + bufsize, prop_data, prop_size + 1);
2399 bufsize += prop_size;
2400 HeapFree(GetProcessHeap(), 0, prop_data);
2404 return TRUE;
2408 /**************************************************************************
2409 * CLIPBOARD_SerializeMetafile
2411 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2413 HANDLE h = 0;
2415 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2417 if (out) /* Serialize out, caller should free memory */
2419 *lpcbytes = 0; /* Assume failure */
2421 if (wformat == CF_METAFILEPICT)
2423 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2424 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2426 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2427 if (h)
2429 char *pdata = GlobalLock(h);
2431 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2432 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2434 *lpcbytes = size + sizeof(METAFILEPICT);
2436 GlobalUnlock(h);
2439 GlobalUnlock(hdata);
2441 else if (wformat == CF_ENHMETAFILE)
2443 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2445 h = GlobalAlloc(0, size);
2446 if (h)
2448 LPVOID pdata = GlobalLock(h);
2450 GetEnhMetaFileBits(hdata, size, pdata);
2451 *lpcbytes = size;
2453 GlobalUnlock(h);
2457 else
2459 if (wformat == CF_METAFILEPICT)
2461 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2462 if (h)
2464 unsigned int wiresize, size;
2465 LPMETAFILEPICT lpmfp = GlobalLock(h);
2467 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2468 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2469 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2470 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2471 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
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, HANDLE16 hData16, HANDLE hData32, 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 ((!hData16 && !hData32) ||
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, hData16, hData32, 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 BOOL CDECL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
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->hData32 )
2883 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2885 /* Convert between 32 -> 16 bit data, if necessary */
2886 if (lpRender->hData32 && !lpRender->hData16)
2888 int size;
2890 if (lpRender->wFormatID == CF_METAFILEPICT)
2891 size = sizeof(METAFILEPICT16);
2892 else
2893 size = GlobalSize(lpRender->hData32);
2895 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2897 if (!lpRender->hData16)
2898 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2899 else
2901 if (lpRender->wFormatID == CF_METAFILEPICT)
2903 FIXME("\timplement function CopyMetaFilePict32to16\n");
2904 FIXME("\tin the appropriate file.\n");
2905 #ifdef SOMEONE_IMPLEMENTED_ME
2906 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2907 GlobalLock(lpRender->hData32));
2908 #endif
2910 else
2912 memcpy(GlobalLock16(lpRender->hData16),
2913 GlobalLock(lpRender->hData32), size);
2916 GlobalUnlock16(lpRender->hData16);
2917 GlobalUnlock(lpRender->hData32);
2921 /* Convert between 32 -> 16 bit data, if necessary */
2922 if (lpRender->hData16 && !lpRender->hData32)
2924 int size;
2926 if (lpRender->wFormatID == CF_METAFILEPICT)
2927 size = sizeof(METAFILEPICT16);
2928 else
2929 size = GlobalSize(lpRender->hData32);
2931 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2932 GMEM_DDESHARE, size);
2934 if (lpRender->wFormatID == CF_METAFILEPICT)
2936 FIXME("\timplement function CopyMetaFilePict16to32\n");
2937 FIXME("\tin the appropriate file.\n");
2938 #ifdef SOMEONE_IMPLEMENTED_ME
2939 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2940 GlobalLock(lpRender->hData16));
2941 #endif
2943 else
2945 memcpy(GlobalLock(lpRender->hData32),
2946 GlobalLock16(lpRender->hData16), size);
2949 GlobalUnlock(lpRender->hData32);
2950 GlobalUnlock16(lpRender->hData16);
2953 if (phData16)
2954 *phData16 = lpRender->hData16;
2956 if (phData32)
2957 *phData32 = lpRender->hData32;
2959 TRACE(" returning hData16(%04x) hData32(%p) (type %04x)\n",
2960 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2962 return lpRender->hData16 || lpRender->hData32;
2965 return 0;
2969 /**************************************************************************
2970 * ResetSelectionOwner
2972 * Called when the thread owning the selection is destroyed and we need to
2973 * preserve the selection ownership. We look for another top level window
2974 * in this process and send it a message to acquire the selection.
2976 void X11DRV_ResetSelectionOwner(void)
2978 HWND hwnd;
2979 DWORD procid;
2981 TRACE("\n");
2983 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2984 return;
2986 selectionAcquired = S_NOSELECTION;
2987 selectionWindow = 0;
2989 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2992 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2994 if (GetCurrentProcessId() == procid)
2996 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2997 return;
3000 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
3002 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
3004 X11DRV_CLIPBOARD_ReleaseOwnership();
3005 X11DRV_EmptyClipboard(FALSE);
3009 /**************************************************************************
3010 * X11DRV_CLIPBOARD_SynthesizeData
3012 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
3014 BOOL bsyn = TRUE;
3015 LPWINE_CLIPDATA lpSource = NULL;
3017 TRACE(" %04x\n", wFormatID);
3019 /* Don't need to synthesize if it already exists */
3020 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
3021 return TRUE;
3023 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
3025 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
3026 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3027 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
3028 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3029 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
3030 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
3032 else if (wFormatID == CF_ENHMETAFILE)
3034 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
3035 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3037 else if (wFormatID == CF_METAFILEPICT)
3039 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
3040 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3042 else if (wFormatID == CF_DIB)
3044 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
3045 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3047 else if (wFormatID == CF_BITMAP)
3049 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
3050 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3053 if (bsyn)
3054 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
3056 return bsyn;
3061 /**************************************************************************
3062 * X11DRV_EndClipboardUpdate
3063 * TODO:
3064 * Add locale if it hasn't already been added
3066 void CDECL X11DRV_EndClipboardUpdate(void)
3068 INT count = ClipDataCount;
3070 /* Do Unicode <-> Text <-> OEM mapping */
3071 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
3072 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
3073 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
3075 /* Enhmetafile <-> MetafilePict mapping */
3076 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
3077 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
3079 /* DIB <-> Bitmap mapping */
3080 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
3081 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
3083 TRACE("%d formats added to cached data\n", ClipDataCount - count);
3087 /***********************************************************************
3088 * X11DRV_SelectionRequest_TARGETS
3089 * Service a TARGETS selection request event
3091 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
3092 Atom target, Atom rprop )
3094 UINT i;
3095 Atom* targets;
3096 ULONG cTargets;
3097 LPWINE_CLIPFORMAT lpFormats;
3098 LPWINE_CLIPDATA lpData;
3100 /* Create X atoms for any clipboard types which don't have atoms yet.
3101 * This avoids sending bogus zero atoms.
3102 * Without this, copying might not have access to all clipboard types.
3103 * FIXME: is it safe to call this here?
3105 intern_atoms();
3108 * Count the number of items we wish to expose as selection targets.
3110 cTargets = 1; /* Include TARGETS */
3112 if (!(lpData = ClipData)) return None;
3116 lpFormats = ClipFormats;
3118 while (lpFormats)
3120 if ((lpFormats->wFormatID == lpData->wFormatID) &&
3121 lpFormats->lpDrvExportFunc && lpFormats->drvData)
3122 cTargets++;
3124 lpFormats = lpFormats->NextFormat;
3127 lpData = lpData->NextData;
3129 while (lpData != ClipData);
3131 TRACE(" found %d formats\n", cTargets);
3133 /* Allocate temp buffer */
3134 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
3135 if(targets == NULL)
3136 return None;
3138 i = 0;
3139 lpData = ClipData;
3140 targets[i++] = x11drv_atom(TARGETS);
3144 lpFormats = ClipFormats;
3146 while (lpFormats)
3148 if ((lpFormats->wFormatID == lpData->wFormatID) &&
3149 lpFormats->lpDrvExportFunc && lpFormats->drvData)
3150 targets[i++] = lpFormats->drvData;
3152 lpFormats = lpFormats->NextFormat;
3155 lpData = lpData->NextData;
3157 while (lpData != ClipData);
3159 wine_tsx11_lock();
3161 if (TRACE_ON(clipboard))
3163 unsigned int i;
3164 for ( i = 0; i < cTargets; i++)
3166 char *itemFmtName = XGetAtomName(display, targets[i]);
3167 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3168 XFree(itemFmtName);
3172 /* We may want to consider setting the type to xaTargets instead,
3173 * in case some apps expect this instead of XA_ATOM */
3174 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3175 PropModeReplace, (unsigned char *)targets, cTargets);
3176 wine_tsx11_unlock();
3178 HeapFree(GetProcessHeap(), 0, targets);
3180 return rprop;
3184 /***********************************************************************
3185 * X11DRV_SelectionRequest_MULTIPLE
3186 * Service a MULTIPLE selection request event
3187 * rprop contains a list of (target,property) atom pairs.
3188 * The first atom names a target and the second names a property.
3189 * The effect is as if we have received a sequence of SelectionRequest events
3190 * (one for each atom pair) except that:
3191 * 1. We reply with a SelectionNotify only when all the requested conversions
3192 * have been performed.
3193 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3194 * we replace the atom in the property by None.
3196 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3198 Display *display = pevent->display;
3199 Atom rprop;
3200 Atom atype=AnyPropertyType;
3201 int aformat;
3202 unsigned long remain;
3203 Atom* targetPropList=NULL;
3204 unsigned long cTargetPropList = 0;
3206 /* If the specified property is None the requestor is an obsolete client.
3207 * We support these by using the specified target atom as the reply property.
3209 rprop = pevent->property;
3210 if( rprop == None )
3211 rprop = pevent->target;
3212 if (!rprop)
3213 return 0;
3215 /* Read the MULTIPLE property contents. This should contain a list of
3216 * (target,property) atom pairs.
3218 wine_tsx11_lock();
3219 if(XGetWindowProperty(display, pevent->requestor, rprop,
3220 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3221 &cTargetPropList, &remain,
3222 (unsigned char**)&targetPropList) != Success)
3224 wine_tsx11_unlock();
3225 TRACE("\tCouldn't read MULTIPLE property\n");
3227 else
3229 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3230 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
3231 wine_tsx11_unlock();
3234 * Make sure we got what we expect.
3235 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3236 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3237 * However some X apps(such as XPaint) are not compliant with this and return
3238 * a user defined atom in atype when XGetWindowProperty is called.
3239 * The data *is* an atom pair but is not denoted as such.
3241 if(aformat == 32 /* atype == xAtomPair */ )
3243 unsigned int i;
3245 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3246 * for each (target,property) pair */
3248 for (i = 0; i < cTargetPropList; i+=2)
3250 XSelectionRequestEvent event;
3252 if (TRACE_ON(clipboard))
3254 char *targetName, *propName;
3255 wine_tsx11_lock();
3256 targetName = XGetAtomName(display, targetPropList[i]);
3257 propName = XGetAtomName(display, targetPropList[i+1]);
3258 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3259 i/2, targetName, propName);
3260 XFree(targetName);
3261 XFree(propName);
3262 wine_tsx11_unlock();
3265 /* We must have a non "None" property to service a MULTIPLE target atom */
3266 if ( !targetPropList[i+1] )
3268 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3269 continue;
3272 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3273 event = *pevent;
3274 event.target = targetPropList[i];
3275 event.property = targetPropList[i+1];
3277 /* Fire a SelectionRequest, informing the handler that we are processing
3278 * a MULTIPLE selection request event.
3280 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3284 /* Free the list of targets/properties */
3285 wine_tsx11_lock();
3286 XFree(targetPropList);
3287 wine_tsx11_unlock();
3290 return rprop;
3294 /***********************************************************************
3295 * X11DRV_HandleSelectionRequest
3296 * Process an event selection request event.
3297 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3298 * recursively while servicing a "MULTIPLE" selection target.
3300 * Note: We only receive this event when WINE owns the X selection
3302 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3304 Display *display = event->display;
3305 XSelectionEvent result;
3306 Atom rprop = None;
3307 Window request = event->requestor;
3309 TRACE("\n");
3312 * We can only handle the selection request if :
3313 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3314 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3315 * since this has been already done.
3317 if ( !bIsMultiple )
3319 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3320 goto END;
3323 /* If the specified property is None the requestor is an obsolete client.
3324 * We support these by using the specified target atom as the reply property.
3326 rprop = event->property;
3327 if( rprop == None )
3328 rprop = event->target;
3330 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3332 /* TARGETS selection request */
3333 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3335 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3337 /* MULTIPLE selection request */
3338 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3340 else
3342 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3344 if (lpFormat && lpFormat->lpDrvExportFunc)
3346 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3348 if (lpData)
3350 unsigned char* lpClipData;
3351 DWORD cBytes;
3352 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3353 rprop, lpData, &cBytes);
3355 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3357 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
3359 wine_tsx11_lock();
3360 XChangeProperty(display, request, rprop, event->target,
3361 8, PropModeReplace, lpClipData, cBytes);
3362 wine_tsx11_unlock();
3364 GlobalUnlock(hClipData);
3365 GlobalFree(hClipData);
3371 END:
3372 /* reply to sender
3373 * SelectionNotify should be sent only at the end of a MULTIPLE request
3375 if ( !bIsMultiple )
3377 result.type = SelectionNotify;
3378 result.display = display;
3379 result.requestor = request;
3380 result.selection = event->selection;
3381 result.property = rprop;
3382 result.target = event->target;
3383 result.time = event->time;
3384 TRACE("Sending SelectionNotify event...\n");
3385 wine_tsx11_lock();
3386 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3387 wine_tsx11_unlock();
3392 /***********************************************************************
3393 * X11DRV_SelectionRequest
3395 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3397 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3401 /***********************************************************************
3402 * X11DRV_SelectionClear
3404 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3406 XSelectionClearEvent *event = &xev->xselectionclear;
3407 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3408 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3409 event->window, hWnd, event->time );