push bf07e57c7285aac9a4b820bd27ad9b8768385b88
[wine/hacks.git] / dlls / winex11.drv / clipboard.c
blob5a042f6ab1c55807ba291274c8192a2056850370
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_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
166 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
167 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
168 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
169 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
170 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
171 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
172 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
173 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
174 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
175 unsigned char** data, unsigned long* datasize);
176 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
177 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
178 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
180 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
181 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
182 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
184 /* Clipboard formats
185 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
186 * declared in clipboard.h
188 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
189 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
190 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
191 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
192 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
193 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
194 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
195 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
196 static const WCHAR wszIMAGEBMP[] = {'i','m','a','g','e','/','b','m','p',0};
197 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
198 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
199 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
200 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
201 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
202 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
203 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
204 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
205 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
206 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
207 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
208 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
209 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
210 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
211 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
213 static WINE_CLIPFORMAT ClipFormats[] =
215 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
216 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
218 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
219 NULL, &ClipFormats[0], &ClipFormats[2]},
221 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
222 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
224 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
225 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
227 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
228 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
230 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
231 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
233 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
234 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
236 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
237 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
239 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
240 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
242 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
243 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
245 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
246 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
248 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
249 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
251 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
252 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
254 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
255 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
256 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
258 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
259 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
261 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
262 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
264 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
265 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
267 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
268 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
270 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
271 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
273 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
274 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
276 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
277 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
279 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
280 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
282 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
283 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], &ClipFormats[23]},
285 { CF_DIB, wszIMAGEBMP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportImageBmp,
286 NULL, &ClipFormats[22], NULL},
289 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
291 /* Maps X properties to Windows formats */
292 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
293 static const WCHAR wszGIF[] = {'G','I','F',0};
294 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
295 static const struct
297 LPCWSTR lpszFormat;
298 UINT prop;
299 } PropertyFormatMap[] =
301 { wszRichTextFormat, XATOM_text_rtf },
302 { wszRichTextFormat, XATOM_text_richtext },
303 { wszGIF, XATOM_image_gif },
304 { wszHTMLFormat, XATOM_text_html },
309 * Cached clipboard data.
311 static LPWINE_CLIPDATA ClipData = NULL;
312 static UINT ClipDataCount = 0;
315 * Clipboard sequence number
317 static UINT wSeqNo = 0;
319 /**************************************************************************
320 * Internal Clipboard implementation methods
321 **************************************************************************/
323 static Window thread_selection_wnd(void)
325 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
326 Window w = thread_data->selection_wnd;
328 if (!w)
330 XSetWindowAttributes attr;
332 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
333 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
335 wine_tsx11_lock();
336 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
337 InputOutput, CopyFromParent, CWEventMask, &attr);
338 wine_tsx11_unlock();
340 if (w)
341 thread_data->selection_wnd = w;
342 else
343 FIXME("Failed to create window. Fetching selection data will fail.\n");
346 return w;
349 /**************************************************************************
350 * X11DRV_InitClipboard
352 void X11DRV_InitClipboard(void)
354 UINT i;
356 /* Register known mapping between window formats and X properties */
357 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
358 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
362 /**************************************************************************
363 * intern_atoms
365 * Intern atoms for formats that don't have one yet.
367 static void intern_atoms(void)
369 LPWINE_CLIPFORMAT format;
370 int i, count, len;
371 char **names;
372 Atom *atoms;
373 Display *display;
375 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
376 if (!format->drvData) count++;
377 if (!count) return;
379 display = thread_init_display();
381 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
382 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
384 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
385 if (!format->drvData) {
386 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
387 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
388 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
392 wine_tsx11_lock();
393 XInternAtoms( display, names, count, False, atoms );
394 wine_tsx11_unlock();
396 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
397 if (!format->drvData) {
398 HeapFree(GetProcessHeap(), 0, names[i]);
399 format->drvData = atoms[i++];
403 HeapFree( GetProcessHeap(), 0, names );
404 HeapFree( GetProcessHeap(), 0, atoms );
408 /**************************************************************************
409 * register_format
411 * Register a custom X clipboard format.
413 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
415 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
417 TRACE("%s\n", debugstr_w(FormatName));
419 /* walk format chain to see if it's already registered */
420 while (lpFormat)
422 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
423 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
424 return lpFormat;
425 lpFormat = lpFormat->NextFormat;
428 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
432 /**************************************************************************
433 * X11DRV_CLIPBOARD_LookupFormat
435 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
437 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
439 while(lpFormat)
441 if (lpFormat->wFormatID == wID)
442 break;
444 lpFormat = lpFormat->NextFormat;
446 if (lpFormat && !lpFormat->drvData) intern_atoms();
447 return lpFormat;
451 /**************************************************************************
452 * X11DRV_CLIPBOARD_LookupProperty
454 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
456 for (;;)
458 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
459 BOOL need_intern = FALSE;
461 if (current)
462 lpFormat = current->NextFormat;
464 while(lpFormat)
466 if (lpFormat->drvData == drvData) return lpFormat;
467 if (!lpFormat->drvData) need_intern = TRUE;
468 lpFormat = lpFormat->NextFormat;
470 if (!need_intern) return NULL;
471 intern_atoms();
472 /* restart the search for the new atoms */
477 /**************************************************************************
478 * X11DRV_CLIPBOARD_LookupData
480 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
482 LPWINE_CLIPDATA lpData = ClipData;
484 if (lpData)
488 if (lpData->wFormatID == wID)
489 break;
491 lpData = lpData->NextData;
493 while(lpData != ClipData);
495 if (lpData->wFormatID != wID)
496 lpData = NULL;
499 return lpData;
503 /**************************************************************************
504 * InsertClipboardFormat
506 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
508 LPWINE_CLIPFORMAT lpFormat;
509 LPWINE_CLIPFORMAT lpNewFormat;
510 LPWSTR new_name;
512 /* allocate storage for new format entry */
513 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
515 if(lpNewFormat == NULL)
517 WARN("No more memory for a new format!\n");
518 return NULL;
521 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
523 WARN("No more memory for the new format name!\n");
524 HeapFree(GetProcessHeap(), 0, lpNewFormat);
525 return NULL;
528 lpNewFormat->Name = strcpyW(new_name, FormatName);
529 lpNewFormat->wFlags = 0;
530 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
531 lpNewFormat->drvData = prop;
532 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
533 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
535 /* Link Format */
536 lpFormat = ClipFormats;
538 while(lpFormat->NextFormat) /* Move to last entry */
539 lpFormat = lpFormat->NextFormat;
541 lpNewFormat->NextFormat = NULL;
542 lpFormat->NextFormat = lpNewFormat;
543 lpNewFormat->PrevFormat = lpFormat;
545 TRACE("Registering format(%04x): %s drvData %d\n",
546 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
548 return lpNewFormat;
554 /**************************************************************************
555 * X11DRV_CLIPBOARD_GetClipboardInfo
557 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
559 BOOL bRet = FALSE;
561 SERVER_START_REQ( set_clipboard_info )
563 req->flags = 0;
565 if (wine_server_call_err( req ))
567 ERR("Failed to get clipboard owner.\n");
569 else
571 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
572 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
573 cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
574 cbInfo->seqno = reply->seqno;
575 cbInfo->flags = reply->flags;
577 bRet = TRUE;
580 SERVER_END_REQ;
582 return bRet;
586 /**************************************************************************
587 * X11DRV_CLIPBOARD_ReleaseOwnership
589 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
591 BOOL bRet = FALSE;
593 SERVER_START_REQ( set_clipboard_info )
595 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
597 if (wine_server_call_err( req ))
599 ERR("Failed to set clipboard.\n");
601 else
603 bRet = TRUE;
606 SERVER_END_REQ;
608 return bRet;
613 /**************************************************************************
614 * X11DRV_CLIPBOARD_InsertClipboardData
616 * Caller *must* have the clipboard open and be the owner.
618 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
619 HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
621 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
623 TRACE("format=%04x lpData=%p hData16=%08x hData32=%p flags=0x%08x lpFormat=%p override=%d\n",
624 wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
626 if (lpData && !override)
627 return TRUE;
629 if (lpData)
631 X11DRV_CLIPBOARD_FreeData(lpData);
633 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
634 lpData->hData32 = hData32;
636 else
638 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
640 lpData->wFormatID = wFormatID;
641 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
642 lpData->hData32 = hData32;
643 lpData->lpFormat = lpFormat;
644 lpData->drvData = 0;
646 if (ClipData)
648 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
650 lpData->PrevData = lpPrevData;
651 lpData->NextData = ClipData;
653 lpPrevData->NextData = lpData;
654 ClipData->PrevData = lpData;
656 else
658 lpData->NextData = lpData;
659 lpData->PrevData = lpData;
660 ClipData = lpData;
663 ClipDataCount++;
666 lpData->wFlags = flags;
668 return TRUE;
672 /**************************************************************************
673 * X11DRV_CLIPBOARD_FreeData
675 * Free clipboard data handle.
677 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
679 TRACE("%04x\n", lpData->wFormatID);
681 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
682 lpData->wFormatID <= CF_GDIOBJLAST) ||
683 lpData->wFormatID == CF_BITMAP ||
684 lpData->wFormatID == CF_DIB ||
685 lpData->wFormatID == CF_PALETTE)
687 if (lpData->hData32)
688 DeleteObject(lpData->hData32);
690 if (lpData->hData16)
691 DeleteObject(HGDIOBJ_32(lpData->hData16));
693 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
694 XFreePixmap(gdi_display, lpData->drvData);
696 else if (lpData->wFormatID == CF_METAFILEPICT)
698 if (lpData->hData32)
700 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
701 GlobalFree(lpData->hData32);
703 if (lpData->hData16)
704 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
705 and a shallow copy is enough to share a METAFILEPICT
706 structure between 16bit and 32bit clipboards. The MetaFile
707 should of course only be deleted once. */
708 GlobalFree16(lpData->hData16);
711 if (lpData->hData16)
713 METAFILEPICT16* lpMetaPict = GlobalLock16(lpData->hData16);
715 if (lpMetaPict)
717 /* To delete 16-bit meta file, we just need to free the associated
718 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
719 GlobalFree16(lpMetaPict->hMF);
720 lpMetaPict->hMF = 0;
723 GlobalFree16(lpData->hData16);
726 else if (lpData->wFormatID == CF_ENHMETAFILE)
728 if (lpData->hData32)
729 DeleteEnhMetaFile(lpData->hData32);
731 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
732 lpData->wFormatID > CF_PRIVATELAST)
734 if (lpData->hData32)
735 GlobalFree(lpData->hData32);
737 if (lpData->hData16)
738 GlobalFree16(lpData->hData16);
741 lpData->hData16 = 0;
742 lpData->hData32 = 0;
743 lpData->drvData = 0;
747 /**************************************************************************
748 * X11DRV_CLIPBOARD_UpdateCache
750 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
752 BOOL bret = TRUE;
754 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
756 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
758 ERR("Failed to retrieve clipboard information.\n");
759 bret = FALSE;
761 else if (wSeqNo < lpcbinfo->seqno)
763 X11DRV_EmptyClipboard(TRUE);
765 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
767 ERR("Failed to cache clipboard data owned by another process.\n");
768 bret = FALSE;
770 else
772 X11DRV_EndClipboardUpdate();
775 wSeqNo = lpcbinfo->seqno;
779 return bret;
783 /**************************************************************************
784 * X11DRV_CLIPBOARD_RenderFormat
786 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
788 BOOL bret = TRUE;
790 TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
791 lpData->wFormatID, lpData->hData32, lpData->hData16);
793 if (lpData->hData32 || lpData->hData16)
794 return bret; /* Already rendered */
796 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
797 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
798 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
800 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
802 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
803 lpData->wFormatID);
804 bret = FALSE;
807 else
809 CLIPBOARDINFO cbInfo;
811 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
813 /* Send a WM_RENDERFORMAT message to notify the owner to render the
814 * data requested into the clipboard.
816 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
817 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
819 if (!lpData->hData32 && !lpData->hData16)
820 bret = FALSE;
822 else
824 ERR("hWndClipOwner is lost!\n");
825 bret = FALSE;
829 return bret;
833 /**************************************************************************
834 * CLIPBOARD_ConvertText
835 * Returns number of required/converted characters - not bytes!
837 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
838 WORD dst_fmt, void *dst, INT dst_size)
840 UINT cp;
842 if(src_fmt == CF_UNICODETEXT)
844 switch(dst_fmt)
846 case CF_TEXT:
847 cp = CP_ACP;
848 break;
849 case CF_OEMTEXT:
850 cp = CP_OEMCP;
851 break;
852 default:
853 return 0;
855 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
858 if(dst_fmt == CF_UNICODETEXT)
860 switch(src_fmt)
862 case CF_TEXT:
863 cp = CP_ACP;
864 break;
865 case CF_OEMTEXT:
866 cp = CP_OEMCP;
867 break;
868 default:
869 return 0;
871 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
874 if(!dst_size) return src_size;
876 if(dst_size > src_size) dst_size = src_size;
878 if(src_fmt == CF_TEXT )
879 CharToOemBuffA(src, dst, dst_size);
880 else
881 OemToCharBuffA(src, dst, dst_size);
883 return dst_size;
887 /**************************************************************************
888 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
890 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
892 BOOL bret = FALSE;
894 TRACE("\n");
896 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
898 UINT wFormatID = lpData->wFormatID;
900 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
901 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
902 else
904 switch (wFormatID)
906 case CF_DIB:
907 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
908 break;
910 case CF_BITMAP:
911 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
912 break;
914 case CF_ENHMETAFILE:
915 case CF_METAFILEPICT:
916 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
917 break;
919 default:
920 FIXME("Called to synthesize unknown format\n");
921 break;
925 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
928 return bret;
932 /**************************************************************************
933 * X11DRV_CLIPBOARD_RenderSynthesizedText
935 * Renders synthesized text
937 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
939 LPCSTR lpstrS;
940 LPSTR lpstrT;
941 HANDLE hData32;
942 INT src_chars, dst_chars, alloc_size;
943 LPWINE_CLIPDATA lpSource = NULL;
945 TRACE("%04x\n", wFormatID);
947 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
948 lpSource->hData32)
949 return TRUE;
951 /* Look for rendered source or non-synthesized source */
952 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
953 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
955 TRACE("UNICODETEXT -> %04x\n", wFormatID);
957 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
958 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
960 TRACE("TEXT -> %04x\n", wFormatID);
962 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
963 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
965 TRACE("OEMTEXT -> %04x\n", wFormatID);
968 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
969 !lpSource->hData32))
970 return FALSE;
972 /* Ask the clipboard owner to render the source text if necessary */
973 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
974 return FALSE;
976 if (lpSource->hData32)
978 lpstrS = GlobalLock(lpSource->hData32);
980 else
982 lpstrS = GlobalLock16(lpSource->hData16);
985 if (!lpstrS)
986 return FALSE;
988 /* Text always NULL terminated */
989 if(lpSource->wFormatID == CF_UNICODETEXT)
990 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
991 else
992 src_chars = strlen(lpstrS) + 1;
994 /* Calculate number of characters in the destination buffer */
995 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
996 src_chars, wFormatID, NULL, 0);
998 if (!dst_chars)
999 return FALSE;
1001 TRACE("Converting from '%04x' to '%04x', %i chars\n",
1002 lpSource->wFormatID, wFormatID, src_chars);
1004 /* Convert characters to bytes */
1005 if(wFormatID == CF_UNICODETEXT)
1006 alloc_size = dst_chars * sizeof(WCHAR);
1007 else
1008 alloc_size = dst_chars;
1010 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1011 GMEM_DDESHARE, alloc_size);
1013 lpstrT = GlobalLock(hData32);
1015 if (lpstrT)
1017 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1018 wFormatID, lpstrT, dst_chars);
1019 GlobalUnlock(hData32);
1022 /* Unlock source */
1023 if (lpSource->hData32)
1024 GlobalUnlock(lpSource->hData32);
1025 else
1026 GlobalUnlock16(lpSource->hData16);
1028 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1032 /**************************************************************************
1033 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1035 * Renders synthesized DIB
1037 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1039 BOOL bret = FALSE;
1040 LPWINE_CLIPDATA lpSource = NULL;
1042 TRACE("\n");
1044 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1046 bret = TRUE;
1048 /* If we have a bitmap and it's not synthesized or it has been rendered */
1049 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1050 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1052 /* Render source if required */
1053 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1055 HDC hdc;
1056 HGLOBAL hData32;
1058 hdc = GetDC(NULL);
1059 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1060 ReleaseDC(NULL, hdc);
1062 if (hData32)
1064 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1065 bret = TRUE;
1070 return bret;
1074 /**************************************************************************
1075 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1077 * Renders synthesized bitmap
1079 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1081 BOOL bret = FALSE;
1082 LPWINE_CLIPDATA lpSource = NULL;
1084 TRACE("\n");
1086 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1088 bret = TRUE;
1090 /* If we have a dib and it's not synthesized or it has been rendered */
1091 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1092 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1094 /* Render source if required */
1095 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1097 HDC hdc;
1098 HBITMAP hData32;
1099 unsigned int offset;
1100 LPBITMAPINFOHEADER lpbmih;
1102 hdc = GetDC(NULL);
1103 lpbmih = GlobalLock(lpSource->hData32);
1105 offset = sizeof(BITMAPINFOHEADER)
1106 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1107 (1 << lpbmih->biBitCount)) : 0);
1109 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1110 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1112 GlobalUnlock(lpSource->hData32);
1113 ReleaseDC(NULL, hdc);
1115 if (hData32)
1117 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1118 bret = TRUE;
1123 return bret;
1127 /**************************************************************************
1128 * X11DRV_CLIPBOARD_ImportXAString
1130 * Import XA_STRING, converting the string to CF_TEXT.
1132 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1134 LPBYTE lpdata;
1135 unsigned long cbytes;
1136 LPSTR lpstr;
1137 unsigned long i, inlcount = 0;
1138 HANDLE hText = 0;
1140 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1141 return 0;
1143 for (i = 0; i <= cbytes; i++)
1145 if (lpdata[i] == '\n')
1146 inlcount++;
1149 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1151 lpstr = GlobalLock(hText);
1153 for (i = 0, inlcount = 0; i <= cbytes; i++)
1155 if (lpdata[i] == '\n')
1156 lpstr[inlcount++] = '\r';
1158 lpstr[inlcount++] = lpdata[i];
1161 GlobalUnlock(hText);
1164 /* Free the retrieved property data */
1165 HeapFree(GetProcessHeap(), 0, lpdata);
1167 return hText;
1171 /**************************************************************************
1172 * X11DRV_CLIPBOARD_ImportUTF8
1174 * Import XA_STRING, converting the string to CF_UNICODE.
1176 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1178 LPBYTE lpdata;
1179 unsigned long cbytes;
1180 LPSTR lpstr;
1181 unsigned long i, inlcount = 0;
1182 HANDLE hUnicodeText = 0;
1184 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1185 return 0;
1187 for (i = 0; i <= cbytes; i++)
1189 if (lpdata[i] == '\n')
1190 inlcount++;
1193 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1195 UINT count;
1197 for (i = 0, inlcount = 0; i <= cbytes; i++)
1199 if (lpdata[i] == '\n')
1200 lpstr[inlcount++] = '\r';
1202 lpstr[inlcount++] = lpdata[i];
1205 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1206 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1208 if (hUnicodeText)
1210 WCHAR *textW = GlobalLock(hUnicodeText);
1211 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1212 GlobalUnlock(hUnicodeText);
1215 HeapFree(GetProcessHeap(), 0, lpstr);
1218 /* Free the retrieved property data */
1219 HeapFree(GetProcessHeap(), 0, lpdata);
1221 return hUnicodeText;
1225 /**************************************************************************
1226 * X11DRV_CLIPBOARD_ImportCompoundText
1228 * Import COMPOUND_TEXT to CF_UNICODE
1230 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1232 int i, j, ret;
1233 char** srcstr;
1234 int count, lcount;
1235 int srclen, destlen;
1236 HANDLE hUnicodeText;
1237 XTextProperty txtprop;
1239 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1241 return 0;
1244 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1245 txtprop.format = 8;
1246 wine_tsx11_lock();
1247 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1248 wine_tsx11_unlock();
1249 HeapFree(GetProcessHeap(), 0, txtprop.value);
1250 if (ret != Success || !count) return 0;
1252 TRACE("Importing %d line(s)\n", count);
1254 /* Compute number of lines */
1255 srclen = strlen(srcstr[0]);
1256 for (i = 0, lcount = 0; i <= srclen; i++)
1258 if (srcstr[0][i] == '\n')
1259 lcount++;
1262 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1264 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1266 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1268 WCHAR *deststr = GlobalLock(hUnicodeText);
1269 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1271 if (lcount)
1273 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1275 deststr[j] = deststr[i];
1277 if (deststr[i] == '\n')
1278 deststr[--j] = '\r';
1282 GlobalUnlock(hUnicodeText);
1285 wine_tsx11_lock();
1286 XFreeStringList(srcstr);
1287 wine_tsx11_unlock();
1289 return hUnicodeText;
1293 /**************************************************************************
1294 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1296 * Import XA_PIXMAP, converting the image to CF_DIB.
1298 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1300 HWND hwnd;
1301 HDC hdc;
1302 LPBYTE lpdata;
1303 unsigned long cbytes;
1304 Pixmap *pPixmap;
1305 HANDLE hClipData = 0;
1307 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1309 pPixmap = (Pixmap *) lpdata;
1311 hwnd = GetOpenClipboardWindow();
1312 hdc = GetDC(hwnd);
1314 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1315 ReleaseDC(hwnd, hdc);
1317 /* Free the retrieved property data */
1318 HeapFree(GetProcessHeap(), 0, lpdata);
1321 return hClipData;
1325 /**************************************************************************
1326 * X11DRV_CLIPBOARD_ImportImageBmp
1328 * Import image/bmp, converting the image to CF_DIB.
1330 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1332 LPBYTE lpdata;
1333 unsigned long cbytes;
1334 HANDLE hClipData = 0;
1336 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1338 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1340 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1341 bfh->bfType == 0x4d42 /* "BM" */)
1343 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1344 HBITMAP hbmp;
1345 HDC hdc;
1347 hdc = GetDC(0);
1348 hbmp = CreateDIBitmap(
1349 hdc,
1350 &(bmi->bmiHeader),
1351 CBM_INIT,
1352 lpdata+bfh->bfOffBits,
1353 bmi,
1354 DIB_RGB_COLORS
1357 hClipData = X11DRV_DIB_CreateDIBFromBitmap(hdc, hbmp);
1359 DeleteObject(hbmp);
1360 ReleaseDC(0, hdc);
1363 /* Free the retrieved property data */
1364 HeapFree(GetProcessHeap(), 0, lpdata);
1367 return hClipData;
1371 /**************************************************************************
1372 * X11DRV_CLIPBOARD_ImportMetaFilePict
1374 * Import MetaFilePict.
1376 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1378 LPBYTE lpdata;
1379 unsigned long cbytes;
1380 HANDLE hClipData = 0;
1382 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1384 if (cbytes)
1385 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1387 /* Free the retrieved property data */
1388 HeapFree(GetProcessHeap(), 0, lpdata);
1391 return hClipData;
1395 /**************************************************************************
1396 * X11DRV_ImportEnhMetaFile
1398 * Import EnhMetaFile.
1400 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1402 LPBYTE lpdata;
1403 unsigned long cbytes;
1404 HANDLE hClipData = 0;
1406 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1408 if (cbytes)
1409 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1411 /* Free the retrieved property data */
1412 HeapFree(GetProcessHeap(), 0, lpdata);
1415 return hClipData;
1419 /**************************************************************************
1420 * X11DRV_ImportClipbordaData
1422 * Generic import clipboard data routine.
1424 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1426 LPVOID lpClipData;
1427 LPBYTE lpdata;
1428 unsigned long cbytes;
1429 HANDLE hClipData = 0;
1431 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1433 if (cbytes)
1435 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1436 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1437 if (hClipData == 0)
1438 return NULL;
1440 if ((lpClipData = GlobalLock(hClipData)))
1442 memcpy(lpClipData, lpdata, cbytes);
1443 GlobalUnlock(hClipData);
1445 else
1447 GlobalFree(hClipData);
1448 hClipData = 0;
1452 /* Free the retrieved property data */
1453 HeapFree(GetProcessHeap(), 0, lpdata);
1456 return hClipData;
1460 /**************************************************************************
1461 X11DRV_CLIPBOARD_ExportClipboardData
1463 * Generic export clipboard data routine.
1465 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1466 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1468 LPVOID lpClipData;
1469 UINT datasize = 0;
1470 HANDLE hClipData = 0;
1472 *lpBytes = 0; /* Assume failure */
1474 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1475 ERR("Failed to export %04x format\n", lpData->wFormatID);
1476 else
1478 datasize = GlobalSize(lpData->hData32);
1480 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1481 if (hClipData == 0) return NULL;
1483 if ((lpClipData = GlobalLock(hClipData)))
1485 LPVOID lpdata = GlobalLock(lpData->hData32);
1487 memcpy(lpClipData, lpdata, datasize);
1488 *lpBytes = datasize;
1490 GlobalUnlock(lpData->hData32);
1491 GlobalUnlock(hClipData);
1492 } else {
1493 GlobalFree(hClipData);
1494 hClipData = 0;
1498 return hClipData;
1502 /**************************************************************************
1503 * X11DRV_CLIPBOARD_ExportXAString
1505 * Export CF_TEXT converting the string to XA_STRING.
1506 * Helper function for X11DRV_CLIPBOARD_ExportString.
1508 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1510 UINT i, j;
1511 UINT size;
1512 LPSTR text, lpstr = NULL;
1514 *lpBytes = 0; /* Assume return has zero bytes */
1516 text = GlobalLock(lpData->hData32);
1517 size = strlen(text);
1519 /* remove carriage returns */
1520 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1521 if (lpstr == NULL)
1522 goto done;
1524 for (i = 0,j = 0; i < size && text[i]; i++)
1526 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1527 continue;
1528 lpstr[j++] = text[i];
1531 lpstr[j]='\0';
1532 *lpBytes = j; /* Number of bytes in string */
1534 done:
1535 HeapFree(GetProcessHeap(), 0, text);
1536 GlobalUnlock(lpData->hData32);
1538 return lpstr;
1542 /**************************************************************************
1543 * X11DRV_CLIPBOARD_ExportUTF8String
1545 * Export CF_UNICODE converting the string to UTF8.
1546 * Helper function for X11DRV_CLIPBOARD_ExportString.
1548 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1550 UINT i, j;
1551 UINT size;
1552 LPWSTR uni_text;
1553 LPSTR text, lpstr = NULL;
1555 *lpBytes = 0; /* Assume return has zero bytes */
1557 uni_text = GlobalLock(lpData->hData32);
1559 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1561 text = HeapAlloc(GetProcessHeap(), 0, size);
1562 if (!text)
1563 goto done;
1564 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1566 /* remove carriage returns */
1567 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1568 if (lpstr == NULL)
1569 goto done;
1571 for (i = 0,j = 0; i < size && text[i]; i++)
1573 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1574 continue;
1575 lpstr[j++] = text[i];
1577 lpstr[j]='\0';
1579 *lpBytes = j; /* Number of bytes in string */
1581 done:
1582 HeapFree(GetProcessHeap(), 0, text);
1583 GlobalUnlock(lpData->hData32);
1585 return lpstr;
1590 /**************************************************************************
1591 * X11DRV_CLIPBOARD_ExportCompoundText
1593 * Export CF_UNICODE to COMPOUND_TEXT
1594 * Helper function for X11DRV_CLIPBOARD_ExportString.
1596 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1597 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1599 char* lpstr = 0;
1600 XTextProperty prop;
1601 XICCEncodingStyle style;
1602 UINT i, j;
1603 UINT size;
1604 LPWSTR uni_text;
1606 uni_text = GlobalLock(lpData->hData32);
1608 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1609 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1610 if (!lpstr)
1611 return 0;
1613 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1615 /* remove carriage returns */
1616 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1618 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1619 continue;
1620 lpstr[j++] = lpstr[i];
1622 lpstr[j]='\0';
1624 GlobalUnlock(lpData->hData32);
1626 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1627 style = XCompoundTextStyle;
1628 else
1629 style = XStdICCTextStyle;
1631 /* Update the X property */
1632 wine_tsx11_lock();
1633 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1635 XSetTextProperty(display, requestor, &prop, rprop);
1636 XFree(prop.value);
1638 wine_tsx11_unlock();
1640 HeapFree(GetProcessHeap(), 0, lpstr);
1642 return 0;
1645 /**************************************************************************
1646 * X11DRV_CLIPBOARD_ExportString
1648 * Export string
1650 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1651 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1653 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1655 if (aTarget == XA_STRING)
1656 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1657 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1658 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1659 rprop, lpData, lpBytes);
1660 else
1662 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1663 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1666 else
1667 ERR("Failed to render %04x format\n", lpData->wFormatID);
1669 return 0;
1673 /**************************************************************************
1674 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1676 * Export CF_DIB to XA_PIXMAP.
1678 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1679 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1681 HDC hdc;
1682 HANDLE hData;
1683 unsigned char* lpData;
1685 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1687 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1688 return 0;
1691 if (!lpdata->drvData) /* If not already rendered */
1693 /* For convert from packed DIB to Pixmap */
1694 hdc = GetDC(0);
1695 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1696 ReleaseDC(0, hdc);
1699 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1701 /* Wrap pixmap so we can return a handle */
1702 hData = GlobalAlloc(0, *lpBytes);
1703 lpData = GlobalLock(hData);
1704 memcpy(lpData, &lpdata->drvData, *lpBytes);
1705 GlobalUnlock(hData);
1707 return hData;
1711 /**************************************************************************
1712 * X11DRV_CLIPBOARD_ExportMetaFilePict
1714 * Export MetaFilePict.
1716 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1717 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1719 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1721 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1722 return 0;
1725 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1729 /**************************************************************************
1730 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1732 * Export EnhMetaFile.
1734 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1735 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1737 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1739 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1740 return 0;
1743 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1747 /**************************************************************************
1748 * X11DRV_CLIPBOARD_QueryTargets
1750 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1751 Atom target, XEvent *xe)
1753 INT i;
1754 Bool res;
1756 wine_tsx11_lock();
1757 XConvertSelection(display, selection, target,
1758 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1759 wine_tsx11_unlock();
1762 * Wait until SelectionNotify is received
1764 for (i = 0; i < SELECTION_RETRIES; i++)
1766 wine_tsx11_lock();
1767 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1768 wine_tsx11_unlock();
1769 if (res && xe->xselection.selection == selection) break;
1771 usleep(SELECTION_WAIT);
1774 /* Verify that the selection returned a valid TARGETS property */
1775 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1777 /* Selection owner failed to respond or we missed the SelectionNotify */
1778 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1779 return FALSE;
1782 return TRUE;
1786 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1788 return (event->error_code == BadAtom);
1791 /**************************************************************************
1792 * X11DRV_CLIPBOARD_InsertSelectionProperties
1794 * Mark properties available for future retrieval.
1796 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1798 UINT i, nb_atoms = 0;
1799 Atom *atoms = NULL;
1801 /* Cache these formats in the clipboard cache */
1802 for (i = 0; i < count; i++)
1804 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1806 if (lpFormat)
1808 /* We found at least one Window's format that mapps to the property.
1809 * Continue looking for more.
1811 * If more than one property map to a Window's format then we use the first
1812 * one and ignore the rest.
1814 while (lpFormat)
1816 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
1817 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1818 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1819 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1822 else if (properties[i])
1824 /* add it to the list of atoms that we don't know about yet */
1825 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1826 (count - i) * sizeof(*atoms) );
1827 if (atoms) atoms[nb_atoms++] = properties[i];
1831 /* query all unknown atoms in one go */
1832 if (atoms)
1834 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1835 if (names)
1837 X11DRV_expect_error( display, is_atom_error, NULL );
1838 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1839 if (X11DRV_check_error())
1841 WARN( "got some bad atoms, ignoring\n" );
1842 nb_atoms = 0;
1844 for (i = 0; i < nb_atoms; i++)
1846 WINE_CLIPFORMAT *lpFormat;
1847 LPWSTR wname;
1848 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1849 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1850 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1852 lpFormat = register_format( wname, atoms[i] );
1853 HeapFree(GetProcessHeap(), 0, wname);
1854 if (!lpFormat)
1856 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1857 continue;
1859 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
1860 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1861 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1863 wine_tsx11_lock();
1864 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1865 wine_tsx11_unlock();
1866 HeapFree( GetProcessHeap(), 0, names );
1868 HeapFree( GetProcessHeap(), 0, atoms );
1873 /**************************************************************************
1874 * X11DRV_CLIPBOARD_QueryAvailableData
1876 * Caches the list of data formats available from the current selection.
1877 * This queries the selection owner for the TARGETS property and saves all
1878 * reported property types.
1880 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1882 XEvent xe;
1883 Atom atype=AnyPropertyType;
1884 int aformat;
1885 unsigned long remain;
1886 Atom* targetList=NULL;
1887 Window w;
1888 unsigned long cSelectionTargets = 0;
1890 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1892 ERR("Received request to cache selection but process is owner=(%08x)\n",
1893 (unsigned) selectionWindow);
1894 return -1; /* Prevent self request */
1897 w = thread_selection_wnd();
1898 if (!w)
1900 ERR("No window available to retrieve selection!\n");
1901 return -1;
1905 * Query the selection owner for the TARGETS property
1907 wine_tsx11_lock();
1908 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1909 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1911 wine_tsx11_unlock();
1912 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1913 selectionCacheSrc = XA_PRIMARY;
1914 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1915 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1916 else
1918 Atom xstr = XA_STRING;
1920 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1921 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1923 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1924 selectionCacheSrc = XA_PRIMARY;
1925 return 1;
1927 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1929 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1930 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1931 return 1;
1933 else
1935 WARN("Failed to query selection owner for available data.\n");
1936 return -1;
1940 else /* No selection owner so report 0 targets available */
1942 wine_tsx11_unlock();
1943 return 0;
1946 /* Read the TARGETS property contents */
1947 wine_tsx11_lock();
1948 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1949 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1950 &remain, (unsigned char**)&targetList) != Success)
1952 wine_tsx11_unlock();
1953 WARN("Failed to read TARGETS property\n");
1955 else
1957 wine_tsx11_unlock();
1958 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1959 atype, aformat, cSelectionTargets, remain);
1961 * The TARGETS property should have returned us a list of atoms
1962 * corresponding to each selection target format supported.
1964 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1966 if (aformat == 32)
1968 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1970 else if (aformat == 8) /* work around quartz-wm brain damage */
1972 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
1973 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
1974 for (i = 0; i < count; i++)
1975 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
1976 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
1977 HeapFree( GetProcessHeap(), 0, atoms );
1981 /* Free the list of targets */
1982 wine_tsx11_lock();
1983 XFree(targetList);
1984 wine_tsx11_unlock();
1987 return cSelectionTargets;
1991 /**************************************************************************
1992 * X11DRV_CLIPBOARD_ReadSelectionData
1994 * This method is invoked only when we DO NOT own the X selection
1996 * We always get the data from the selection client each time,
1997 * since we have no way of determining if the data in our cache is stale.
1999 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2001 Bool res;
2002 DWORD i;
2003 XEvent xe;
2004 BOOL bRet = FALSE;
2006 TRACE("%04x\n", lpData->wFormatID);
2008 if (!lpData->lpFormat)
2010 ERR("Requesting format %04x but no source format linked to data.\n",
2011 lpData->wFormatID);
2012 return FALSE;
2015 if (!selectionAcquired)
2017 Window w = thread_selection_wnd();
2018 if(!w)
2020 ERR("No window available to read selection data!\n");
2021 return FALSE;
2024 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2025 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
2027 wine_tsx11_lock();
2028 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2029 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2030 wine_tsx11_unlock();
2032 /* wait until SelectionNotify is received */
2033 for (i = 0; i < SELECTION_RETRIES; i++)
2035 wine_tsx11_lock();
2036 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2037 wine_tsx11_unlock();
2038 if (res && xe.xselection.selection == selectionCacheSrc) break;
2040 usleep(SELECTION_WAIT);
2043 /* Verify that the selection returned a valid TARGETS property */
2044 if (xe.xselection.property != None)
2047 * Read the contents of the X selection property
2048 * into WINE's clipboard cache and converting the
2049 * data format if necessary.
2051 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2052 xe.xselection.property);
2054 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
2056 else
2058 TRACE("Failed to convert selection\n");
2061 else
2063 ERR("Received request to cache selection data but process is owner\n");
2066 TRACE("Returning %d\n", bRet);
2068 return bRet;
2072 /**************************************************************************
2073 * X11DRV_CLIPBOARD_GetProperty
2074 * Gets type, data and size.
2076 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2077 Atom *atype, unsigned char** data, unsigned long* datasize)
2079 int aformat;
2080 unsigned long pos = 0, nitems, remain, count;
2081 unsigned char *val = NULL, *buffer;
2083 TRACE("Reading property %lu from X window %lx\n", prop, w);
2085 for (;;)
2087 wine_tsx11_lock();
2088 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2089 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2091 wine_tsx11_unlock();
2092 WARN("Failed to read property\n");
2093 HeapFree( GetProcessHeap(), 0, val );
2094 return FALSE;
2097 count = get_property_size( aformat, nitems );
2098 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2099 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2101 if (!*data)
2103 XFree( buffer );
2104 wine_tsx11_unlock();
2105 HeapFree( GetProcessHeap(), 0, val );
2106 return FALSE;
2108 val = *data;
2109 memcpy( (int *)val + pos, buffer, count );
2110 XFree( buffer );
2111 wine_tsx11_unlock();
2112 if (!remain)
2114 *datasize = pos * sizeof(int) + count;
2115 val[*datasize] = 0;
2116 break;
2118 pos += count / sizeof(int);
2121 /* Delete the property on the window now that we are done
2122 * This will send a PropertyNotify event to the selection owner. */
2123 wine_tsx11_lock();
2124 XDeleteProperty(display, w, prop);
2125 wine_tsx11_unlock();
2126 return TRUE;
2130 /**************************************************************************
2131 * X11DRV_CLIPBOARD_ReadProperty
2132 * Reads the contents of the X selection property.
2134 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2135 unsigned char** data, unsigned long* datasize)
2137 Atom atype;
2138 XEvent xe;
2140 if (prop == None)
2141 return FALSE;
2143 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2144 return FALSE;
2146 wine_tsx11_lock();
2147 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2149 wine_tsx11_unlock();
2151 if (atype == x11drv_atom(INCR))
2153 unsigned char *buf = *data;
2154 unsigned long bufsize = 0;
2156 for (;;)
2158 int i;
2159 unsigned char *prop_data, *tmp;
2160 unsigned long prop_size;
2162 /* Wait until PropertyNotify is received */
2163 for (i = 0; i < SELECTION_RETRIES; i++)
2165 Bool res;
2167 wine_tsx11_lock();
2168 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2169 wine_tsx11_unlock();
2170 if (res && xe.xproperty.atom == prop &&
2171 xe.xproperty.state == PropertyNewValue)
2172 break;
2173 usleep(SELECTION_WAIT);
2176 if (i >= SELECTION_RETRIES ||
2177 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2179 HeapFree(GetProcessHeap(), 0, buf);
2180 return FALSE;
2183 /* Retrieved entire data. */
2184 if (prop_size == 0)
2186 HeapFree(GetProcessHeap(), 0, prop_data);
2187 *data = buf;
2188 *datasize = bufsize;
2189 return TRUE;
2192 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2193 if (!tmp)
2195 HeapFree(GetProcessHeap(), 0, buf);
2196 return FALSE;
2199 buf = tmp;
2200 memcpy(buf + bufsize, prop_data, prop_size + 1);
2201 bufsize += prop_size;
2202 HeapFree(GetProcessHeap(), 0, prop_data);
2206 return TRUE;
2210 /**************************************************************************
2211 * CLIPBOARD_SerializeMetafile
2213 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2215 HANDLE h = 0;
2217 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2219 if (out) /* Serialize out, caller should free memory */
2221 *lpcbytes = 0; /* Assume failure */
2223 if (wformat == CF_METAFILEPICT)
2225 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2226 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2228 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2229 if (h)
2231 char *pdata = GlobalLock(h);
2233 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2234 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2236 *lpcbytes = size + sizeof(METAFILEPICT);
2238 GlobalUnlock(h);
2241 GlobalUnlock(hdata);
2243 else if (wformat == CF_ENHMETAFILE)
2245 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2247 h = GlobalAlloc(0, size);
2248 if (h)
2250 LPVOID pdata = GlobalLock(h);
2252 GetEnhMetaFileBits(hdata, size, pdata);
2253 *lpcbytes = size;
2255 GlobalUnlock(h);
2259 else
2261 if (wformat == CF_METAFILEPICT)
2263 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2264 if (h)
2266 unsigned int wiresize, size;
2267 LPMETAFILEPICT lpmfp = GlobalLock(h);
2269 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2270 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2271 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2272 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2273 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2274 GlobalUnlock(h);
2277 else if (wformat == CF_ENHMETAFILE)
2279 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2283 return h;
2287 /**************************************************************************
2288 * X11DRV_CLIPBOARD_ReleaseSelection
2290 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2292 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2294 /* w is the window that lost the selection
2296 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2297 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2299 if (selectionAcquired && (w == selectionWindow))
2301 CLIPBOARDINFO cbinfo;
2303 /* completely give up the selection */
2304 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2306 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2308 if (cbinfo.flags & CB_PROCESS)
2310 /* Since we're still the owner, this wasn't initiated by
2311 another Wine process */
2312 if (OpenClipboard(hwnd))
2314 /* Destroy private objects */
2315 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2317 /* Give up ownership of the windows clipboard */
2318 X11DRV_CLIPBOARD_ReleaseOwnership();
2319 CloseClipboard();
2323 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2325 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2327 wine_tsx11_lock();
2328 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2330 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2331 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2333 else
2334 TRACE("We no longer own PRIMARY\n");
2335 wine_tsx11_unlock();
2337 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2339 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2341 wine_tsx11_lock();
2342 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2344 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2345 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2347 else
2348 TRACE("We no longer own CLIPBOARD\n");
2349 wine_tsx11_unlock();
2352 selectionWindow = None;
2354 X11DRV_EmptyClipboard(FALSE);
2356 /* Reset the selection flags now that we are done */
2357 selectionAcquired = S_NOSELECTION;
2362 /**************************************************************************
2363 * IsSelectionOwner (X11DRV.@)
2365 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2367 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2369 return selectionAcquired;
2373 /**************************************************************************
2374 * X11DRV Clipboard Exports
2375 **************************************************************************/
2378 /**************************************************************************
2379 * RegisterClipboardFormat (X11DRV.@)
2381 * Registers a custom X clipboard format
2382 * Returns: Format id or 0 on failure
2384 UINT CDECL X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2386 LPWINE_CLIPFORMAT lpFormat;
2388 if (FormatName == NULL) return 0;
2389 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2390 return lpFormat->wFormatID;
2394 /**************************************************************************
2395 * X11DRV_GetClipboardFormatName
2397 INT CDECL X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2399 LPWINE_CLIPFORMAT lpFormat;
2401 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2403 if (wFormat < 0xc000)
2405 SetLastError(ERROR_INVALID_PARAMETER);
2406 return 0;
2409 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2411 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2413 TRACE("Unknown format 0x%08x!\n", wFormat);
2414 SetLastError(ERROR_INVALID_HANDLE);
2415 return 0;
2418 lstrcpynW(retStr, lpFormat->Name, maxlen);
2420 return strlenW(retStr);
2424 /**************************************************************************
2425 * AcquireClipboard (X11DRV.@)
2427 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2429 DWORD procid;
2430 Window owner;
2431 Display *display;
2433 TRACE(" %p\n", hWndClipWindow);
2436 * It's important that the selection get acquired from the thread
2437 * that owns the clipboard window. The primary reason is that we know
2438 * it is running a message loop and therefore can process the
2439 * X selection events.
2441 if (hWndClipWindow &&
2442 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2444 if (procid != GetCurrentProcessId())
2446 WARN("Setting clipboard owner to other process is not supported\n");
2447 hWndClipWindow = NULL;
2449 else
2451 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2452 GetCurrentThreadId(),
2453 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2455 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2459 owner = thread_selection_wnd();
2460 display = thread_display();
2462 wine_tsx11_lock();
2464 selectionAcquired = 0;
2465 selectionWindow = 0;
2467 /* Grab PRIMARY selection if not owned */
2468 if (use_primary_selection)
2469 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2471 /* Grab CLIPBOARD selection if not owned */
2472 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2474 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2475 selectionAcquired |= S_PRIMARY;
2477 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2478 selectionAcquired |= S_CLIPBOARD;
2480 wine_tsx11_unlock();
2482 if (selectionAcquired)
2484 selectionWindow = owner;
2485 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2488 return 1;
2492 /**************************************************************************
2493 * X11DRV_EmptyClipboard
2495 * Empty cached clipboard data.
2497 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2499 if (ClipData)
2501 LPWINE_CLIPDATA lpData, lpStart;
2502 LPWINE_CLIPDATA lpNext = ClipData;
2504 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2508 lpStart = ClipData;
2509 lpData = lpNext;
2510 lpNext = lpData->NextData;
2512 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2514 lpData->PrevData->NextData = lpData->NextData;
2515 lpData->NextData->PrevData = lpData->PrevData;
2517 if (lpData == ClipData)
2518 ClipData = lpNext != lpData ? lpNext : NULL;
2520 X11DRV_CLIPBOARD_FreeData(lpData);
2521 HeapFree(GetProcessHeap(), 0, lpData);
2523 ClipDataCount--;
2525 } while (lpNext != lpStart);
2528 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2533 /**************************************************************************
2534 * X11DRV_SetClipboardData
2536 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2538 DWORD flags = 0;
2539 BOOL bResult = TRUE;
2541 /* If it's not owned, data can only be set if the format data is not already owned
2542 and its rendering is not delayed */
2543 if (!owner)
2545 CLIPBOARDINFO cbinfo;
2546 LPWINE_CLIPDATA lpRender;
2548 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2550 if ((!hData16 && !hData32) ||
2551 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2552 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2553 bResult = FALSE;
2554 else
2555 flags = CF_FLAG_UNOWNED;
2558 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags, NULL, TRUE);
2560 return bResult;
2564 /**************************************************************************
2565 * CountClipboardFormats
2567 INT CDECL X11DRV_CountClipboardFormats(void)
2569 CLIPBOARDINFO cbinfo;
2571 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2573 TRACE(" count=%d\n", ClipDataCount);
2575 return ClipDataCount;
2579 /**************************************************************************
2580 * X11DRV_EnumClipboardFormats
2582 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2584 CLIPBOARDINFO cbinfo;
2585 UINT wNextFormat = 0;
2587 TRACE("(%04X)\n", wFormat);
2589 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2591 if (!wFormat)
2593 if (ClipData)
2594 wNextFormat = ClipData->wFormatID;
2596 else
2598 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2600 if (lpData && lpData->NextData != ClipData)
2601 wNextFormat = lpData->NextData->wFormatID;
2604 return wNextFormat;
2608 /**************************************************************************
2609 * X11DRV_IsClipboardFormatAvailable
2611 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2613 BOOL bRet = FALSE;
2614 CLIPBOARDINFO cbinfo;
2616 TRACE("(%04X)\n", wFormat);
2618 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2620 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2621 bRet = TRUE;
2623 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2625 return bRet;
2629 /**************************************************************************
2630 * GetClipboardData (USER.142)
2632 BOOL CDECL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2634 CLIPBOARDINFO cbinfo;
2635 LPWINE_CLIPDATA lpRender;
2637 TRACE("(%04X)\n", wFormat);
2639 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2641 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2643 if ( !lpRender->hData32 )
2644 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2646 /* Convert between 32 -> 16 bit data, if necessary */
2647 if (lpRender->hData32 && !lpRender->hData16)
2649 int size;
2651 if (lpRender->wFormatID == CF_METAFILEPICT)
2652 size = sizeof(METAFILEPICT16);
2653 else
2654 size = GlobalSize(lpRender->hData32);
2656 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2658 if (!lpRender->hData16)
2659 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2660 else
2662 if (lpRender->wFormatID == CF_METAFILEPICT)
2664 FIXME("\timplement function CopyMetaFilePict32to16\n");
2665 FIXME("\tin the appropriate file.\n");
2666 #ifdef SOMEONE_IMPLEMENTED_ME
2667 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2668 GlobalLock(lpRender->hData32));
2669 #endif
2671 else
2673 memcpy(GlobalLock16(lpRender->hData16),
2674 GlobalLock(lpRender->hData32), size);
2677 GlobalUnlock16(lpRender->hData16);
2678 GlobalUnlock(lpRender->hData32);
2682 /* Convert between 32 -> 16 bit data, if necessary */
2683 if (lpRender->hData16 && !lpRender->hData32)
2685 int size;
2687 if (lpRender->wFormatID == CF_METAFILEPICT)
2688 size = sizeof(METAFILEPICT16);
2689 else
2690 size = GlobalSize(lpRender->hData32);
2692 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2693 GMEM_DDESHARE, size);
2695 if (lpRender->wFormatID == CF_METAFILEPICT)
2697 FIXME("\timplement function CopyMetaFilePict16to32\n");
2698 FIXME("\tin the appropriate file.\n");
2699 #ifdef SOMEONE_IMPLEMENTED_ME
2700 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2701 GlobalLock(lpRender->hData16));
2702 #endif
2704 else
2706 memcpy(GlobalLock(lpRender->hData32),
2707 GlobalLock16(lpRender->hData16), size);
2710 GlobalUnlock(lpRender->hData32);
2711 GlobalUnlock16(lpRender->hData16);
2714 if (phData16)
2715 *phData16 = lpRender->hData16;
2717 if (phData32)
2718 *phData32 = lpRender->hData32;
2720 TRACE(" returning hData16(%04x) hData32(%p) (type %04x)\n",
2721 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2723 return lpRender->hData16 || lpRender->hData32;
2726 return 0;
2730 /**************************************************************************
2731 * ResetSelectionOwner
2733 * Called when the thread owning the selection is destroyed and we need to
2734 * preserve the selection ownership. We look for another top level window
2735 * in this process and send it a message to acquire the selection.
2737 void X11DRV_ResetSelectionOwner(void)
2739 HWND hwnd;
2740 DWORD procid;
2742 TRACE("\n");
2744 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2745 return;
2747 selectionAcquired = S_NOSELECTION;
2748 selectionWindow = 0;
2750 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2753 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2755 if (GetCurrentProcessId() == procid)
2757 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2758 return;
2761 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2763 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2765 X11DRV_CLIPBOARD_ReleaseOwnership();
2766 X11DRV_EmptyClipboard(FALSE);
2770 /**************************************************************************
2771 * X11DRV_CLIPBOARD_SynthesizeData
2773 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2775 BOOL bsyn = TRUE;
2776 LPWINE_CLIPDATA lpSource = NULL;
2778 TRACE(" %04x\n", wFormatID);
2780 /* Don't need to synthesize if it already exists */
2781 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2782 return TRUE;
2784 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2786 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2787 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2788 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2789 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2790 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2791 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2793 else if (wFormatID == CF_ENHMETAFILE)
2795 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2796 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2798 else if (wFormatID == CF_METAFILEPICT)
2800 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2801 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2803 else if (wFormatID == CF_DIB)
2805 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2806 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2808 else if (wFormatID == CF_BITMAP)
2810 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2811 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2814 if (bsyn)
2815 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2817 return bsyn;
2822 /**************************************************************************
2823 * X11DRV_EndClipboardUpdate
2824 * TODO:
2825 * Add locale if it hasn't already been added
2827 void CDECL X11DRV_EndClipboardUpdate(void)
2829 INT count = ClipDataCount;
2831 /* Do Unicode <-> Text <-> OEM mapping */
2832 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2833 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2834 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2836 /* Enhmetafile <-> MetafilePict mapping */
2837 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2838 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2840 /* DIB <-> Bitmap mapping */
2841 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2842 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2844 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2848 /***********************************************************************
2849 * X11DRV_SelectionRequest_TARGETS
2850 * Service a TARGETS selection request event
2852 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2853 Atom target, Atom rprop )
2855 UINT i;
2856 Atom* targets;
2857 ULONG cTargets;
2858 LPWINE_CLIPFORMAT lpFormats;
2859 LPWINE_CLIPDATA lpData;
2861 /* Create X atoms for any clipboard types which don't have atoms yet.
2862 * This avoids sending bogus zero atoms.
2863 * Without this, copying might not have access to all clipboard types.
2864 * FIXME: is it safe to call this here?
2866 intern_atoms();
2869 * Count the number of items we wish to expose as selection targets.
2871 cTargets = 1; /* Include TARGETS */
2873 if (!(lpData = ClipData)) return None;
2877 lpFormats = ClipFormats;
2879 while (lpFormats)
2881 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2882 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2883 cTargets++;
2885 lpFormats = lpFormats->NextFormat;
2888 lpData = lpData->NextData;
2890 while (lpData != ClipData);
2892 TRACE(" found %d formats\n", cTargets);
2894 /* Allocate temp buffer */
2895 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2896 if(targets == NULL)
2897 return None;
2899 i = 0;
2900 lpData = ClipData;
2901 targets[i++] = x11drv_atom(TARGETS);
2905 lpFormats = ClipFormats;
2907 while (lpFormats)
2909 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2910 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2911 targets[i++] = lpFormats->drvData;
2913 lpFormats = lpFormats->NextFormat;
2916 lpData = lpData->NextData;
2918 while (lpData != ClipData);
2920 wine_tsx11_lock();
2922 if (TRACE_ON(clipboard))
2924 unsigned int i;
2925 for ( i = 0; i < cTargets; i++)
2927 char *itemFmtName = XGetAtomName(display, targets[i]);
2928 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2929 XFree(itemFmtName);
2933 /* We may want to consider setting the type to xaTargets instead,
2934 * in case some apps expect this instead of XA_ATOM */
2935 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2936 PropModeReplace, (unsigned char *)targets, cTargets);
2937 wine_tsx11_unlock();
2939 HeapFree(GetProcessHeap(), 0, targets);
2941 return rprop;
2945 /***********************************************************************
2946 * X11DRV_SelectionRequest_MULTIPLE
2947 * Service a MULTIPLE selection request event
2948 * rprop contains a list of (target,property) atom pairs.
2949 * The first atom names a target and the second names a property.
2950 * The effect is as if we have received a sequence of SelectionRequest events
2951 * (one for each atom pair) except that:
2952 * 1. We reply with a SelectionNotify only when all the requested conversions
2953 * have been performed.
2954 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2955 * we replace the atom in the property by None.
2957 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2959 Display *display = pevent->display;
2960 Atom rprop;
2961 Atom atype=AnyPropertyType;
2962 int aformat;
2963 unsigned long remain;
2964 Atom* targetPropList=NULL;
2965 unsigned long cTargetPropList = 0;
2967 /* If the specified property is None the requestor is an obsolete client.
2968 * We support these by using the specified target atom as the reply property.
2970 rprop = pevent->property;
2971 if( rprop == None )
2972 rprop = pevent->target;
2973 if (!rprop)
2974 return 0;
2976 /* Read the MULTIPLE property contents. This should contain a list of
2977 * (target,property) atom pairs.
2979 wine_tsx11_lock();
2980 if(XGetWindowProperty(display, pevent->requestor, rprop,
2981 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2982 &cTargetPropList, &remain,
2983 (unsigned char**)&targetPropList) != Success)
2985 wine_tsx11_unlock();
2986 TRACE("\tCouldn't read MULTIPLE property\n");
2988 else
2990 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2991 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2992 wine_tsx11_unlock();
2995 * Make sure we got what we expect.
2996 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2997 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2998 * However some X apps(such as XPaint) are not compliant with this and return
2999 * a user defined atom in atype when XGetWindowProperty is called.
3000 * The data *is* an atom pair but is not denoted as such.
3002 if(aformat == 32 /* atype == xAtomPair */ )
3004 unsigned int i;
3006 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3007 * for each (target,property) pair */
3009 for (i = 0; i < cTargetPropList; i+=2)
3011 XSelectionRequestEvent event;
3013 if (TRACE_ON(clipboard))
3015 char *targetName, *propName;
3016 wine_tsx11_lock();
3017 targetName = XGetAtomName(display, targetPropList[i]);
3018 propName = XGetAtomName(display, targetPropList[i+1]);
3019 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3020 i/2, targetName, propName);
3021 XFree(targetName);
3022 XFree(propName);
3023 wine_tsx11_unlock();
3026 /* We must have a non "None" property to service a MULTIPLE target atom */
3027 if ( !targetPropList[i+1] )
3029 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3030 continue;
3033 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3034 event = *pevent;
3035 event.target = targetPropList[i];
3036 event.property = targetPropList[i+1];
3038 /* Fire a SelectionRequest, informing the handler that we are processing
3039 * a MULTIPLE selection request event.
3041 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3045 /* Free the list of targets/properties */
3046 wine_tsx11_lock();
3047 XFree(targetPropList);
3048 wine_tsx11_unlock();
3051 return rprop;
3055 /***********************************************************************
3056 * X11DRV_HandleSelectionRequest
3057 * Process an event selection request event.
3058 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3059 * recursively while servicing a "MULTIPLE" selection target.
3061 * Note: We only receive this event when WINE owns the X selection
3063 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3065 Display *display = event->display;
3066 XSelectionEvent result;
3067 Atom rprop = None;
3068 Window request = event->requestor;
3070 TRACE("\n");
3073 * We can only handle the selection request if :
3074 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3075 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3076 * since this has been already done.
3078 if ( !bIsMultiple )
3080 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3081 goto END;
3084 /* If the specified property is None the requestor is an obsolete client.
3085 * We support these by using the specified target atom as the reply property.
3087 rprop = event->property;
3088 if( rprop == None )
3089 rprop = event->target;
3091 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3093 /* TARGETS selection request */
3094 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3096 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3098 /* MULTIPLE selection request */
3099 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3101 else
3103 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3105 if (lpFormat && lpFormat->lpDrvExportFunc)
3107 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3109 if (lpData)
3111 unsigned char* lpClipData;
3112 DWORD cBytes;
3113 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3114 rprop, lpData, &cBytes);
3116 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3118 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
3120 wine_tsx11_lock();
3121 XChangeProperty(display, request, rprop, event->target,
3122 8, PropModeReplace, lpClipData, cBytes);
3123 wine_tsx11_unlock();
3125 GlobalUnlock(hClipData);
3126 GlobalFree(hClipData);
3132 END:
3133 /* reply to sender
3134 * SelectionNotify should be sent only at the end of a MULTIPLE request
3136 if ( !bIsMultiple )
3138 result.type = SelectionNotify;
3139 result.display = display;
3140 result.requestor = request;
3141 result.selection = event->selection;
3142 result.property = rprop;
3143 result.target = event->target;
3144 result.time = event->time;
3145 TRACE("Sending SelectionNotify event...\n");
3146 wine_tsx11_lock();
3147 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3148 wine_tsx11_unlock();
3153 /***********************************************************************
3154 * X11DRV_SelectionRequest
3156 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3158 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3162 /***********************************************************************
3163 * X11DRV_SelectionClear
3165 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3167 XSelectionClearEvent *event = &xev->xselectionclear;
3168 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3169 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3170 event->window, hWnd, event->time );