push 9eb9af089d68d39110a91889d3a673043db63c4b
[wine/hacks.git] / dlls / winex11.drv / clipboard.c
blobec7d5ab1417c00b31fd5e8737aef2d86573ad8de
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 X11DRV_EmptyClipboard(BOOL keepunowned);
149 void 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_ImportXAString(Display *d, Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
157 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
158 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
159 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
160 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
161 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
162 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
163 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
164 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
165 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
166 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
167 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
168 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
169 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
170 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
171 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
172 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
173 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
174 unsigned char** data, unsigned long* datasize);
175 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
176 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
177 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
178 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
180 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
181 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
183 /* Clipboard formats
184 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
185 * declared in clipboard.h
187 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
188 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
189 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
190 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
191 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
192 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
193 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
194 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
195 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
196 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
197 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
198 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
199 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
200 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
201 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
202 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
203 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
204 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
205 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
206 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
207 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
208 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
209 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
211 static WINE_CLIPFORMAT ClipFormats[] =
213 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
214 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
216 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
217 NULL, &ClipFormats[0], &ClipFormats[2]},
219 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
220 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
222 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
223 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
225 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
226 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
228 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
229 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
231 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
232 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
234 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
235 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
237 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
238 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
240 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
241 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
243 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
244 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
246 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
247 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
249 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
250 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
252 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
253 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
254 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
256 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
257 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
259 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
260 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
262 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
263 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
265 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
266 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
268 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
269 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
271 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
272 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
274 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
275 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
277 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
278 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
280 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
281 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], NULL}
284 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
286 /* Maps X properties to Windows formats */
287 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
288 static const WCHAR wszGIF[] = {'G','I','F',0};
289 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
290 static const struct
292 LPCWSTR lpszFormat;
293 UINT prop;
294 } PropertyFormatMap[] =
296 { wszRichTextFormat, XATOM_text_rtf },
297 { wszRichTextFormat, XATOM_text_richtext },
298 { wszGIF, XATOM_image_gif },
299 { wszHTMLFormat, XATOM_text_html },
304 * Cached clipboard data.
306 static LPWINE_CLIPDATA ClipData = NULL;
307 static UINT ClipDataCount = 0;
310 * Clipboard sequence number
312 static UINT wSeqNo = 0;
314 /**************************************************************************
315 * Internal Clipboard implementation methods
316 **************************************************************************/
318 static Window thread_selection_wnd(void)
320 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
321 Window w = thread_data->selection_wnd;
323 if (!w)
325 XSetWindowAttributes attr;
327 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
328 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
330 wine_tsx11_lock();
331 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
332 InputOutput, CopyFromParent, CWEventMask, &attr);
333 wine_tsx11_unlock();
335 if (w)
336 thread_data->selection_wnd = w;
337 else
338 FIXME("Failed to create window. Fetching selection data will fail.\n");
341 return w;
344 /**************************************************************************
345 * X11DRV_InitClipboard
347 void X11DRV_InitClipboard(void)
349 UINT i;
351 /* Register known mapping between window formats and X properties */
352 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
353 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
357 /**************************************************************************
358 * intern_atoms
360 * Intern atoms for formats that don't have one yet.
362 static void intern_atoms(void)
364 LPWINE_CLIPFORMAT format;
365 int i, count, len;
366 char **names;
367 Atom *atoms;
368 Display *display;
370 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
371 if (!format->drvData) count++;
372 if (!count) return;
374 display = thread_init_display();
376 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
377 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
379 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
380 if (!format->drvData) {
381 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
382 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
383 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
387 wine_tsx11_lock();
388 XInternAtoms( display, names, count, False, atoms );
389 wine_tsx11_unlock();
391 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
392 if (!format->drvData) {
393 HeapFree(GetProcessHeap(), 0, names[i]);
394 format->drvData = atoms[i++];
398 HeapFree( GetProcessHeap(), 0, names );
399 HeapFree( GetProcessHeap(), 0, atoms );
403 /**************************************************************************
404 * register_format
406 * Register a custom X clipboard format.
408 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
410 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
412 TRACE("%s\n", debugstr_w(FormatName));
414 /* walk format chain to see if it's already registered */
415 while (lpFormat)
417 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
418 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
419 return lpFormat;
420 lpFormat = lpFormat->NextFormat;
423 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
427 /**************************************************************************
428 * X11DRV_CLIPBOARD_LookupFormat
430 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
432 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
434 while(lpFormat)
436 if (lpFormat->wFormatID == wID)
437 break;
439 lpFormat = lpFormat->NextFormat;
441 if (lpFormat && !lpFormat->drvData) intern_atoms();
442 return lpFormat;
446 /**************************************************************************
447 * X11DRV_CLIPBOARD_LookupProperty
449 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
451 for (;;)
453 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
454 BOOL need_intern = FALSE;
456 if (current)
457 lpFormat = current->NextFormat;
459 while(lpFormat)
461 if (lpFormat->drvData == drvData) return lpFormat;
462 if (!lpFormat->drvData) need_intern = TRUE;
463 lpFormat = lpFormat->NextFormat;
465 if (!need_intern) return NULL;
466 intern_atoms();
467 /* restart the search for the new atoms */
472 /**************************************************************************
473 * X11DRV_CLIPBOARD_LookupData
475 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
477 LPWINE_CLIPDATA lpData = ClipData;
479 if (lpData)
483 if (lpData->wFormatID == wID)
484 break;
486 lpData = lpData->NextData;
488 while(lpData != ClipData);
490 if (lpData->wFormatID != wID)
491 lpData = NULL;
494 return lpData;
498 /**************************************************************************
499 * InsertClipboardFormat
501 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
503 LPWINE_CLIPFORMAT lpFormat;
504 LPWINE_CLIPFORMAT lpNewFormat;
505 LPWSTR new_name;
507 /* allocate storage for new format entry */
508 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
510 if(lpNewFormat == NULL)
512 WARN("No more memory for a new format!\n");
513 return NULL;
516 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
518 WARN("No more memory for the new format name!\n");
519 HeapFree(GetProcessHeap(), 0, lpNewFormat);
520 return NULL;
523 lpNewFormat->Name = strcpyW(new_name, FormatName);
524 lpNewFormat->wFlags = 0;
525 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
526 lpNewFormat->drvData = prop;
527 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
528 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
530 /* Link Format */
531 lpFormat = ClipFormats;
533 while(lpFormat->NextFormat) /* Move to last entry */
534 lpFormat = lpFormat->NextFormat;
536 lpNewFormat->NextFormat = NULL;
537 lpFormat->NextFormat = lpNewFormat;
538 lpNewFormat->PrevFormat = lpFormat;
540 TRACE("Registering format(%d): %s drvData %d\n",
541 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
543 return lpNewFormat;
549 /**************************************************************************
550 * X11DRV_CLIPBOARD_GetClipboardInfo
552 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
554 BOOL bRet = FALSE;
556 SERVER_START_REQ( set_clipboard_info )
558 req->flags = 0;
560 if (wine_server_call_err( req ))
562 ERR("Failed to get clipboard owner.\n");
564 else
566 cbInfo->hWndOpen = reply->old_clipboard;
567 cbInfo->hWndOwner = reply->old_owner;
568 cbInfo->hWndViewer = reply->old_viewer;
569 cbInfo->seqno = reply->seqno;
570 cbInfo->flags = reply->flags;
572 bRet = TRUE;
575 SERVER_END_REQ;
577 return bRet;
581 /**************************************************************************
582 * X11DRV_CLIPBOARD_ReleaseOwnership
584 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
586 BOOL bRet = FALSE;
588 SERVER_START_REQ( set_clipboard_info )
590 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
592 if (wine_server_call_err( req ))
594 ERR("Failed to set clipboard.\n");
596 else
598 bRet = TRUE;
601 SERVER_END_REQ;
603 return bRet;
608 /**************************************************************************
609 * X11DRV_CLIPBOARD_InsertClipboardData
611 * Caller *must* have the clipboard open and be the owner.
613 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
614 HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
616 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
618 TRACE("format=%d lpData=%p hData16=%08x hData32=%p flags=0x%08x lpFormat=%p override=%d\n",
619 wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
621 if (lpData && !override)
622 return TRUE;
624 if (lpData)
626 X11DRV_CLIPBOARD_FreeData(lpData);
628 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
629 lpData->hData32 = hData32;
631 else
633 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
635 lpData->wFormatID = wFormatID;
636 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
637 lpData->hData32 = hData32;
638 lpData->lpFormat = lpFormat;
639 lpData->drvData = 0;
641 if (ClipData)
643 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
645 lpData->PrevData = lpPrevData;
646 lpData->NextData = ClipData;
648 lpPrevData->NextData = lpData;
649 ClipData->PrevData = lpData;
651 else
653 lpData->NextData = lpData;
654 lpData->PrevData = lpData;
655 ClipData = lpData;
658 ClipDataCount++;
661 lpData->wFlags = flags;
663 return TRUE;
667 /**************************************************************************
668 * X11DRV_CLIPBOARD_FreeData
670 * Free clipboard data handle.
672 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
674 TRACE("%d\n", lpData->wFormatID);
676 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
677 lpData->wFormatID <= CF_GDIOBJLAST) ||
678 lpData->wFormatID == CF_BITMAP ||
679 lpData->wFormatID == CF_DIB ||
680 lpData->wFormatID == CF_PALETTE)
682 if (lpData->hData32)
683 DeleteObject(lpData->hData32);
685 if (lpData->hData16)
686 DeleteObject(HGDIOBJ_32(lpData->hData16));
688 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
689 XFreePixmap(gdi_display, lpData->drvData);
691 else if (lpData->wFormatID == CF_METAFILEPICT)
693 if (lpData->hData32)
695 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
696 GlobalFree(lpData->hData32);
698 if (lpData->hData16)
699 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
700 and a shallow copy is enough to share a METAFILEPICT
701 structure between 16bit and 32bit clipboards. The MetaFile
702 should of course only be deleted once. */
703 GlobalFree16(lpData->hData16);
706 if (lpData->hData16)
708 METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
710 if (lpMetaPict)
712 /* To delete 16-bit meta file, we just need to free the associated
713 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
714 GlobalFree16(lpMetaPict->hMF);
715 lpMetaPict->hMF = 0;
718 GlobalFree16(lpData->hData16);
721 else if (lpData->wFormatID == CF_ENHMETAFILE)
723 if (lpData->hData32)
724 DeleteEnhMetaFile(lpData->hData32);
726 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
727 lpData->wFormatID > CF_PRIVATELAST)
729 if (lpData->hData32)
730 GlobalFree(lpData->hData32);
732 if (lpData->hData16)
733 GlobalFree16(lpData->hData16);
736 lpData->hData16 = 0;
737 lpData->hData32 = 0;
738 lpData->drvData = 0;
742 /**************************************************************************
743 * X11DRV_CLIPBOARD_UpdateCache
745 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
747 BOOL bret = TRUE;
749 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
751 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
753 ERR("Failed to retrieve clipboard information.\n");
754 bret = FALSE;
756 else if (wSeqNo < lpcbinfo->seqno)
758 X11DRV_EmptyClipboard(TRUE);
760 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
762 ERR("Failed to cache clipboard data owned by another process.\n");
763 bret = FALSE;
765 else
767 X11DRV_EndClipboardUpdate();
770 wSeqNo = lpcbinfo->seqno;
774 return bret;
778 /**************************************************************************
779 * X11DRV_CLIPBOARD_RenderFormat
781 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
783 BOOL bret = TRUE;
785 TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
786 lpData->wFormatID, lpData->hData32, lpData->hData16);
788 if (lpData->hData32 || lpData->hData16)
789 return bret; /* Already rendered */
791 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
792 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
793 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
795 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
797 ERR("Failed to cache clipboard data owned by another process. Format=%d\n",
798 lpData->wFormatID);
799 bret = FALSE;
802 else
804 CLIPBOARDINFO cbInfo;
806 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
808 /* Send a WM_RENDERFORMAT message to notify the owner to render the
809 * data requested into the clipboard.
811 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
812 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
814 if (!lpData->hData32 && !lpData->hData16)
815 bret = FALSE;
817 else
819 ERR("hWndClipOwner is lost!\n");
820 bret = FALSE;
824 return bret;
828 /**************************************************************************
829 * CLIPBOARD_ConvertText
830 * Returns number of required/converted characters - not bytes!
832 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
833 WORD dst_fmt, void *dst, INT dst_size)
835 UINT cp;
837 if(src_fmt == CF_UNICODETEXT)
839 switch(dst_fmt)
841 case CF_TEXT:
842 cp = CP_ACP;
843 break;
844 case CF_OEMTEXT:
845 cp = CP_OEMCP;
846 break;
847 default:
848 return 0;
850 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
853 if(dst_fmt == CF_UNICODETEXT)
855 switch(src_fmt)
857 case CF_TEXT:
858 cp = CP_ACP;
859 break;
860 case CF_OEMTEXT:
861 cp = CP_OEMCP;
862 break;
863 default:
864 return 0;
866 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
869 if(!dst_size) return src_size;
871 if(dst_size > src_size) dst_size = src_size;
873 if(src_fmt == CF_TEXT )
874 CharToOemBuffA(src, dst, dst_size);
875 else
876 OemToCharBuffA(src, dst, dst_size);
878 return dst_size;
882 /**************************************************************************
883 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
885 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
887 BOOL bret = FALSE;
889 TRACE("\n");
891 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
893 UINT wFormatID = lpData->wFormatID;
895 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
896 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
897 else
899 switch (wFormatID)
901 case CF_DIB:
902 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
903 break;
905 case CF_BITMAP:
906 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
907 break;
909 case CF_ENHMETAFILE:
910 case CF_METAFILEPICT:
911 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
912 break;
914 default:
915 FIXME("Called to synthesize unknown format\n");
916 break;
920 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
923 return bret;
927 /**************************************************************************
928 * X11DRV_CLIPBOARD_RenderSynthesizedText
930 * Renders synthesized text
932 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
934 LPCSTR lpstrS;
935 LPSTR lpstrT;
936 HANDLE hData32;
937 INT src_chars, dst_chars, alloc_size;
938 LPWINE_CLIPDATA lpSource = NULL;
940 TRACE(" %d\n", wFormatID);
942 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
943 lpSource->hData32)
944 return TRUE;
946 /* Look for rendered source or non-synthesized source */
947 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
948 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
950 TRACE("UNICODETEXT -> %d\n", wFormatID);
952 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
953 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
955 TRACE("TEXT -> %d\n", wFormatID);
957 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
958 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
960 TRACE("OEMTEXT -> %d\n", wFormatID);
963 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
964 !lpSource->hData32))
965 return FALSE;
967 /* Ask the clipboard owner to render the source text if necessary */
968 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
969 return FALSE;
971 if (lpSource->hData32)
973 lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
975 else
977 lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
980 if (!lpstrS)
981 return FALSE;
983 /* Text always NULL terminated */
984 if(lpSource->wFormatID == CF_UNICODETEXT)
985 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
986 else
987 src_chars = strlen(lpstrS) + 1;
989 /* Calculate number of characters in the destination buffer */
990 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
991 src_chars, wFormatID, NULL, 0);
993 if (!dst_chars)
994 return FALSE;
996 TRACE("Converting from '%d' to '%d', %i chars\n",
997 lpSource->wFormatID, wFormatID, src_chars);
999 /* Convert characters to bytes */
1000 if(wFormatID == CF_UNICODETEXT)
1001 alloc_size = dst_chars * sizeof(WCHAR);
1002 else
1003 alloc_size = dst_chars;
1005 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1006 GMEM_DDESHARE, alloc_size);
1008 lpstrT = (LPSTR)GlobalLock(hData32);
1010 if (lpstrT)
1012 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1013 wFormatID, lpstrT, dst_chars);
1014 GlobalUnlock(hData32);
1017 /* Unlock source */
1018 if (lpSource->hData32)
1019 GlobalUnlock(lpSource->hData32);
1020 else
1021 GlobalUnlock16(lpSource->hData16);
1023 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1027 /**************************************************************************
1028 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1030 * Renders synthesized DIB
1032 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1034 BOOL bret = FALSE;
1035 LPWINE_CLIPDATA lpSource = NULL;
1037 TRACE("\n");
1039 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1041 bret = TRUE;
1043 /* If we have a bitmap and it's not synthesized or it has been rendered */
1044 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1045 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1047 /* Render source if required */
1048 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1050 HDC hdc;
1051 HGLOBAL hData32;
1053 hdc = GetDC(NULL);
1054 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1055 ReleaseDC(NULL, hdc);
1057 if (hData32)
1059 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1060 bret = TRUE;
1065 return bret;
1069 /**************************************************************************
1070 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1072 * Renders synthesized bitmap
1074 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1076 BOOL bret = FALSE;
1077 LPWINE_CLIPDATA lpSource = NULL;
1079 TRACE("\n");
1081 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1083 bret = TRUE;
1085 /* If we have a dib and it's not synthesized or it has been rendered */
1086 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1087 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1089 /* Render source if required */
1090 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1092 HDC hdc;
1093 HBITMAP hData32;
1094 unsigned int offset;
1095 LPBITMAPINFOHEADER lpbmih;
1097 hdc = GetDC(NULL);
1098 lpbmih = (LPBITMAPINFOHEADER) GlobalLock(lpSource->hData32);
1100 offset = sizeof(BITMAPINFOHEADER)
1101 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1102 (1 << lpbmih->biBitCount)) : 0);
1104 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1105 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1107 GlobalUnlock(lpSource->hData32);
1108 ReleaseDC(NULL, hdc);
1110 if (hData32)
1112 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1113 bret = TRUE;
1118 return bret;
1122 /**************************************************************************
1123 * X11DRV_CLIPBOARD_ImportXAString
1125 * Import XA_STRING, converting the string to CF_TEXT.
1127 HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1129 LPBYTE lpdata;
1130 unsigned long cbytes;
1131 LPSTR lpstr;
1132 unsigned long i, inlcount = 0;
1133 HANDLE hText = 0;
1135 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1136 return 0;
1138 for (i = 0; i <= cbytes; i++)
1140 if (lpdata[i] == '\n')
1141 inlcount++;
1144 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1146 lpstr = GlobalLock(hText);
1148 for (i = 0, inlcount = 0; i <= cbytes; i++)
1150 if (lpdata[i] == '\n')
1151 lpstr[inlcount++] = '\r';
1153 lpstr[inlcount++] = lpdata[i];
1156 GlobalUnlock(hText);
1159 /* Free the retrieved property data */
1160 HeapFree(GetProcessHeap(), 0, lpdata);
1162 return hText;
1166 /**************************************************************************
1167 * X11DRV_CLIPBOARD_ImportUTF8
1169 * Import XA_STRING, converting the string to CF_UNICODE.
1171 HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1173 LPBYTE lpdata;
1174 unsigned long cbytes;
1175 LPSTR lpstr;
1176 unsigned long i, inlcount = 0;
1177 HANDLE hUnicodeText = 0;
1179 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1180 return 0;
1182 for (i = 0; i <= cbytes; i++)
1184 if (lpdata[i] == '\n')
1185 inlcount++;
1188 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1190 UINT count;
1192 for (i = 0, inlcount = 0; i <= cbytes; i++)
1194 if (lpdata[i] == '\n')
1195 lpstr[inlcount++] = '\r';
1197 lpstr[inlcount++] = lpdata[i];
1200 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1201 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1203 if (hUnicodeText)
1205 WCHAR *textW = GlobalLock(hUnicodeText);
1206 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1207 GlobalUnlock(hUnicodeText);
1210 HeapFree(GetProcessHeap(), 0, lpstr);
1213 /* Free the retrieved property data */
1214 HeapFree(GetProcessHeap(), 0, lpdata);
1216 return hUnicodeText;
1220 /**************************************************************************
1221 * X11DRV_CLIPBOARD_ImportCompoundText
1223 * Import COMPOUND_TEXT to CF_UNICODE
1225 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1227 int i, j;
1228 char** srcstr;
1229 int count, lcount;
1230 int srclen, destlen;
1231 HANDLE hUnicodeText;
1232 XTextProperty txtprop;
1234 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1236 return 0;
1239 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1240 txtprop.format = 8;
1241 wine_tsx11_lock();
1242 XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1243 wine_tsx11_unlock();
1244 HeapFree(GetProcessHeap(), 0, txtprop.value);
1246 TRACE("Importing %d line(s)\n", count);
1248 /* Compute number of lines */
1249 srclen = strlen(srcstr[0]);
1250 for (i = 0, lcount = 0; i <= srclen; i++)
1252 if (srcstr[0][i] == '\n')
1253 lcount++;
1256 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1258 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1260 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1262 WCHAR *deststr = GlobalLock(hUnicodeText);
1263 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1265 if (lcount)
1267 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1269 deststr[j] = deststr[i];
1271 if (deststr[i] == '\n')
1272 deststr[--j] = '\r';
1276 GlobalUnlock(hUnicodeText);
1279 wine_tsx11_lock();
1280 XFreeStringList(srcstr);
1281 wine_tsx11_unlock();
1283 return hUnicodeText;
1287 /**************************************************************************
1288 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1290 * Import XA_PIXMAP, converting the image to CF_DIB.
1292 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1294 HWND hwnd;
1295 HDC hdc;
1296 LPBYTE lpdata;
1297 unsigned long cbytes;
1298 Pixmap *pPixmap;
1299 HANDLE hClipData = 0;
1301 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1303 pPixmap = (Pixmap *) lpdata;
1305 hwnd = GetOpenClipboardWindow();
1306 hdc = GetDC(hwnd);
1308 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1309 ReleaseDC(hwnd, hdc);
1311 /* Free the retrieved property data */
1312 HeapFree(GetProcessHeap(), 0, lpdata);
1315 return hClipData;
1319 /**************************************************************************
1320 * X11DRV_CLIPBOARD_ImportMetaFilePict
1322 * Import MetaFilePict.
1324 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1326 LPBYTE lpdata;
1327 unsigned long cbytes;
1328 HANDLE hClipData = 0;
1330 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1332 if (cbytes)
1333 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1335 /* Free the retrieved property data */
1336 HeapFree(GetProcessHeap(), 0, lpdata);
1339 return hClipData;
1343 /**************************************************************************
1344 * X11DRV_ImportEnhMetaFile
1346 * Import EnhMetaFile.
1348 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1350 LPBYTE lpdata;
1351 unsigned long cbytes;
1352 HANDLE hClipData = 0;
1354 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1356 if (cbytes)
1357 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1359 /* Free the retrieved property data */
1360 HeapFree(GetProcessHeap(), 0, lpdata);
1363 return hClipData;
1367 /**************************************************************************
1368 * X11DRV_ImportClipbordaData
1370 * Generic import clipboard data routine.
1372 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1374 LPVOID lpClipData;
1375 LPBYTE lpdata;
1376 unsigned long cbytes;
1377 HANDLE hClipData = 0;
1379 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1381 if (cbytes)
1383 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1384 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1385 if (hClipData == 0)
1386 return NULL;
1388 if ((lpClipData = GlobalLock(hClipData)))
1390 memcpy(lpClipData, lpdata, cbytes);
1391 GlobalUnlock(hClipData);
1393 else
1395 GlobalFree(hClipData);
1396 hClipData = 0;
1400 /* Free the retrieved property data */
1401 HeapFree(GetProcessHeap(), 0, lpdata);
1404 return hClipData;
1408 /**************************************************************************
1409 X11DRV_CLIPBOARD_ExportClipboardData
1411 * Generic export clipboard data routine.
1413 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1414 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1416 LPVOID lpClipData;
1417 UINT datasize = 0;
1418 HANDLE hClipData = 0;
1420 *lpBytes = 0; /* Assume failure */
1422 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1423 ERR("Failed to export %d format\n", lpData->wFormatID);
1424 else
1426 datasize = GlobalSize(lpData->hData32);
1428 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1429 if (hClipData == 0) return NULL;
1431 if ((lpClipData = GlobalLock(hClipData)))
1433 LPVOID lpdata = GlobalLock(lpData->hData32);
1435 memcpy(lpClipData, lpdata, datasize);
1436 *lpBytes = datasize;
1438 GlobalUnlock(lpData->hData32);
1439 GlobalUnlock(hClipData);
1440 } else {
1441 GlobalFree(hClipData);
1442 hClipData = 0;
1446 return hClipData;
1450 /**************************************************************************
1451 * X11DRV_CLIPBOARD_ExportXAString
1453 * Export CF_TEXT converting the string to XA_STRING.
1454 * Helper function for X11DRV_CLIPBOARD_ExportString.
1456 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1458 UINT i, j;
1459 UINT size;
1460 LPSTR text, lpstr = NULL;
1462 *lpBytes = 0; /* Assume return has zero bytes */
1464 text = GlobalLock(lpData->hData32);
1465 size = strlen(text);
1467 /* remove carriage returns */
1468 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1469 if (lpstr == NULL)
1470 goto done;
1472 for (i = 0,j = 0; i < size && text[i]; i++)
1474 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1475 continue;
1476 lpstr[j++] = text[i];
1479 lpstr[j]='\0';
1480 *lpBytes = j; /* Number of bytes in string */
1482 done:
1483 HeapFree(GetProcessHeap(), 0, text);
1484 GlobalUnlock(lpData->hData32);
1486 return lpstr;
1490 /**************************************************************************
1491 * X11DRV_CLIPBOARD_ExportUTF8String
1493 * Export CF_UNICODE converting the string to UTF8.
1494 * Helper function for X11DRV_CLIPBOARD_ExportString.
1496 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1498 UINT i, j;
1499 UINT size;
1500 LPWSTR uni_text;
1501 LPSTR text, lpstr = NULL;
1503 *lpBytes = 0; /* Assume return has zero bytes */
1505 uni_text = GlobalLock(lpData->hData32);
1507 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1509 text = HeapAlloc(GetProcessHeap(), 0, size);
1510 if (!text)
1511 goto done;
1512 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1514 /* remove carriage returns */
1515 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1516 if (lpstr == NULL)
1517 goto done;
1519 for (i = 0,j = 0; i < size && text[i]; i++)
1521 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1522 continue;
1523 lpstr[j++] = text[i];
1525 lpstr[j]='\0';
1527 *lpBytes = j; /* Number of bytes in string */
1529 done:
1530 HeapFree(GetProcessHeap(), 0, text);
1531 GlobalUnlock(lpData->hData32);
1533 return lpstr;
1538 /**************************************************************************
1539 * X11DRV_CLIPBOARD_ExportCompoundText
1541 * Export CF_UNICODE to COMPOUND_TEXT
1542 * Helper function for X11DRV_CLIPBOARD_ExportString.
1544 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1545 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1547 char* lpstr = 0;
1548 XTextProperty prop;
1549 XICCEncodingStyle style;
1550 UINT i, j;
1551 UINT size;
1552 LPWSTR uni_text;
1554 uni_text = GlobalLock(lpData->hData32);
1556 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1557 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1558 if (!lpstr)
1559 return 0;
1561 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1563 /* remove carriage returns */
1564 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1566 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1567 continue;
1568 lpstr[j++] = lpstr[i];
1570 lpstr[j]='\0';
1572 GlobalUnlock(lpData->hData32);
1574 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1575 style = XCompoundTextStyle;
1576 else
1577 style = XStdICCTextStyle;
1579 /* Update the X property */
1580 wine_tsx11_lock();
1581 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1583 XSetTextProperty(display, requestor, &prop, rprop);
1584 XFree(prop.value);
1586 wine_tsx11_unlock();
1588 HeapFree(GetProcessHeap(), 0, lpstr);
1590 return 0;
1593 /**************************************************************************
1594 * X11DRV_CLIPBOARD_ExportString
1596 * Export string
1598 HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1599 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1601 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1603 if (aTarget == XA_STRING)
1604 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1605 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1606 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1607 rprop, lpData, lpBytes);
1608 else
1610 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1611 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1614 else
1615 ERR("Failed to render %d format\n", lpData->wFormatID);
1617 return 0;
1621 /**************************************************************************
1622 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1624 * Export CF_DIB to XA_PIXMAP.
1626 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1627 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1629 HDC hdc;
1630 HANDLE hData;
1631 unsigned char* lpData;
1633 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1635 ERR("Failed to export %d format\n", lpdata->wFormatID);
1636 return 0;
1639 if (!lpdata->drvData) /* If not already rendered */
1641 /* For convert from packed DIB to Pixmap */
1642 hdc = GetDC(0);
1643 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1644 ReleaseDC(0, hdc);
1647 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1649 /* Wrap pixmap so we can return a handle */
1650 hData = GlobalAlloc(0, *lpBytes);
1651 lpData = GlobalLock(hData);
1652 memcpy(lpData, &lpdata->drvData, *lpBytes);
1653 GlobalUnlock(hData);
1655 return hData;
1659 /**************************************************************************
1660 * X11DRV_CLIPBOARD_ExportMetaFilePict
1662 * Export MetaFilePict.
1664 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1665 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1667 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1669 ERR("Failed to export %d format\n", lpdata->wFormatID);
1670 return 0;
1673 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1677 /**************************************************************************
1678 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1680 * Export EnhMetaFile.
1682 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1683 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1685 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1687 ERR("Failed to export %d format\n", lpdata->wFormatID);
1688 return 0;
1691 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1695 /**************************************************************************
1696 * X11DRV_CLIPBOARD_QueryTargets
1698 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1699 Atom target, XEvent *xe)
1701 INT i;
1702 Bool res;
1704 wine_tsx11_lock();
1705 XConvertSelection(display, selection, target,
1706 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1707 wine_tsx11_unlock();
1710 * Wait until SelectionNotify is received
1712 for (i = 0; i < SELECTION_RETRIES; i++)
1714 wine_tsx11_lock();
1715 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1716 wine_tsx11_unlock();
1717 if (res && xe->xselection.selection == selection) break;
1719 usleep(SELECTION_WAIT);
1722 /* Verify that the selection returned a valid TARGETS property */
1723 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1725 /* Selection owner failed to respond or we missed the SelectionNotify */
1726 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1727 return FALSE;
1730 return TRUE;
1734 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1736 return (event->error_code == BadAtom);
1739 /**************************************************************************
1740 * X11DRV_CLIPBOARD_InsertSelectionProperties
1742 * Mark properties available for future retrieval.
1744 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1746 UINT i, nb_atoms = 0;
1747 Atom *atoms = NULL;
1749 /* Cache these formats in the clipboard cache */
1750 for (i = 0; i < count; i++)
1752 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1754 if (lpFormat)
1756 /* We found at least one Window's format that mapps to the property.
1757 * Continue looking for more.
1759 * If more than one property map to a Window's format then we use the first
1760 * one and ignore the rest.
1762 while (lpFormat)
1764 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1765 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1766 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1767 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1770 else if (properties[i])
1772 /* add it to the list of atoms that we don't know about yet */
1773 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1774 (count - i) * sizeof(*atoms) );
1775 if (atoms) atoms[nb_atoms++] = properties[i];
1779 /* query all unknown atoms in one go */
1780 if (atoms)
1782 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1783 if (names)
1785 X11DRV_expect_error( display, is_atom_error, NULL );
1786 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1787 if (X11DRV_check_error())
1789 WARN( "got some bad atoms, ignoring\n" );
1790 nb_atoms = 0;
1792 for (i = 0; i < nb_atoms; i++)
1794 WINE_CLIPFORMAT *lpFormat;
1795 LPWSTR wname;
1796 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1797 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1798 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1800 lpFormat = register_format( wname, atoms[i] );
1801 HeapFree(GetProcessHeap(), 0, wname);
1802 if (!lpFormat)
1804 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1805 continue;
1807 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1808 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1809 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1811 wine_tsx11_lock();
1812 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1813 wine_tsx11_unlock();
1814 HeapFree( GetProcessHeap(), 0, names );
1816 HeapFree( GetProcessHeap(), 0, atoms );
1821 /**************************************************************************
1822 * X11DRV_CLIPBOARD_QueryAvailableData
1824 * Caches the list of data formats available from the current selection.
1825 * This queries the selection owner for the TARGETS property and saves all
1826 * reported property types.
1828 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1830 XEvent xe;
1831 Atom atype=AnyPropertyType;
1832 int aformat;
1833 unsigned long remain;
1834 Atom* targetList=NULL;
1835 Window w;
1836 unsigned long cSelectionTargets = 0;
1838 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1840 ERR("Received request to cache selection but process is owner=(%08x)\n",
1841 (unsigned) selectionWindow);
1842 return -1; /* Prevent self request */
1845 w = thread_selection_wnd();
1846 if (!w)
1848 ERR("No window available to retrieve selection!\n");
1849 return -1;
1853 * Query the selection owner for the TARGETS property
1855 wine_tsx11_lock();
1856 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1857 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1859 wine_tsx11_unlock();
1860 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1861 selectionCacheSrc = XA_PRIMARY;
1862 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1863 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1864 else
1866 Atom xstr = XA_STRING;
1868 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1869 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1871 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1872 selectionCacheSrc = XA_PRIMARY;
1873 return 1;
1875 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1877 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1878 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1879 return 1;
1881 else
1883 WARN("Failed to query selection owner for available data.\n");
1884 return -1;
1888 else /* No selection owner so report 0 targets available */
1890 wine_tsx11_unlock();
1891 return 0;
1894 /* Read the TARGETS property contents */
1895 wine_tsx11_lock();
1896 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1897 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1898 &remain, (unsigned char**)&targetList) != Success)
1900 wine_tsx11_unlock();
1901 WARN("Failed to read TARGETS property\n");
1903 else
1905 wine_tsx11_unlock();
1906 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1907 atype, aformat, cSelectionTargets, remain);
1909 * The TARGETS property should have returned us a list of atoms
1910 * corresponding to each selection target format supported.
1912 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1914 if (aformat == 32)
1916 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1918 else if (aformat == 8) /* work around quartz-wm brain damage */
1920 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
1921 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
1922 for (i = 0; i < count; i++)
1923 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
1924 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
1925 HeapFree( GetProcessHeap(), 0, atoms );
1929 /* Free the list of targets */
1930 wine_tsx11_lock();
1931 XFree(targetList);
1932 wine_tsx11_unlock();
1935 return cSelectionTargets;
1939 /**************************************************************************
1940 * X11DRV_CLIPBOARD_ReadSelectionData
1942 * This method is invoked only when we DO NOT own the X selection
1944 * We always get the data from the selection client each time,
1945 * since we have no way of determining if the data in our cache is stale.
1947 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
1949 Bool res;
1950 DWORD i;
1951 XEvent xe;
1952 BOOL bRet = FALSE;
1954 TRACE("%d\n", lpData->wFormatID);
1956 if (!lpData->lpFormat)
1958 ERR("Requesting format %d but no source format linked to data.\n",
1959 lpData->wFormatID);
1960 return FALSE;
1963 if (!selectionAcquired)
1965 Window w = thread_selection_wnd();
1966 if(!w)
1968 ERR("No window available to read selection data!\n");
1969 return FALSE;
1972 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
1973 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
1975 wine_tsx11_lock();
1976 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
1977 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1978 wine_tsx11_unlock();
1980 /* wait until SelectionNotify is received */
1981 for (i = 0; i < SELECTION_RETRIES; i++)
1983 wine_tsx11_lock();
1984 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1985 wine_tsx11_unlock();
1986 if (res && xe.xselection.selection == selectionCacheSrc) break;
1988 usleep(SELECTION_WAIT);
1991 /* Verify that the selection returned a valid TARGETS property */
1992 if (xe.xselection.property != None)
1995 * Read the contents of the X selection property
1996 * into WINE's clipboard cache and converting the
1997 * data format if necessary.
1999 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2000 xe.xselection.property);
2002 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
2004 else
2006 TRACE("Failed to convert selection\n");
2009 else
2011 ERR("Received request to cache selection data but process is owner\n");
2014 TRACE("Returning %d\n", bRet);
2016 return bRet;
2020 /**************************************************************************
2021 * X11DRV_CLIPBOARD_GetProperty
2022 * Gets type, data and size.
2024 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2025 Atom *atype, unsigned char** data, unsigned long* datasize)
2027 int aformat;
2028 unsigned long pos = 0, nitems, remain, count;
2029 unsigned char *val = NULL, *buffer;
2031 TRACE("Reading property %lu from X window %lx\n", prop, w);
2033 for (;;)
2035 wine_tsx11_lock();
2036 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2037 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2039 wine_tsx11_unlock();
2040 WARN("Failed to read property\n");
2041 HeapFree( GetProcessHeap(), 0, val );
2042 return FALSE;
2045 count = get_property_size( aformat, nitems );
2046 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2047 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2049 if (!*data)
2051 XFree( buffer );
2052 wine_tsx11_unlock();
2053 HeapFree( GetProcessHeap(), 0, val );
2054 return FALSE;
2056 val = *data;
2057 memcpy( (int *)val + pos, buffer, count );
2058 XFree( buffer );
2059 wine_tsx11_unlock();
2060 if (!remain)
2062 *datasize = pos * sizeof(int) + count;
2063 val[*datasize] = 0;
2064 break;
2066 pos += count / sizeof(int);
2069 /* Delete the property on the window now that we are done
2070 * This will send a PropertyNotify event to the selection owner. */
2071 wine_tsx11_lock();
2072 XDeleteProperty(display, w, prop);
2073 wine_tsx11_unlock();
2074 return TRUE;
2078 /**************************************************************************
2079 * X11DRV_CLIPBOARD_ReadProperty
2080 * Reads the contents of the X selection property.
2082 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2083 unsigned char** data, unsigned long* datasize)
2085 Atom atype;
2086 XEvent xe;
2088 if (prop == None)
2089 return FALSE;
2091 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2092 return FALSE;
2094 wine_tsx11_lock();
2095 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2097 wine_tsx11_unlock();
2099 if (atype == x11drv_atom(INCR))
2101 unsigned char *buf = *data;
2102 unsigned long bufsize = 0;
2104 for (;;)
2106 int i;
2107 unsigned char *prop_data, *tmp;
2108 unsigned long prop_size;
2110 /* Wait until PropertyNotify is received */
2111 for (i = 0; i < SELECTION_RETRIES; i++)
2113 Bool res;
2115 wine_tsx11_lock();
2116 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2117 wine_tsx11_unlock();
2118 if (res && xe.xproperty.atom == prop &&
2119 xe.xproperty.state == PropertyNewValue)
2120 break;
2121 usleep(SELECTION_WAIT);
2124 if (i >= SELECTION_RETRIES ||
2125 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2127 HeapFree(GetProcessHeap(), 0, buf);
2128 return FALSE;
2131 /* Retrieved entire data. */
2132 if (prop_size == 0)
2134 HeapFree(GetProcessHeap(), 0, prop_data);
2135 *data = buf;
2136 *datasize = bufsize;
2137 return TRUE;
2140 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2141 if (!tmp)
2143 HeapFree(GetProcessHeap(), 0, buf);
2144 return FALSE;
2147 buf = tmp;
2148 memcpy(buf + bufsize, prop_data, prop_size + 1);
2149 bufsize += prop_size;
2150 HeapFree(GetProcessHeap(), 0, prop_data);
2154 return TRUE;
2158 /**************************************************************************
2159 * CLIPBOARD_SerializeMetafile
2161 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2163 HANDLE h = 0;
2165 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2167 if (out) /* Serialize out, caller should free memory */
2169 *lpcbytes = 0; /* Assume failure */
2171 if (wformat == CF_METAFILEPICT)
2173 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
2174 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2176 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2177 if (h)
2179 char *pdata = GlobalLock(h);
2181 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2182 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2184 *lpcbytes = size + sizeof(METAFILEPICT);
2186 GlobalUnlock(h);
2189 GlobalUnlock(hdata);
2191 else if (wformat == CF_ENHMETAFILE)
2193 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2195 h = GlobalAlloc(0, size);
2196 if (h)
2198 LPVOID pdata = GlobalLock(h);
2200 GetEnhMetaFileBits(hdata, size, pdata);
2201 *lpcbytes = size;
2203 GlobalUnlock(h);
2207 else
2209 if (wformat == CF_METAFILEPICT)
2211 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2212 if (h)
2214 unsigned int wiresize, size;
2215 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
2217 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2218 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2219 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2220 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2221 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2222 GlobalUnlock(h);
2225 else if (wformat == CF_ENHMETAFILE)
2227 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2231 return h;
2235 /**************************************************************************
2236 * X11DRV_CLIPBOARD_ReleaseSelection
2238 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2240 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2242 /* w is the window that lost the selection
2244 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2245 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2247 if (selectionAcquired && (w == selectionWindow))
2249 CLIPBOARDINFO cbinfo;
2251 /* completely give up the selection */
2252 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2254 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2256 if (cbinfo.flags & CB_PROCESS)
2258 /* Since we're still the owner, this wasn't initiated by
2259 another Wine process */
2260 if (OpenClipboard(hwnd))
2262 /* Destroy private objects */
2263 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2265 /* Give up ownership of the windows clipboard */
2266 X11DRV_CLIPBOARD_ReleaseOwnership();
2267 CloseClipboard();
2271 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2273 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2275 wine_tsx11_lock();
2276 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2278 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2279 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2281 else
2282 TRACE("We no longer own PRIMARY\n");
2283 wine_tsx11_unlock();
2285 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2287 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2289 wine_tsx11_lock();
2290 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2292 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2293 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2295 else
2296 TRACE("We no longer own CLIPBOARD\n");
2297 wine_tsx11_unlock();
2300 selectionWindow = None;
2302 X11DRV_EmptyClipboard(FALSE);
2304 /* Reset the selection flags now that we are done */
2305 selectionAcquired = S_NOSELECTION;
2310 /**************************************************************************
2311 * IsSelectionOwner (X11DRV.@)
2313 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2315 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2317 return selectionAcquired;
2321 /**************************************************************************
2322 * X11DRV Clipboard Exports
2323 **************************************************************************/
2326 /**************************************************************************
2327 * RegisterClipboardFormat (X11DRV.@)
2329 * Registers a custom X clipboard format
2330 * Returns: Format id or 0 on failure
2332 UINT X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2334 LPWINE_CLIPFORMAT lpFormat;
2336 if (FormatName == NULL) return 0;
2337 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2338 return lpFormat->wFormatID;
2342 /**************************************************************************
2343 * X11DRV_GetClipboardFormatName
2345 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2347 LPWINE_CLIPFORMAT lpFormat;
2349 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2351 if (wFormat < 0xc000)
2353 SetLastError(ERROR_INVALID_PARAMETER);
2354 return 0;
2357 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2359 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2361 TRACE("Unknown format 0x%08x!\n", wFormat);
2362 SetLastError(ERROR_INVALID_HANDLE);
2363 return 0;
2366 lstrcpynW(retStr, lpFormat->Name, maxlen);
2368 return strlenW(retStr);
2372 /**************************************************************************
2373 * AcquireClipboard (X11DRV.@)
2375 int X11DRV_AcquireClipboard(HWND hWndClipWindow)
2377 DWORD procid;
2378 Window owner;
2379 Display *display;
2381 TRACE(" %p\n", hWndClipWindow);
2384 * It's important that the selection get acquired from the thread
2385 * that owns the clipboard window. The primary reason is that we know
2386 * it is running a message loop and therefore can process the
2387 * X selection events.
2389 if (hWndClipWindow &&
2390 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2392 if (procid != GetCurrentProcessId())
2394 WARN("Setting clipboard owner to other process is not supported\n");
2395 hWndClipWindow = NULL;
2397 else
2399 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2400 GetCurrentThreadId(),
2401 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2403 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2407 owner = thread_selection_wnd();
2408 display = thread_display();
2410 wine_tsx11_lock();
2412 selectionAcquired = 0;
2413 selectionWindow = 0;
2415 /* Grab PRIMARY selection if not owned */
2416 if (use_primary_selection)
2417 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2419 /* Grab CLIPBOARD selection if not owned */
2420 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2422 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2423 selectionAcquired |= S_PRIMARY;
2425 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2426 selectionAcquired |= S_CLIPBOARD;
2428 wine_tsx11_unlock();
2430 if (selectionAcquired)
2432 selectionWindow = owner;
2433 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2436 return 1;
2440 /**************************************************************************
2441 * X11DRV_EmptyClipboard
2443 * Empty cached clipboard data.
2445 void X11DRV_EmptyClipboard(BOOL keepunowned)
2447 if (ClipData)
2449 LPWINE_CLIPDATA lpData, lpStart;
2450 LPWINE_CLIPDATA lpNext = ClipData;
2452 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2456 lpStart = ClipData;
2457 lpData = lpNext;
2458 lpNext = lpData->NextData;
2460 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2462 lpData->PrevData->NextData = lpData->NextData;
2463 lpData->NextData->PrevData = lpData->PrevData;
2465 if (lpData == ClipData)
2466 ClipData = lpNext != lpData ? lpNext : NULL;
2468 X11DRV_CLIPBOARD_FreeData(lpData);
2469 HeapFree(GetProcessHeap(), 0, lpData);
2471 ClipDataCount--;
2473 } while (lpNext != lpStart);
2476 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2481 /**************************************************************************
2482 * X11DRV_SetClipboardData
2484 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2486 DWORD flags = 0;
2487 BOOL bResult = TRUE;
2489 /* If it's not owned, data can only be set if the format data is not already owned
2490 and its rendering is not delayed */
2491 if (!owner)
2493 CLIPBOARDINFO cbinfo;
2494 LPWINE_CLIPDATA lpRender;
2496 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2498 if ((!hData16 && !hData32) ||
2499 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2500 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2501 bResult = FALSE;
2502 else
2503 flags = CF_FLAG_UNOWNED;
2506 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags, NULL, TRUE);
2508 return bResult;
2512 /**************************************************************************
2513 * CountClipboardFormats
2515 INT X11DRV_CountClipboardFormats(void)
2517 CLIPBOARDINFO cbinfo;
2519 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2521 TRACE(" count=%d\n", ClipDataCount);
2523 return ClipDataCount;
2527 /**************************************************************************
2528 * X11DRV_EnumClipboardFormats
2530 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2532 CLIPBOARDINFO cbinfo;
2533 UINT wNextFormat = 0;
2535 TRACE("(%04X)\n", wFormat);
2537 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2539 if (!wFormat)
2541 if (ClipData)
2542 wNextFormat = ClipData->wFormatID;
2544 else
2546 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2548 if (lpData && lpData->NextData != ClipData)
2549 wNextFormat = lpData->NextData->wFormatID;
2552 return wNextFormat;
2556 /**************************************************************************
2557 * X11DRV_IsClipboardFormatAvailable
2559 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2561 BOOL bRet = FALSE;
2562 CLIPBOARDINFO cbinfo;
2564 TRACE("(%04X)\n", wFormat);
2566 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2568 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2569 bRet = TRUE;
2571 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2573 return bRet;
2577 /**************************************************************************
2578 * GetClipboardData (USER.142)
2580 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2582 CLIPBOARDINFO cbinfo;
2583 LPWINE_CLIPDATA lpRender;
2585 TRACE("(%04X)\n", wFormat);
2587 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2589 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2591 if ( !lpRender->hData32 )
2592 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2594 /* Convert between 32 -> 16 bit data, if necessary */
2595 if (lpRender->hData32 && !lpRender->hData16)
2597 int size;
2599 if (lpRender->wFormatID == CF_METAFILEPICT)
2600 size = sizeof(METAFILEPICT16);
2601 else
2602 size = GlobalSize(lpRender->hData32);
2604 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2606 if (!lpRender->hData16)
2607 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2608 else
2610 if (lpRender->wFormatID == CF_METAFILEPICT)
2612 FIXME("\timplement function CopyMetaFilePict32to16\n");
2613 FIXME("\tin the appropriate file.\n");
2614 #ifdef SOMEONE_IMPLEMENTED_ME
2615 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2616 GlobalLock(lpRender->hData32));
2617 #endif
2619 else
2621 memcpy(GlobalLock16(lpRender->hData16),
2622 GlobalLock(lpRender->hData32), size);
2625 GlobalUnlock16(lpRender->hData16);
2626 GlobalUnlock(lpRender->hData32);
2630 /* Convert between 32 -> 16 bit data, if necessary */
2631 if (lpRender->hData16 && !lpRender->hData32)
2633 int size;
2635 if (lpRender->wFormatID == CF_METAFILEPICT)
2636 size = sizeof(METAFILEPICT16);
2637 else
2638 size = GlobalSize(lpRender->hData32);
2640 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2641 GMEM_DDESHARE, size);
2643 if (lpRender->wFormatID == CF_METAFILEPICT)
2645 FIXME("\timplement function CopyMetaFilePict16to32\n");
2646 FIXME("\tin the appropriate file.\n");
2647 #ifdef SOMEONE_IMPLEMENTED_ME
2648 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2649 GlobalLock(lpRender->hData16));
2650 #endif
2652 else
2654 memcpy(GlobalLock(lpRender->hData32),
2655 GlobalLock16(lpRender->hData16), size);
2658 GlobalUnlock(lpRender->hData32);
2659 GlobalUnlock16(lpRender->hData16);
2662 if (phData16)
2663 *phData16 = lpRender->hData16;
2665 if (phData32)
2666 *phData32 = lpRender->hData32;
2668 TRACE(" returning hData16(%04x) hData32(%p) (type %d)\n",
2669 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2671 return lpRender->hData16 || lpRender->hData32;
2674 return 0;
2678 /**************************************************************************
2679 * ResetSelectionOwner
2681 * Called when the thread owning the selection is destroyed and we need to
2682 * preserve the selection ownership. We look for another top level window
2683 * in this process and send it a message to acquire the selection.
2685 void X11DRV_ResetSelectionOwner(void)
2687 HWND hwnd;
2688 DWORD procid;
2690 TRACE("\n");
2692 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2693 return;
2695 selectionAcquired = S_NOSELECTION;
2696 selectionWindow = 0;
2698 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2701 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2703 if (GetCurrentProcessId() == procid)
2705 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2706 return;
2709 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2711 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2713 X11DRV_CLIPBOARD_ReleaseOwnership();
2714 X11DRV_EmptyClipboard(FALSE);
2718 /**************************************************************************
2719 * X11DRV_CLIPBOARD_SynthesizeData
2721 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2723 BOOL bsyn = TRUE;
2724 LPWINE_CLIPDATA lpSource = NULL;
2726 TRACE(" %d\n", wFormatID);
2728 /* Don't need to synthesize if it already exists */
2729 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2730 return TRUE;
2732 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2734 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2735 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2736 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2737 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2738 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2739 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2741 else if (wFormatID == CF_ENHMETAFILE)
2743 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2744 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2746 else if (wFormatID == CF_METAFILEPICT)
2748 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2749 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2751 else if (wFormatID == CF_DIB)
2753 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2754 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2756 else if (wFormatID == CF_BITMAP)
2758 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2759 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2762 if (bsyn)
2763 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2765 return bsyn;
2770 /**************************************************************************
2771 * X11DRV_EndClipboardUpdate
2772 * TODO:
2773 * Add locale if it hasn't already been added
2775 void X11DRV_EndClipboardUpdate(void)
2777 INT count = ClipDataCount;
2779 /* Do Unicode <-> Text <-> OEM mapping */
2780 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2781 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2782 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2784 /* Enhmetafile <-> MetafilePict mapping */
2785 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2786 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2788 /* DIB <-> Bitmap mapping */
2789 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2790 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2792 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2796 /***********************************************************************
2797 * X11DRV_SelectionRequest_TARGETS
2798 * Service a TARGETS selection request event
2800 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2801 Atom target, Atom rprop )
2803 UINT i;
2804 Atom* targets;
2805 ULONG cTargets;
2806 LPWINE_CLIPFORMAT lpFormats;
2807 LPWINE_CLIPDATA lpData;
2809 /* Create X atoms for any clipboard types which don't have atoms yet.
2810 * This avoids sending bogus zero atoms.
2811 * Without this, copying might not have access to all clipboard types.
2812 * FIXME: is it safe to call this here?
2814 intern_atoms();
2817 * Count the number of items we wish to expose as selection targets.
2819 cTargets = 1; /* Include TARGETS */
2821 if (!(lpData = ClipData)) return None;
2825 lpFormats = ClipFormats;
2827 while (lpFormats)
2829 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2830 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2831 cTargets++;
2833 lpFormats = lpFormats->NextFormat;
2836 lpData = lpData->NextData;
2838 while (lpData != ClipData);
2840 TRACE(" found %d formats\n", cTargets);
2842 /* Allocate temp buffer */
2843 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2844 if(targets == NULL)
2845 return None;
2847 i = 0;
2848 lpData = ClipData;
2849 targets[i++] = x11drv_atom(TARGETS);
2853 lpFormats = ClipFormats;
2855 while (lpFormats)
2857 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2858 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2859 targets[i++] = lpFormats->drvData;
2861 lpFormats = lpFormats->NextFormat;
2864 lpData = lpData->NextData;
2866 while (lpData != ClipData);
2868 wine_tsx11_lock();
2870 if (TRACE_ON(clipboard))
2872 unsigned int i;
2873 for ( i = 0; i < cTargets; i++)
2875 char *itemFmtName = XGetAtomName(display, targets[i]);
2876 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2877 XFree(itemFmtName);
2881 /* We may want to consider setting the type to xaTargets instead,
2882 * in case some apps expect this instead of XA_ATOM */
2883 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2884 PropModeReplace, (unsigned char *)targets, cTargets);
2885 wine_tsx11_unlock();
2887 HeapFree(GetProcessHeap(), 0, targets);
2889 return rprop;
2893 /***********************************************************************
2894 * X11DRV_SelectionRequest_MULTIPLE
2895 * Service a MULTIPLE selection request event
2896 * rprop contains a list of (target,property) atom pairs.
2897 * The first atom names a target and the second names a property.
2898 * The effect is as if we have received a sequence of SelectionRequest events
2899 * (one for each atom pair) except that:
2900 * 1. We reply with a SelectionNotify only when all the requested conversions
2901 * have been performed.
2902 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2903 * we replace the atom in the property by None.
2905 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2907 Display *display = pevent->display;
2908 Atom rprop;
2909 Atom atype=AnyPropertyType;
2910 int aformat;
2911 unsigned long remain;
2912 Atom* targetPropList=NULL;
2913 unsigned long cTargetPropList = 0;
2915 /* If the specified property is None the requestor is an obsolete client.
2916 * We support these by using the specified target atom as the reply property.
2918 rprop = pevent->property;
2919 if( rprop == None )
2920 rprop = pevent->target;
2921 if (!rprop)
2922 return 0;
2924 /* Read the MULTIPLE property contents. This should contain a list of
2925 * (target,property) atom pairs.
2927 wine_tsx11_lock();
2928 if(XGetWindowProperty(display, pevent->requestor, rprop,
2929 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2930 &cTargetPropList, &remain,
2931 (unsigned char**)&targetPropList) != Success)
2933 wine_tsx11_unlock();
2934 TRACE("\tCouldn't read MULTIPLE property\n");
2936 else
2938 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2939 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2940 wine_tsx11_unlock();
2943 * Make sure we got what we expect.
2944 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2945 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2946 * However some X apps(such as XPaint) are not compliant with this and return
2947 * a user defined atom in atype when XGetWindowProperty is called.
2948 * The data *is* an atom pair but is not denoted as such.
2950 if(aformat == 32 /* atype == xAtomPair */ )
2952 unsigned int i;
2954 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2955 * for each (target,property) pair */
2957 for (i = 0; i < cTargetPropList; i+=2)
2959 XSelectionRequestEvent event;
2961 if (TRACE_ON(clipboard))
2963 char *targetName, *propName;
2964 wine_tsx11_lock();
2965 targetName = XGetAtomName(display, targetPropList[i]);
2966 propName = XGetAtomName(display, targetPropList[i+1]);
2967 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
2968 i/2, targetName, propName);
2969 XFree(targetName);
2970 XFree(propName);
2971 wine_tsx11_unlock();
2974 /* We must have a non "None" property to service a MULTIPLE target atom */
2975 if ( !targetPropList[i+1] )
2977 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
2978 continue;
2981 /* Set up an XSelectionRequestEvent for this (target,property) pair */
2982 event = *pevent;
2983 event.target = targetPropList[i];
2984 event.property = targetPropList[i+1];
2986 /* Fire a SelectionRequest, informing the handler that we are processing
2987 * a MULTIPLE selection request event.
2989 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
2993 /* Free the list of targets/properties */
2994 wine_tsx11_lock();
2995 XFree(targetPropList);
2996 wine_tsx11_unlock();
2999 return rprop;
3003 /***********************************************************************
3004 * X11DRV_HandleSelectionRequest
3005 * Process an event selection request event.
3006 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3007 * recursively while servicing a "MULTIPLE" selection target.
3009 * Note: We only receive this event when WINE owns the X selection
3011 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3013 Display *display = event->display;
3014 XSelectionEvent result;
3015 Atom rprop = None;
3016 Window request = event->requestor;
3018 TRACE("\n");
3021 * We can only handle the selection request if :
3022 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3023 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3024 * since this has been already done.
3026 if ( !bIsMultiple )
3028 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3029 goto END;
3032 /* If the specified property is None the requestor is an obsolete client.
3033 * We support these by using the specified target atom as the reply property.
3035 rprop = event->property;
3036 if( rprop == None )
3037 rprop = event->target;
3039 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3041 /* TARGETS selection request */
3042 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3044 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3046 /* MULTIPLE selection request */
3047 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3049 else
3051 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3053 if (lpFormat && lpFormat->lpDrvExportFunc)
3055 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3057 if (lpData)
3059 unsigned char* lpClipData;
3060 DWORD cBytes;
3061 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3062 rprop, lpData, &cBytes);
3064 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3066 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
3068 wine_tsx11_lock();
3069 XChangeProperty(display, request, rprop, event->target,
3070 8, PropModeReplace, lpClipData, cBytes);
3071 wine_tsx11_unlock();
3073 GlobalUnlock(hClipData);
3074 GlobalFree(hClipData);
3080 END:
3081 /* reply to sender
3082 * SelectionNotify should be sent only at the end of a MULTIPLE request
3084 if ( !bIsMultiple )
3086 result.type = SelectionNotify;
3087 result.display = display;
3088 result.requestor = request;
3089 result.selection = event->selection;
3090 result.property = rprop;
3091 result.target = event->target;
3092 result.time = event->time;
3093 TRACE("Sending SelectionNotify event...\n");
3094 wine_tsx11_lock();
3095 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3096 wine_tsx11_unlock();
3101 /***********************************************************************
3102 * X11DRV_SelectionRequest
3104 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3106 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3110 /***********************************************************************
3111 * X11DRV_SelectionClear
3113 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3115 XSelectionClearEvent *event = &xev->xselectionclear;
3116 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3117 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3118 event->window, hWnd, event->time );