gdiplus: Add TRACE(..) for font calls.
[wine/multimedia.git] / dlls / winex11.drv / clipboard.c
blob8a35a0bd3cdb80e80b1d6f258b517472a9a60767
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);
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 wine_tsx11_lock();
1235 if (!XGetTextProperty(display, w, &txtprop, prop))
1237 wine_tsx11_unlock();
1238 return 0;
1241 XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1242 wine_tsx11_unlock();
1244 TRACE("Importing %d line(s)\n", count);
1246 /* Compute number of lines */
1247 srclen = strlen(srcstr[0]);
1248 for (i = 0, lcount = 0; i <= srclen; i++)
1250 if (srcstr[0][i] == '\n')
1251 lcount++;
1254 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1256 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1258 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1260 WCHAR *deststr = GlobalLock(hUnicodeText);
1261 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1263 if (lcount)
1265 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1267 deststr[j] = deststr[i];
1269 if (deststr[i] == '\n')
1270 deststr[--j] = '\r';
1274 GlobalUnlock(hUnicodeText);
1277 wine_tsx11_lock();
1278 XFreeStringList(srcstr);
1279 XFree(txtprop.value);
1280 wine_tsx11_unlock();
1282 return hUnicodeText;
1286 /**************************************************************************
1287 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1289 * Import XA_PIXMAP, converting the image to CF_DIB.
1291 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1293 HWND hwnd;
1294 HDC hdc;
1295 LPBYTE lpdata;
1296 unsigned long cbytes;
1297 Pixmap *pPixmap;
1298 HANDLE hClipData = 0;
1300 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1302 pPixmap = (Pixmap *) lpdata;
1304 hwnd = GetOpenClipboardWindow();
1305 hdc = GetDC(hwnd);
1307 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1308 ReleaseDC(hwnd, hdc);
1310 /* Free the retrieved property data */
1311 HeapFree(GetProcessHeap(), 0, lpdata);
1314 return hClipData;
1318 /**************************************************************************
1319 * X11DRV_CLIPBOARD_ImportMetaFilePict
1321 * Import MetaFilePict.
1323 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1325 LPBYTE lpdata;
1326 unsigned long cbytes;
1327 HANDLE hClipData = 0;
1329 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1331 if (cbytes)
1332 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1334 /* Free the retrieved property data */
1335 HeapFree(GetProcessHeap(), 0, lpdata);
1338 return hClipData;
1342 /**************************************************************************
1343 * X11DRV_ImportEnhMetaFile
1345 * Import EnhMetaFile.
1347 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1349 LPBYTE lpdata;
1350 unsigned long cbytes;
1351 HANDLE hClipData = 0;
1353 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1355 if (cbytes)
1356 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1358 /* Free the retrieved property data */
1359 HeapFree(GetProcessHeap(), 0, lpdata);
1362 return hClipData;
1366 /**************************************************************************
1367 * X11DRV_ImportClipbordaData
1369 * Generic import clipboard data routine.
1371 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1373 LPVOID lpClipData;
1374 LPBYTE lpdata;
1375 unsigned long cbytes;
1376 HANDLE hClipData = 0;
1378 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1380 if (cbytes)
1382 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1383 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1384 if (hClipData == 0)
1385 return NULL;
1387 if ((lpClipData = GlobalLock(hClipData)))
1389 memcpy(lpClipData, lpdata, cbytes);
1390 GlobalUnlock(hClipData);
1392 else
1394 GlobalFree(hClipData);
1395 hClipData = 0;
1399 /* Free the retrieved property data */
1400 HeapFree(GetProcessHeap(), 0, lpdata);
1403 return hClipData;
1407 /**************************************************************************
1408 X11DRV_CLIPBOARD_ExportClipboardData
1410 * Generic export clipboard data routine.
1412 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1413 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1415 LPVOID lpClipData;
1416 UINT datasize = 0;
1417 HANDLE hClipData = 0;
1419 *lpBytes = 0; /* Assume failure */
1421 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1422 ERR("Failed to export %d format\n", lpData->wFormatID);
1423 else
1425 datasize = GlobalSize(lpData->hData32);
1427 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1428 if (hClipData == 0) return NULL;
1430 if ((lpClipData = GlobalLock(hClipData)))
1432 LPVOID lpdata = GlobalLock(lpData->hData32);
1434 memcpy(lpClipData, lpdata, datasize);
1435 *lpBytes = datasize;
1437 GlobalUnlock(lpData->hData32);
1438 GlobalUnlock(hClipData);
1439 } else {
1440 GlobalFree(hClipData);
1441 hClipData = 0;
1445 return hClipData;
1449 /**************************************************************************
1450 * X11DRV_CLIPBOARD_ExportXAString
1452 * Export CF_TEXT converting the string to XA_STRING.
1453 * Helper function for X11DRV_CLIPBOARD_ExportString.
1455 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1457 UINT i, j;
1458 UINT size;
1459 LPSTR text, lpstr = NULL;
1461 *lpBytes = 0; /* Assume return has zero bytes */
1463 text = GlobalLock(lpData->hData32);
1464 size = strlen(text);
1466 /* remove carriage returns */
1467 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1468 if (lpstr == NULL)
1469 goto done;
1471 for (i = 0,j = 0; i < size && text[i]; i++)
1473 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1474 continue;
1475 lpstr[j++] = text[i];
1478 lpstr[j]='\0';
1479 *lpBytes = j; /* Number of bytes in string */
1481 done:
1482 HeapFree(GetProcessHeap(), 0, text);
1483 GlobalUnlock(lpData->hData32);
1485 return lpstr;
1489 /**************************************************************************
1490 * X11DRV_CLIPBOARD_ExportUTF8String
1492 * Export CF_UNICODE converting the string to UTF8.
1493 * Helper function for X11DRV_CLIPBOARD_ExportString.
1495 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1497 UINT i, j;
1498 UINT size;
1499 LPWSTR uni_text;
1500 LPSTR text, lpstr = NULL;
1502 *lpBytes = 0; /* Assume return has zero bytes */
1504 uni_text = GlobalLock(lpData->hData32);
1506 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1508 text = HeapAlloc(GetProcessHeap(), 0, size);
1509 if (!text)
1510 goto done;
1511 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1513 /* remove carriage returns */
1514 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1515 if (lpstr == NULL)
1516 goto done;
1518 for (i = 0,j = 0; i < size && text[i]; i++)
1520 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1521 continue;
1522 lpstr[j++] = text[i];
1524 lpstr[j]='\0';
1526 *lpBytes = j; /* Number of bytes in string */
1528 done:
1529 HeapFree(GetProcessHeap(), 0, text);
1530 GlobalUnlock(lpData->hData32);
1532 return lpstr;
1537 /**************************************************************************
1538 * X11DRV_CLIPBOARD_ExportCompoundText
1540 * Export CF_UNICODE to COMPOUND_TEXT
1541 * Helper function for X11DRV_CLIPBOARD_ExportString.
1543 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1544 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1546 char* lpstr = 0;
1547 XTextProperty prop;
1548 XICCEncodingStyle style;
1549 UINT i, j;
1550 UINT size;
1551 LPWSTR uni_text;
1553 uni_text = GlobalLock(lpData->hData32);
1555 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1556 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1557 if (!lpstr)
1558 return 0;
1560 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1562 /* remove carriage returns */
1563 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1565 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1566 continue;
1567 lpstr[j++] = lpstr[i];
1569 lpstr[j]='\0';
1571 GlobalUnlock(lpData->hData32);
1573 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1574 style = XCompoundTextStyle;
1575 else
1576 style = XStdICCTextStyle;
1578 /* Update the X property */
1579 wine_tsx11_lock();
1580 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1582 XSetTextProperty(display, requestor, &prop, rprop);
1583 XFree(prop.value);
1585 wine_tsx11_unlock();
1587 HeapFree(GetProcessHeap(), 0, lpstr);
1589 return 0;
1592 /**************************************************************************
1593 * X11DRV_CLIPBOARD_ExportString
1595 * Export string
1597 HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1598 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1600 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1602 if (aTarget == XA_STRING)
1603 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1604 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1605 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1606 rprop, lpData, lpBytes);
1607 else
1609 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1610 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1613 else
1614 ERR("Failed to render %d format\n", lpData->wFormatID);
1616 return 0;
1620 /**************************************************************************
1621 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1623 * Export CF_DIB to XA_PIXMAP.
1625 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1626 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1628 HDC hdc;
1629 HANDLE hData;
1630 unsigned char* lpData;
1632 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1634 ERR("Failed to export %d format\n", lpdata->wFormatID);
1635 return 0;
1638 if (!lpdata->drvData) /* If not already rendered */
1640 /* For convert from packed DIB to Pixmap */
1641 hdc = GetDC(0);
1642 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1643 ReleaseDC(0, hdc);
1646 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1648 /* Wrap pixmap so we can return a handle */
1649 hData = GlobalAlloc(0, *lpBytes);
1650 lpData = GlobalLock(hData);
1651 memcpy(lpData, &lpdata->drvData, *lpBytes);
1652 GlobalUnlock(hData);
1654 return hData;
1658 /**************************************************************************
1659 * X11DRV_CLIPBOARD_ExportMetaFilePict
1661 * Export MetaFilePict.
1663 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1664 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1666 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1668 ERR("Failed to export %d format\n", lpdata->wFormatID);
1669 return 0;
1672 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1676 /**************************************************************************
1677 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1679 * Export EnhMetaFile.
1681 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1682 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1684 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1686 ERR("Failed to export %d format\n", lpdata->wFormatID);
1687 return 0;
1690 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1694 /**************************************************************************
1695 * X11DRV_CLIPBOARD_QueryTargets
1697 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1698 Atom target, XEvent *xe)
1700 INT i;
1701 Bool res;
1703 wine_tsx11_lock();
1704 XConvertSelection(display, selection, target,
1705 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1706 wine_tsx11_unlock();
1709 * Wait until SelectionNotify is received
1711 for (i = 0; i < SELECTION_RETRIES; i++)
1713 wine_tsx11_lock();
1714 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1715 wine_tsx11_unlock();
1716 if (res && xe->xselection.selection == selection) break;
1718 usleep(SELECTION_WAIT);
1721 /* Verify that the selection returned a valid TARGETS property */
1722 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1724 /* Selection owner failed to respond or we missed the SelectionNotify */
1725 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1726 return FALSE;
1729 return TRUE;
1733 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1735 return (event->error_code == BadAtom);
1738 /**************************************************************************
1739 * X11DRV_CLIPBOARD_InsertSelectionProperties
1741 * Mark properties available for future retrieval.
1743 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1745 UINT i, nb_atoms = 0;
1746 Atom *atoms = NULL;
1748 /* Cache these formats in the clipboard cache */
1749 for (i = 0; i < count; i++)
1751 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1753 if (lpFormat)
1755 /* We found at least one Window's format that mapps to the property.
1756 * Continue looking for more.
1758 * If more than one property map to a Window's format then we use the first
1759 * one and ignore the rest.
1761 while (lpFormat)
1763 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1764 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1765 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1766 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1769 else if (properties[i])
1771 /* add it to the list of atoms that we don't know about yet */
1772 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1773 (count - i) * sizeof(*atoms) );
1774 if (atoms) atoms[nb_atoms++] = properties[i];
1778 /* query all unknown atoms in one go */
1779 if (atoms)
1781 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1782 if (names)
1784 X11DRV_expect_error( display, is_atom_error, NULL );
1785 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1786 if (X11DRV_check_error())
1788 WARN( "got some bad atoms, ignoring\n" );
1789 nb_atoms = 0;
1791 for (i = 0; i < nb_atoms; i++)
1793 WINE_CLIPFORMAT *lpFormat;
1794 LPWSTR wname;
1795 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1796 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1797 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1799 lpFormat = register_format( wname, atoms[i] );
1800 HeapFree(GetProcessHeap(), 0, wname);
1801 if (!lpFormat)
1803 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1804 continue;
1806 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1807 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1808 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1810 wine_tsx11_lock();
1811 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1812 wine_tsx11_unlock();
1813 HeapFree( GetProcessHeap(), 0, names );
1815 HeapFree( GetProcessHeap(), 0, atoms );
1820 /**************************************************************************
1821 * X11DRV_CLIPBOARD_QueryAvailableData
1823 * Caches the list of data formats available from the current selection.
1824 * This queries the selection owner for the TARGETS property and saves all
1825 * reported property types.
1827 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1829 XEvent xe;
1830 Atom atype=AnyPropertyType;
1831 int aformat;
1832 unsigned long remain;
1833 Atom* targetList=NULL;
1834 Window w;
1835 unsigned long cSelectionTargets = 0;
1837 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1839 ERR("Received request to cache selection but process is owner=(%08x)\n",
1840 (unsigned) selectionWindow);
1841 return -1; /* Prevent self request */
1844 w = thread_selection_wnd();
1845 if (!w)
1847 ERR("No window available to retrieve selection!\n");
1848 return -1;
1852 * Query the selection owner for the TARGETS property
1854 wine_tsx11_lock();
1855 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1856 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1858 wine_tsx11_unlock();
1859 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1860 selectionCacheSrc = XA_PRIMARY;
1861 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1862 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1863 else
1865 Atom xstr = XA_STRING;
1867 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1868 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1870 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1871 selectionCacheSrc = XA_PRIMARY;
1872 return 1;
1874 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1876 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1877 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1878 return 1;
1880 else
1882 WARN("Failed to query selection owner for available data.\n");
1883 return -1;
1887 else /* No selection owner so report 0 targets available */
1889 wine_tsx11_unlock();
1890 return 0;
1893 /* Read the TARGETS property contents */
1894 wine_tsx11_lock();
1895 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1896 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1897 &remain, (unsigned char**)&targetList) != Success)
1899 wine_tsx11_unlock();
1900 WARN("Failed to read TARGETS property\n");
1902 else
1904 wine_tsx11_unlock();
1905 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1906 atype, aformat, cSelectionTargets, remain);
1908 * The TARGETS property should have returned us a list of atoms
1909 * corresponding to each selection target format supported.
1911 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1913 if (aformat == 32)
1915 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1917 else if (aformat == 8) /* work around quartz-wm brain damage */
1919 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
1920 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
1921 for (i = 0; i < count; i++)
1922 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
1923 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
1924 HeapFree( GetProcessHeap(), 0, atoms );
1928 /* Free the list of targets */
1929 wine_tsx11_lock();
1930 XFree(targetList);
1931 wine_tsx11_unlock();
1934 return cSelectionTargets;
1938 /**************************************************************************
1939 * X11DRV_CLIPBOARD_ReadSelectionData
1941 * This method is invoked only when we DO NOT own the X selection
1943 * We always get the data from the selection client each time,
1944 * since we have no way of determining if the data in our cache is stale.
1946 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
1948 Bool res;
1949 DWORD i;
1950 XEvent xe;
1951 BOOL bRet = FALSE;
1953 TRACE("%d\n", lpData->wFormatID);
1955 if (!lpData->lpFormat)
1957 ERR("Requesting format %d but no source format linked to data.\n",
1958 lpData->wFormatID);
1959 return FALSE;
1962 if (!selectionAcquired)
1964 Window w = thread_selection_wnd();
1965 if(!w)
1967 ERR("No window available to read selection data!\n");
1968 return FALSE;
1971 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
1972 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
1974 wine_tsx11_lock();
1975 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
1976 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1977 wine_tsx11_unlock();
1979 /* wait until SelectionNotify is received */
1980 for (i = 0; i < SELECTION_RETRIES; i++)
1982 wine_tsx11_lock();
1983 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1984 wine_tsx11_unlock();
1985 if (res && xe.xselection.selection == selectionCacheSrc) break;
1987 usleep(SELECTION_WAIT);
1990 /* Verify that the selection returned a valid TARGETS property */
1991 if (xe.xselection.property != None)
1994 * Read the contents of the X selection property
1995 * into WINE's clipboard cache and converting the
1996 * data format if necessary.
1998 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
1999 xe.xselection.property);
2001 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
2003 else
2005 TRACE("Failed to convert selection\n");
2008 else
2010 ERR("Received request to cache selection data but process is owner\n");
2013 TRACE("Returning %d\n", bRet);
2015 return bRet;
2019 /**************************************************************************
2020 * X11DRV_CLIPBOARD_ReadProperty
2021 * Reads the contents of the X selection property.
2023 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2024 unsigned char** data, unsigned long* datasize)
2026 Atom atype = AnyPropertyType;
2027 int aformat;
2028 unsigned long pos = 0, nitems, remain, count;
2029 unsigned char *val = NULL, *buffer;
2031 if (prop == None)
2032 return FALSE;
2034 TRACE("Reading property %lu from X window %lx\n", prop, w);
2036 for (;;)
2038 wine_tsx11_lock();
2039 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2040 AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
2042 wine_tsx11_unlock();
2043 WARN("Failed to read property\n");
2044 HeapFree( GetProcessHeap(), 0, val );
2045 return FALSE;
2048 count = get_property_size( aformat, nitems );
2049 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2050 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2052 if (!*data)
2054 XFree( buffer );
2055 wine_tsx11_unlock();
2056 HeapFree( GetProcessHeap(), 0, val );
2057 return FALSE;
2059 val = *data;
2060 memcpy( (int *)val + pos, buffer, count );
2061 XFree( buffer );
2062 wine_tsx11_unlock();
2063 if (!remain)
2065 *datasize = pos * sizeof(int) + count;
2066 val[*datasize] = 0;
2067 break;
2069 pos += count / sizeof(int);
2072 /* Delete the property on the window now that we are done
2073 * This will send a PropertyNotify event to the selection owner. */
2074 wine_tsx11_lock();
2075 XDeleteProperty(display, w, prop);
2076 wine_tsx11_unlock();
2077 return TRUE;
2081 /**************************************************************************
2082 * CLIPBOARD_SerializeMetafile
2084 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2086 HANDLE h = 0;
2088 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2090 if (out) /* Serialize out, caller should free memory */
2092 *lpcbytes = 0; /* Assume failure */
2094 if (wformat == CF_METAFILEPICT)
2096 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
2097 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2099 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2100 if (h)
2102 char *pdata = GlobalLock(h);
2104 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2105 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2107 *lpcbytes = size + sizeof(METAFILEPICT);
2109 GlobalUnlock(h);
2112 GlobalUnlock(hdata);
2114 else if (wformat == CF_ENHMETAFILE)
2116 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2118 h = GlobalAlloc(0, size);
2119 if (h)
2121 LPVOID pdata = GlobalLock(h);
2123 GetEnhMetaFileBits(hdata, size, pdata);
2124 *lpcbytes = size;
2126 GlobalUnlock(h);
2130 else
2132 if (wformat == CF_METAFILEPICT)
2134 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2135 if (h)
2137 unsigned int wiresize, size;
2138 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
2140 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2141 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2142 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2143 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2144 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2145 GlobalUnlock(h);
2148 else if (wformat == CF_ENHMETAFILE)
2150 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2154 return h;
2158 /**************************************************************************
2159 * X11DRV_CLIPBOARD_ReleaseSelection
2161 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2163 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2165 /* w is the window that lost the selection
2167 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2168 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2170 if (selectionAcquired && (w == selectionWindow))
2172 CLIPBOARDINFO cbinfo;
2174 /* completely give up the selection */
2175 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2177 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2179 if (cbinfo.flags & CB_PROCESS)
2181 /* Since we're still the owner, this wasn't initiated by
2182 another Wine process */
2183 if (OpenClipboard(hwnd))
2185 /* Destroy private objects */
2186 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2188 /* Give up ownership of the windows clipboard */
2189 X11DRV_CLIPBOARD_ReleaseOwnership();
2190 CloseClipboard();
2194 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2196 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2198 wine_tsx11_lock();
2199 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2201 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2202 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2204 else
2205 TRACE("We no longer own PRIMARY\n");
2206 wine_tsx11_unlock();
2208 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2210 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2212 wine_tsx11_lock();
2213 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2215 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2216 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2218 else
2219 TRACE("We no longer own CLIPBOARD\n");
2220 wine_tsx11_unlock();
2223 selectionWindow = None;
2225 X11DRV_EmptyClipboard(FALSE);
2227 /* Reset the selection flags now that we are done */
2228 selectionAcquired = S_NOSELECTION;
2233 /**************************************************************************
2234 * IsSelectionOwner (X11DRV.@)
2236 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2238 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2240 return selectionAcquired;
2244 /**************************************************************************
2245 * X11DRV Clipboard Exports
2246 **************************************************************************/
2249 /**************************************************************************
2250 * RegisterClipboardFormat (X11DRV.@)
2252 * Registers a custom X clipboard format
2253 * Returns: Format id or 0 on failure
2255 UINT X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2257 LPWINE_CLIPFORMAT lpFormat;
2259 if (FormatName == NULL) return 0;
2260 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2261 return lpFormat->wFormatID;
2265 /**************************************************************************
2266 * X11DRV_GetClipboardFormatName
2268 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2270 LPWINE_CLIPFORMAT lpFormat;
2272 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2274 if (wFormat < 0xc000)
2276 SetLastError(ERROR_INVALID_PARAMETER);
2277 return 0;
2280 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2282 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2284 TRACE("Unknown format 0x%08x!\n", wFormat);
2285 SetLastError(ERROR_INVALID_HANDLE);
2286 return 0;
2289 lstrcpynW(retStr, lpFormat->Name, maxlen);
2291 return strlenW(retStr);
2295 /**************************************************************************
2296 * AcquireClipboard (X11DRV.@)
2298 int X11DRV_AcquireClipboard(HWND hWndClipWindow)
2300 DWORD procid;
2301 Window owner;
2302 Display *display;
2304 TRACE(" %p\n", hWndClipWindow);
2307 * It's important that the selection get acquired from the thread
2308 * that owns the clipboard window. The primary reason is that we know
2309 * it is running a message loop and therefore can process the
2310 * X selection events.
2312 if (hWndClipWindow &&
2313 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2315 if (procid != GetCurrentProcessId())
2317 WARN("Setting clipboard owner to other process is not supported\n");
2318 hWndClipWindow = NULL;
2320 else
2322 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2323 GetCurrentThreadId(),
2324 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2326 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2330 owner = thread_selection_wnd();
2331 display = thread_display();
2333 wine_tsx11_lock();
2335 selectionAcquired = 0;
2336 selectionWindow = 0;
2338 /* Grab PRIMARY selection if not owned */
2339 if (use_primary_selection)
2340 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2342 /* Grab CLIPBOARD selection if not owned */
2343 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2345 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2346 selectionAcquired |= S_PRIMARY;
2348 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2349 selectionAcquired |= S_CLIPBOARD;
2351 wine_tsx11_unlock();
2353 if (selectionAcquired)
2355 selectionWindow = owner;
2356 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2359 return 1;
2363 /**************************************************************************
2364 * X11DRV_EmptyClipboard
2366 * Empty cached clipboard data.
2368 void X11DRV_EmptyClipboard(BOOL keepunowned)
2370 if (ClipData)
2372 LPWINE_CLIPDATA lpData, lpStart;
2373 LPWINE_CLIPDATA lpNext = ClipData;
2375 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2379 lpStart = ClipData;
2380 lpData = lpNext;
2381 lpNext = lpData->NextData;
2383 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2385 lpData->PrevData->NextData = lpData->NextData;
2386 lpData->NextData->PrevData = lpData->PrevData;
2388 if (lpData == ClipData)
2389 ClipData = lpNext != lpData ? lpNext : NULL;
2391 X11DRV_CLIPBOARD_FreeData(lpData);
2392 HeapFree(GetProcessHeap(), 0, lpData);
2394 ClipDataCount--;
2396 } while (lpNext != lpStart);
2399 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2404 /**************************************************************************
2405 * X11DRV_SetClipboardData
2407 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2409 DWORD flags = 0;
2410 BOOL bResult = TRUE;
2412 /* If it's not owned, data can only be set if the format data is not already owned
2413 and its rendering is not delayed */
2414 if (!owner)
2416 CLIPBOARDINFO cbinfo;
2417 LPWINE_CLIPDATA lpRender;
2419 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2421 if ((!hData16 && !hData32) ||
2422 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2423 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2424 bResult = FALSE;
2425 else
2426 flags = CF_FLAG_UNOWNED;
2429 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags, NULL, TRUE);
2431 return bResult;
2435 /**************************************************************************
2436 * CountClipboardFormats
2438 INT X11DRV_CountClipboardFormats(void)
2440 CLIPBOARDINFO cbinfo;
2442 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2444 TRACE(" count=%d\n", ClipDataCount);
2446 return ClipDataCount;
2450 /**************************************************************************
2451 * X11DRV_EnumClipboardFormats
2453 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2455 CLIPBOARDINFO cbinfo;
2456 UINT wNextFormat = 0;
2458 TRACE("(%04X)\n", wFormat);
2460 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2462 if (!wFormat)
2464 if (ClipData)
2465 wNextFormat = ClipData->wFormatID;
2467 else
2469 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2471 if (lpData && lpData->NextData != ClipData)
2472 wNextFormat = lpData->NextData->wFormatID;
2475 return wNextFormat;
2479 /**************************************************************************
2480 * X11DRV_IsClipboardFormatAvailable
2482 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2484 BOOL bRet = FALSE;
2485 CLIPBOARDINFO cbinfo;
2487 TRACE("(%04X)\n", wFormat);
2489 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2491 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2492 bRet = TRUE;
2494 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2496 return bRet;
2500 /**************************************************************************
2501 * GetClipboardData (USER.142)
2503 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2505 CLIPBOARDINFO cbinfo;
2506 LPWINE_CLIPDATA lpRender;
2508 TRACE("(%04X)\n", wFormat);
2510 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2512 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2514 if ( !lpRender->hData32 )
2515 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2517 /* Convert between 32 -> 16 bit data, if necessary */
2518 if (lpRender->hData32 && !lpRender->hData16)
2520 int size;
2522 if (lpRender->wFormatID == CF_METAFILEPICT)
2523 size = sizeof(METAFILEPICT16);
2524 else
2525 size = GlobalSize(lpRender->hData32);
2527 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2529 if (!lpRender->hData16)
2530 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2531 else
2533 if (lpRender->wFormatID == CF_METAFILEPICT)
2535 FIXME("\timplement function CopyMetaFilePict32to16\n");
2536 FIXME("\tin the appropriate file.\n");
2537 #ifdef SOMEONE_IMPLEMENTED_ME
2538 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2539 GlobalLock(lpRender->hData32));
2540 #endif
2542 else
2544 memcpy(GlobalLock16(lpRender->hData16),
2545 GlobalLock(lpRender->hData32), size);
2548 GlobalUnlock16(lpRender->hData16);
2549 GlobalUnlock(lpRender->hData32);
2553 /* Convert between 32 -> 16 bit data, if necessary */
2554 if (lpRender->hData16 && !lpRender->hData32)
2556 int size;
2558 if (lpRender->wFormatID == CF_METAFILEPICT)
2559 size = sizeof(METAFILEPICT16);
2560 else
2561 size = GlobalSize(lpRender->hData32);
2563 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2564 GMEM_DDESHARE, size);
2566 if (lpRender->wFormatID == CF_METAFILEPICT)
2568 FIXME("\timplement function CopyMetaFilePict16to32\n");
2569 FIXME("\tin the appropriate file.\n");
2570 #ifdef SOMEONE_IMPLEMENTED_ME
2571 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2572 GlobalLock(lpRender->hData16));
2573 #endif
2575 else
2577 memcpy(GlobalLock(lpRender->hData32),
2578 GlobalLock16(lpRender->hData16), size);
2581 GlobalUnlock(lpRender->hData32);
2582 GlobalUnlock16(lpRender->hData16);
2585 if (phData16)
2586 *phData16 = lpRender->hData16;
2588 if (phData32)
2589 *phData32 = lpRender->hData32;
2591 TRACE(" returning hData16(%04x) hData32(%p) (type %d)\n",
2592 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2594 return lpRender->hData16 || lpRender->hData32;
2597 return 0;
2601 /**************************************************************************
2602 * ResetSelectionOwner
2604 * Called when the thread owning the selection is destroyed and we need to
2605 * preserve the selection ownership. We look for another top level window
2606 * in this process and send it a message to acquire the selection.
2608 void X11DRV_ResetSelectionOwner(void)
2610 HWND hwnd;
2611 DWORD procid;
2613 TRACE("\n");
2615 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2616 return;
2618 selectionAcquired = S_NOSELECTION;
2619 selectionWindow = 0;
2621 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2624 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2626 if (GetCurrentProcessId() == procid)
2628 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2629 return;
2632 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2634 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2636 X11DRV_CLIPBOARD_ReleaseOwnership();
2637 X11DRV_EmptyClipboard(FALSE);
2641 /**************************************************************************
2642 * X11DRV_CLIPBOARD_SynthesizeData
2644 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2646 BOOL bsyn = TRUE;
2647 LPWINE_CLIPDATA lpSource = NULL;
2649 TRACE(" %d\n", wFormatID);
2651 /* Don't need to synthesize if it already exists */
2652 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2653 return TRUE;
2655 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2657 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2658 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2659 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2660 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2661 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2662 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2664 else if (wFormatID == CF_ENHMETAFILE)
2666 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2667 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2669 else if (wFormatID == CF_METAFILEPICT)
2671 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2672 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2674 else if (wFormatID == CF_DIB)
2676 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2677 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2679 else if (wFormatID == CF_BITMAP)
2681 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2682 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2685 if (bsyn)
2686 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2688 return bsyn;
2693 /**************************************************************************
2694 * X11DRV_EndClipboardUpdate
2695 * TODO:
2696 * Add locale if it hasn't already been added
2698 void X11DRV_EndClipboardUpdate(void)
2700 INT count = ClipDataCount;
2702 /* Do Unicode <-> Text <-> OEM mapping */
2703 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2704 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2705 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2707 /* Enhmetafile <-> MetafilePict mapping */
2708 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2709 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2711 /* DIB <-> Bitmap mapping */
2712 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2713 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2715 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2719 /***********************************************************************
2720 * X11DRV_SelectionRequest_TARGETS
2721 * Service a TARGETS selection request event
2723 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2724 Atom target, Atom rprop )
2726 UINT i;
2727 Atom* targets;
2728 ULONG cTargets;
2729 LPWINE_CLIPFORMAT lpFormats;
2730 LPWINE_CLIPDATA lpData;
2732 /* Create X atoms for any clipboard types which don't have atoms yet.
2733 * This avoids sending bogus zero atoms.
2734 * Without this, copying might not have access to all clipboard types.
2735 * FIXME: is it safe to call this here?
2737 intern_atoms();
2740 * Count the number of items we wish to expose as selection targets.
2742 cTargets = 1; /* Include TARGETS */
2744 if (!(lpData = ClipData)) return None;
2748 lpFormats = ClipFormats;
2750 while (lpFormats)
2752 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2753 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2754 cTargets++;
2756 lpFormats = lpFormats->NextFormat;
2759 lpData = lpData->NextData;
2761 while (lpData != ClipData);
2763 TRACE(" found %d formats\n", cTargets);
2765 /* Allocate temp buffer */
2766 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2767 if(targets == NULL)
2768 return None;
2770 i = 0;
2771 lpData = ClipData;
2772 targets[i++] = x11drv_atom(TARGETS);
2776 lpFormats = ClipFormats;
2778 while (lpFormats)
2780 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2781 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2782 targets[i++] = lpFormats->drvData;
2784 lpFormats = lpFormats->NextFormat;
2787 lpData = lpData->NextData;
2789 while (lpData != ClipData);
2791 wine_tsx11_lock();
2793 if (TRACE_ON(clipboard))
2795 unsigned int i;
2796 for ( i = 0; i < cTargets; i++)
2798 char *itemFmtName = XGetAtomName(display, targets[i]);
2799 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2800 XFree(itemFmtName);
2804 /* We may want to consider setting the type to xaTargets instead,
2805 * in case some apps expect this instead of XA_ATOM */
2806 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2807 PropModeReplace, (unsigned char *)targets, cTargets);
2808 wine_tsx11_unlock();
2810 HeapFree(GetProcessHeap(), 0, targets);
2812 return rprop;
2816 /***********************************************************************
2817 * X11DRV_SelectionRequest_MULTIPLE
2818 * Service a MULTIPLE selection request event
2819 * rprop contains a list of (target,property) atom pairs.
2820 * The first atom names a target and the second names a property.
2821 * The effect is as if we have received a sequence of SelectionRequest events
2822 * (one for each atom pair) except that:
2823 * 1. We reply with a SelectionNotify only when all the requested conversions
2824 * have been performed.
2825 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2826 * we replace the atom in the property by None.
2828 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2830 Display *display = pevent->display;
2831 Atom rprop;
2832 Atom atype=AnyPropertyType;
2833 int aformat;
2834 unsigned long remain;
2835 Atom* targetPropList=NULL;
2836 unsigned long cTargetPropList = 0;
2838 /* If the specified property is None the requestor is an obsolete client.
2839 * We support these by using the specified target atom as the reply property.
2841 rprop = pevent->property;
2842 if( rprop == None )
2843 rprop = pevent->target;
2844 if (!rprop)
2845 return 0;
2847 /* Read the MULTIPLE property contents. This should contain a list of
2848 * (target,property) atom pairs.
2850 wine_tsx11_lock();
2851 if(XGetWindowProperty(display, pevent->requestor, rprop,
2852 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2853 &cTargetPropList, &remain,
2854 (unsigned char**)&targetPropList) != Success)
2856 wine_tsx11_unlock();
2857 TRACE("\tCouldn't read MULTIPLE property\n");
2859 else
2861 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2862 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2863 wine_tsx11_unlock();
2866 * Make sure we got what we expect.
2867 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2868 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2869 * However some X apps(such as XPaint) are not compliant with this and return
2870 * a user defined atom in atype when XGetWindowProperty is called.
2871 * The data *is* an atom pair but is not denoted as such.
2873 if(aformat == 32 /* atype == xAtomPair */ )
2875 unsigned int i;
2877 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2878 * for each (target,property) pair */
2880 for (i = 0; i < cTargetPropList; i+=2)
2882 XSelectionRequestEvent event;
2884 if (TRACE_ON(clipboard))
2886 char *targetName, *propName;
2887 wine_tsx11_lock();
2888 targetName = XGetAtomName(display, targetPropList[i]);
2889 propName = XGetAtomName(display, targetPropList[i+1]);
2890 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
2891 i/2, targetName, propName);
2892 XFree(targetName);
2893 XFree(propName);
2894 wine_tsx11_unlock();
2897 /* We must have a non "None" property to service a MULTIPLE target atom */
2898 if ( !targetPropList[i+1] )
2900 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
2901 continue;
2904 /* Set up an XSelectionRequestEvent for this (target,property) pair */
2905 event = *pevent;
2906 event.target = targetPropList[i];
2907 event.property = targetPropList[i+1];
2909 /* Fire a SelectionRequest, informing the handler that we are processing
2910 * a MULTIPLE selection request event.
2912 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
2916 /* Free the list of targets/properties */
2917 wine_tsx11_lock();
2918 XFree(targetPropList);
2919 wine_tsx11_unlock();
2922 return rprop;
2926 /***********************************************************************
2927 * X11DRV_HandleSelectionRequest
2928 * Process an event selection request event.
2929 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
2930 * recursively while servicing a "MULTIPLE" selection target.
2932 * Note: We only receive this event when WINE owns the X selection
2934 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
2936 Display *display = event->display;
2937 XSelectionEvent result;
2938 Atom rprop = None;
2939 Window request = event->requestor;
2941 TRACE("\n");
2944 * We can only handle the selection request if :
2945 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
2946 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
2947 * since this has been already done.
2949 if ( !bIsMultiple )
2951 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
2952 goto END;
2955 /* If the specified property is None the requestor is an obsolete client.
2956 * We support these by using the specified target atom as the reply property.
2958 rprop = event->property;
2959 if( rprop == None )
2960 rprop = event->target;
2962 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
2964 /* TARGETS selection request */
2965 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
2967 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
2969 /* MULTIPLE selection request */
2970 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
2972 else
2974 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
2976 if (lpFormat && lpFormat->lpDrvExportFunc)
2978 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
2980 if (lpData)
2982 unsigned char* lpClipData;
2983 DWORD cBytes;
2984 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
2985 rprop, lpData, &cBytes);
2987 if (hClipData && (lpClipData = GlobalLock(hClipData)))
2989 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
2991 wine_tsx11_lock();
2992 XChangeProperty(display, request, rprop, event->target,
2993 8, PropModeReplace, lpClipData, cBytes);
2994 wine_tsx11_unlock();
2996 GlobalUnlock(hClipData);
2997 GlobalFree(hClipData);
3003 END:
3004 /* reply to sender
3005 * SelectionNotify should be sent only at the end of a MULTIPLE request
3007 if ( !bIsMultiple )
3009 result.type = SelectionNotify;
3010 result.display = display;
3011 result.requestor = request;
3012 result.selection = event->selection;
3013 result.property = rprop;
3014 result.target = event->target;
3015 result.time = event->time;
3016 TRACE("Sending SelectionNotify event...\n");
3017 wine_tsx11_lock();
3018 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3019 wine_tsx11_unlock();
3024 /***********************************************************************
3025 * X11DRV_SelectionRequest
3027 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3029 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3033 /***********************************************************************
3034 * X11DRV_SelectionClear
3036 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3038 XSelectionClearEvent *event = &xev->xselectionclear;
3039 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3040 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3041 event->window, hWnd, event->time );