push b59ba84f7e04af9ef068bd4c6e96701941f0256e
[wine/hacks.git] / dlls / winex11.drv / clipboard.c
blob453746f3a25b29520154fd8e140d8b599f5f3a61
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 <time.h>
76 #include <assert.h>
78 #include "windef.h"
79 #include "winbase.h"
80 #include "wine/wingdi16.h"
81 #include "x11drv.h"
82 #include "wine/debug.h"
83 #include "wine/unicode.h"
84 #include "wine/server.h"
86 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
88 #define HGDIOBJ_32(handle16) ((HGDIOBJ)(ULONG_PTR)(handle16))
90 /* Maximum wait time for selection notify */
91 #define SELECTION_RETRIES 500 /* wait for .1 seconds */
92 #define SELECTION_WAIT 1000 /* us */
93 /* Minimum seconds that must lapse between owner queries */
94 #define OWNERQUERYLAPSETIME 1
96 /* Selection masks */
97 #define S_NOSELECTION 0
98 #define S_PRIMARY 1
99 #define S_CLIPBOARD 2
101 typedef struct
103 HWND hWndOpen;
104 HWND hWndOwner;
105 HWND hWndViewer;
106 UINT seqno;
107 UINT flags;
108 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
110 struct tagWINE_CLIPDATA; /* Forward */
112 typedef HANDLE (*DRVEXPORTFUNC)(Window requestor, Atom aTarget, Atom rprop,
113 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
114 typedef HANDLE (*DRVIMPORTFUNC)(Window w, Atom prop);
116 typedef struct tagWINE_CLIPFORMAT {
117 UINT wFormatID;
118 LPCWSTR Name;
119 UINT drvData;
120 UINT wFlags;
121 DRVIMPORTFUNC lpDrvImportFunc;
122 DRVEXPORTFUNC lpDrvExportFunc;
123 struct tagWINE_CLIPFORMAT *PrevFormat;
124 struct tagWINE_CLIPFORMAT *NextFormat;
125 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
127 typedef struct tagWINE_CLIPDATA {
128 UINT wFormatID;
129 HANDLE16 hData16;
130 HANDLE hData32;
131 UINT wFlags;
132 UINT drvData;
133 LPWINE_CLIPFORMAT lpFormat;
134 struct tagWINE_CLIPDATA *PrevData;
135 struct tagWINE_CLIPDATA *NextData;
136 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
138 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
139 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
140 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
141 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
143 static int selectionAcquired = 0; /* Contains the current selection masks */
144 static Window selectionWindow = None; /* The top level X window which owns the selection */
145 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
147 void X11DRV_EmptyClipboard(BOOL keepunowned);
148 void X11DRV_EndClipboardUpdate(void);
149 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Window w, Atom prop);
150 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
157 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
158 static HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget,
159 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
160 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget,
161 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
162 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget,
163 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
164 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget,
165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
166 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
167 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID);
168 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
169 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
170 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo);
171 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(LPWINE_CLIPDATA lpData);
172 static BOOL X11DRV_CLIPBOARD_ReadProperty(Window w, Atom prop,
173 unsigned char** data, unsigned long* datasize);
174 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData);
175 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
176 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
177 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData);
178 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(void);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(void);
180 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
182 /* Clipboard formats
183 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
184 * declared in clipboard.h
186 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
187 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
188 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
189 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
190 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
191 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
192 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
193 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
194 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
195 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
196 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
197 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
198 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
199 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
200 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
201 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
202 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
203 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
204 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
205 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
206 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
207 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
208 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
210 static WINE_CLIPFORMAT ClipFormats[] =
212 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
213 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
215 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
216 NULL, &ClipFormats[0], &ClipFormats[2]},
218 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
219 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
221 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
222 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
224 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
225 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
227 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
228 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
230 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
231 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
233 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
234 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
236 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
237 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
239 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
240 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
242 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
243 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
245 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
246 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
248 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
249 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
251 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
252 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
253 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
255 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
256 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
258 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
259 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
261 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
262 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
264 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
265 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
267 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
268 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
270 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
271 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
273 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
274 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
276 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
277 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
279 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
280 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], NULL}
283 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
285 /* Maps X properties to Windows formats */
286 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
287 static const WCHAR wszGIF[] = {'G','I','F',0};
288 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
289 static const struct
291 LPCWSTR lpszFormat;
292 UINT prop;
293 } PropertyFormatMap[] =
295 { wszRichTextFormat, XATOM_text_rtf },
296 { wszRichTextFormat, XATOM_text_richtext },
297 { wszGIF, XATOM_image_gif },
298 { wszHTMLFormat, XATOM_text_html },
303 * Cached clipboard data.
305 static LPWINE_CLIPDATA ClipData = NULL;
306 static UINT ClipDataCount = 0;
309 * Clipboard sequence number
311 static UINT wSeqNo = 0;
313 /**************************************************************************
314 * Internal Clipboard implementation methods
315 **************************************************************************/
317 static Window thread_selection_wnd(void)
319 Window w = x11drv_thread_data()->selection_wnd;
321 if (!w)
323 XSetWindowAttributes attr;
325 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
326 ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
328 wine_tsx11_lock();
329 w = XCreateWindow(thread_display(), root_window, 0, 0, 1, 1, 0, screen_depth,
330 InputOutput, CopyFromParent, CWEventMask, &attr);
331 wine_tsx11_unlock();
333 if (w)
334 x11drv_thread_data()->selection_wnd = w;
335 else
336 FIXME("Failed to create window. Fetching selection data will fail.\n");
339 return w;
342 /**************************************************************************
343 * X11DRV_InitClipboard
345 void X11DRV_InitClipboard(void)
347 UINT i;
349 /* Register known mapping between window formats and X properties */
350 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
351 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
355 /**************************************************************************
356 * intern_atoms
358 * Intern atoms for formats that don't have one yet.
360 static void intern_atoms(void)
362 LPWINE_CLIPFORMAT format;
363 int i, count, len;
364 char **names;
365 Atom *atoms;
367 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
368 if (!format->drvData) count++;
369 if (!count) return;
371 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
372 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
374 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
375 if (!format->drvData) {
376 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
377 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
378 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
382 wine_tsx11_lock();
383 XInternAtoms( thread_display(), names, count, False, atoms );
384 wine_tsx11_unlock();
386 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
387 if (!format->drvData) {
388 HeapFree(GetProcessHeap(), 0, names[i]);
389 format->drvData = atoms[i++];
393 HeapFree( GetProcessHeap(), 0, names );
394 HeapFree( GetProcessHeap(), 0, atoms );
398 /**************************************************************************
399 * register_format
401 * Register a custom X clipboard format.
403 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
405 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
407 TRACE("%s\n", debugstr_w(FormatName));
409 /* walk format chain to see if it's already registered */
410 while (lpFormat)
412 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
413 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
414 return lpFormat;
415 lpFormat = lpFormat->NextFormat;
418 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
422 /**************************************************************************
423 * X11DRV_CLIPBOARD_LookupFormat
425 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
427 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
429 while(lpFormat)
431 if (lpFormat->wFormatID == wID)
432 break;
434 lpFormat = lpFormat->NextFormat;
436 if (lpFormat && !lpFormat->drvData) intern_atoms();
437 return lpFormat;
441 /**************************************************************************
442 * X11DRV_CLIPBOARD_LookupProperty
444 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
446 for (;;)
448 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
449 BOOL need_intern = FALSE;
451 if (current)
452 lpFormat = current->NextFormat;
454 while(lpFormat)
456 if (lpFormat->drvData == drvData) return lpFormat;
457 if (!lpFormat->drvData) need_intern = TRUE;
458 lpFormat = lpFormat->NextFormat;
460 if (!need_intern) return NULL;
461 intern_atoms();
462 /* restart the search for the new atoms */
467 /**************************************************************************
468 * X11DRV_CLIPBOARD_LookupData
470 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
472 LPWINE_CLIPDATA lpData = ClipData;
474 if (lpData)
478 if (lpData->wFormatID == wID)
479 break;
481 lpData = lpData->NextData;
483 while(lpData != ClipData);
485 if (lpData->wFormatID != wID)
486 lpData = NULL;
489 return lpData;
493 /**************************************************************************
494 * InsertClipboardFormat
496 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
498 LPWINE_CLIPFORMAT lpFormat;
499 LPWINE_CLIPFORMAT lpNewFormat;
500 LPWSTR new_name;
502 /* allocate storage for new format entry */
503 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
505 if(lpNewFormat == NULL)
507 WARN("No more memory for a new format!\n");
508 return NULL;
511 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
513 WARN("No more memory for the new format name!\n");
514 HeapFree(GetProcessHeap(), 0, lpNewFormat);
515 return NULL;
518 lpNewFormat->Name = strcpyW(new_name, FormatName);
519 lpNewFormat->wFlags = 0;
520 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
521 lpNewFormat->drvData = prop;
522 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
523 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
525 /* Link Format */
526 lpFormat = ClipFormats;
528 while(lpFormat->NextFormat) /* Move to last entry */
529 lpFormat = lpFormat->NextFormat;
531 lpNewFormat->NextFormat = NULL;
532 lpFormat->NextFormat = lpNewFormat;
533 lpNewFormat->PrevFormat = lpFormat;
535 TRACE("Registering format(%d): %s drvData %d\n",
536 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
538 return lpNewFormat;
544 /**************************************************************************
545 * X11DRV_CLIPBOARD_GetClipboardInfo
547 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
549 BOOL bRet = FALSE;
551 SERVER_START_REQ( set_clipboard_info )
553 req->flags = 0;
555 if (wine_server_call_err( req ))
557 ERR("Failed to get clipboard owner.\n");
559 else
561 cbInfo->hWndOpen = reply->old_clipboard;
562 cbInfo->hWndOwner = reply->old_owner;
563 cbInfo->hWndViewer = reply->old_viewer;
564 cbInfo->seqno = reply->seqno;
565 cbInfo->flags = reply->flags;
567 bRet = TRUE;
570 SERVER_END_REQ;
572 return bRet;
576 /**************************************************************************
577 * X11DRV_CLIPBOARD_ReleaseOwnership
579 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
581 BOOL bRet = FALSE;
583 SERVER_START_REQ( set_clipboard_info )
585 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
587 if (wine_server_call_err( req ))
589 ERR("Failed to set clipboard.\n");
591 else
593 bRet = TRUE;
596 SERVER_END_REQ;
598 return bRet;
603 /**************************************************************************
604 * X11DRV_CLIPBOARD_InsertClipboardData
606 * Caller *must* have the clipboard open and be the owner.
608 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
609 HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
611 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
613 TRACE("format=%d lpData=%p hData16=%08x hData32=%p flags=0x%08x lpFormat=%p override=%d\n",
614 wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
616 if (lpData && !override)
617 return TRUE;
619 if (lpData)
621 X11DRV_CLIPBOARD_FreeData(lpData);
623 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
624 lpData->hData32 = hData32;
626 else
628 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
630 lpData->wFormatID = wFormatID;
631 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
632 lpData->hData32 = hData32;
633 lpData->lpFormat = lpFormat;
634 lpData->drvData = 0;
636 if (ClipData)
638 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
640 lpData->PrevData = lpPrevData;
641 lpData->NextData = ClipData;
643 lpPrevData->NextData = lpData;
644 ClipData->PrevData = lpData;
646 else
648 lpData->NextData = lpData;
649 lpData->PrevData = lpData;
650 ClipData = lpData;
653 ClipDataCount++;
656 lpData->wFlags = flags;
658 return TRUE;
662 /**************************************************************************
663 * X11DRV_CLIPBOARD_FreeData
665 * Free clipboard data handle.
667 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
669 TRACE("%d\n", lpData->wFormatID);
671 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
672 lpData->wFormatID <= CF_GDIOBJLAST) ||
673 lpData->wFormatID == CF_BITMAP ||
674 lpData->wFormatID == CF_DIB ||
675 lpData->wFormatID == CF_PALETTE)
677 if (lpData->hData32)
678 DeleteObject(lpData->hData32);
680 if (lpData->hData16)
681 DeleteObject(HGDIOBJ_32(lpData->hData16));
683 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
684 XFreePixmap(gdi_display, lpData->drvData);
686 else if (lpData->wFormatID == CF_METAFILEPICT)
688 if (lpData->hData32)
690 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
691 GlobalFree(lpData->hData32);
693 if (lpData->hData16)
694 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
695 and a shallow copy is enough to share a METAFILEPICT
696 structure between 16bit and 32bit clipboards. The MetaFile
697 should of course only be deleted once. */
698 GlobalFree16(lpData->hData16);
701 if (lpData->hData16)
703 METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
705 if (lpMetaPict)
707 /* To delete 16-bit meta file, we just need to free the associated
708 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
709 GlobalFree16(lpMetaPict->hMF);
710 lpMetaPict->hMF = 0;
713 GlobalFree16(lpData->hData16);
716 else if (lpData->wFormatID == CF_ENHMETAFILE)
718 if (lpData->hData32)
719 DeleteEnhMetaFile(lpData->hData32);
721 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
722 lpData->wFormatID > CF_PRIVATELAST)
724 if (lpData->hData32)
725 GlobalFree(lpData->hData32);
727 if (lpData->hData16)
728 GlobalFree16(lpData->hData16);
731 lpData->hData16 = 0;
732 lpData->hData32 = 0;
733 lpData->drvData = 0;
737 /**************************************************************************
738 * X11DRV_CLIPBOARD_UpdateCache
740 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
742 BOOL bret = TRUE;
744 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
746 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
748 ERR("Failed to retrieve clipboard information.\n");
749 bret = FALSE;
751 else if (wSeqNo < lpcbinfo->seqno)
753 X11DRV_EmptyClipboard(TRUE);
755 if (X11DRV_CLIPBOARD_QueryAvailableData(lpcbinfo) < 0)
757 ERR("Failed to cache clipboard data owned by another process.\n");
758 bret = FALSE;
760 else
762 X11DRV_EndClipboardUpdate();
765 wSeqNo = lpcbinfo->seqno;
769 return bret;
773 /**************************************************************************
774 * X11DRV_CLIPBOARD_RenderFormat
776 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData)
778 BOOL bret = TRUE;
780 TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
781 lpData->wFormatID, lpData->hData32, lpData->hData16);
783 if (lpData->hData32 || lpData->hData16)
784 return bret; /* Already rendered */
786 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
787 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(lpData);
788 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
790 if (!X11DRV_CLIPBOARD_ReadSelectionData(lpData))
792 ERR("Failed to cache clipboard data owned by another process. Format=%d\n",
793 lpData->wFormatID);
794 bret = FALSE;
797 else
799 CLIPBOARDINFO cbInfo;
801 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
803 /* Send a WM_RENDERFORMAT message to notify the owner to render the
804 * data requested into the clipboard.
806 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
807 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
809 if (!lpData->hData32 && !lpData->hData16)
810 bret = FALSE;
812 else
814 ERR("hWndClipOwner is lost!\n");
815 bret = FALSE;
819 return bret;
823 /**************************************************************************
824 * CLIPBOARD_ConvertText
825 * Returns number of required/converted characters - not bytes!
827 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
828 WORD dst_fmt, void *dst, INT dst_size)
830 UINT cp;
832 if(src_fmt == CF_UNICODETEXT)
834 switch(dst_fmt)
836 case CF_TEXT:
837 cp = CP_ACP;
838 break;
839 case CF_OEMTEXT:
840 cp = CP_OEMCP;
841 break;
842 default:
843 return 0;
845 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
848 if(dst_fmt == CF_UNICODETEXT)
850 switch(src_fmt)
852 case CF_TEXT:
853 cp = CP_ACP;
854 break;
855 case CF_OEMTEXT:
856 cp = CP_OEMCP;
857 break;
858 default:
859 return 0;
861 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
864 if(!dst_size) return src_size;
866 if(dst_size > src_size) dst_size = src_size;
868 if(src_fmt == CF_TEXT )
869 CharToOemBuffA(src, dst, dst_size);
870 else
871 OemToCharBuffA(src, dst, dst_size);
873 return dst_size;
877 /**************************************************************************
878 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
880 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData)
882 BOOL bret = FALSE;
884 TRACE("\n");
886 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
888 UINT wFormatID = lpData->wFormatID;
890 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
891 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(wFormatID);
892 else
894 switch (wFormatID)
896 case CF_DIB:
897 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB();
898 break;
900 case CF_BITMAP:
901 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap();
902 break;
904 case CF_ENHMETAFILE:
905 case CF_METAFILEPICT:
906 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
907 break;
909 default:
910 FIXME("Called to synthesize unknown format\n");
911 break;
915 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
918 return bret;
922 /**************************************************************************
923 * X11DRV_CLIPBOARD_RenderSynthesizedText
925 * Renders synthesized text
927 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID)
929 LPCSTR lpstrS;
930 LPSTR lpstrT;
931 HANDLE hData32;
932 INT src_chars, dst_chars, alloc_size;
933 LPWINE_CLIPDATA lpSource = NULL;
935 TRACE(" %d\n", wFormatID);
937 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
938 lpSource->hData32)
939 return TRUE;
941 /* Look for rendered source or non-synthesized source */
942 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
943 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
945 TRACE("UNICODETEXT -> %d\n", wFormatID);
947 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
948 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
950 TRACE("TEXT -> %d\n", wFormatID);
952 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
953 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
955 TRACE("OEMTEXT -> %d\n", wFormatID);
958 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
959 !lpSource->hData32))
960 return FALSE;
962 /* Ask the clipboard owner to render the source text if necessary */
963 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(lpSource))
964 return FALSE;
966 if (lpSource->hData32)
968 lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
970 else
972 lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
975 if (!lpstrS)
976 return FALSE;
978 /* Text always NULL terminated */
979 if(lpSource->wFormatID == CF_UNICODETEXT)
980 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
981 else
982 src_chars = strlen(lpstrS) + 1;
984 /* Calculate number of characters in the destination buffer */
985 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
986 src_chars, wFormatID, NULL, 0);
988 if (!dst_chars)
989 return FALSE;
991 TRACE("Converting from '%d' to '%d', %i chars\n",
992 lpSource->wFormatID, wFormatID, src_chars);
994 /* Convert characters to bytes */
995 if(wFormatID == CF_UNICODETEXT)
996 alloc_size = dst_chars * sizeof(WCHAR);
997 else
998 alloc_size = dst_chars;
1000 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1001 GMEM_DDESHARE, alloc_size);
1003 lpstrT = (LPSTR)GlobalLock(hData32);
1005 if (lpstrT)
1007 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1008 wFormatID, lpstrT, dst_chars);
1009 GlobalUnlock(hData32);
1012 /* Unlock source */
1013 if (lpSource->hData32)
1014 GlobalUnlock(lpSource->hData32);
1015 else
1016 GlobalUnlock16(lpSource->hData16);
1018 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1022 /**************************************************************************
1023 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1025 * Renders synthesized DIB
1027 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(void)
1029 BOOL bret = FALSE;
1030 LPWINE_CLIPDATA lpSource = NULL;
1032 TRACE("\n");
1034 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1036 bret = TRUE;
1038 /* If we have a bitmap and it's not synthesized or it has been rendered */
1039 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1040 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1042 /* Render source if required */
1043 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1045 HDC hdc;
1046 HGLOBAL hData32;
1048 hdc = GetDC(NULL);
1049 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1050 ReleaseDC(NULL, hdc);
1052 if (hData32)
1054 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1055 bret = TRUE;
1060 return bret;
1064 /**************************************************************************
1065 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1067 * Renders synthesized bitmap
1069 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(void)
1071 BOOL bret = FALSE;
1072 LPWINE_CLIPDATA lpSource = NULL;
1074 TRACE("\n");
1076 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1078 bret = TRUE;
1080 /* If we have a dib and it's not synthesized or it has been rendered */
1081 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1082 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1084 /* Render source if required */
1085 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1087 HDC hdc;
1088 HBITMAP hData32;
1089 unsigned int offset;
1090 LPBITMAPINFOHEADER lpbmih;
1092 hdc = GetDC(NULL);
1093 lpbmih = (LPBITMAPINFOHEADER) GlobalLock(lpSource->hData32);
1095 offset = sizeof(BITMAPINFOHEADER)
1096 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1097 (1 << lpbmih->biBitCount)) : 0);
1099 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1100 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1102 GlobalUnlock(lpSource->hData32);
1103 ReleaseDC(NULL, hdc);
1105 if (hData32)
1107 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1108 bret = TRUE;
1113 return bret;
1117 /**************************************************************************
1118 * X11DRV_CLIPBOARD_ImportXAString
1120 * Import XA_STRING, converting the string to CF_TEXT.
1122 HANDLE X11DRV_CLIPBOARD_ImportXAString(Window w, Atom prop)
1124 LPBYTE lpdata;
1125 unsigned long cbytes;
1126 LPSTR lpstr;
1127 unsigned long i, inlcount = 0;
1128 HANDLE hText = 0;
1130 if (!X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1131 return 0;
1133 for (i = 0; i <= cbytes; i++)
1135 if (lpdata[i] == '\n')
1136 inlcount++;
1139 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1141 lpstr = GlobalLock(hText);
1143 for (i = 0, inlcount = 0; i <= cbytes; i++)
1145 if (lpdata[i] == '\n')
1146 lpstr[inlcount++] = '\r';
1148 lpstr[inlcount++] = lpdata[i];
1151 GlobalUnlock(hText);
1154 /* Free the retrieved property data */
1155 HeapFree(GetProcessHeap(), 0, lpdata);
1157 return hText;
1161 /**************************************************************************
1162 * X11DRV_CLIPBOARD_ImportUTF8
1164 * Import XA_STRING, converting the string to CF_UNICODE.
1166 HANDLE X11DRV_CLIPBOARD_ImportUTF8(Window w, Atom prop)
1168 LPBYTE lpdata;
1169 unsigned long cbytes;
1170 LPSTR lpstr;
1171 unsigned long i, inlcount = 0;
1172 HANDLE hUnicodeText = 0;
1174 if (!X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1175 return 0;
1177 for (i = 0; i <= cbytes; i++)
1179 if (lpdata[i] == '\n')
1180 inlcount++;
1183 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1185 UINT count;
1187 for (i = 0, inlcount = 0; i <= cbytes; i++)
1189 if (lpdata[i] == '\n')
1190 lpstr[inlcount++] = '\r';
1192 lpstr[inlcount++] = lpdata[i];
1195 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1196 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1198 if (hUnicodeText)
1200 WCHAR *textW = GlobalLock(hUnicodeText);
1201 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1202 GlobalUnlock(hUnicodeText);
1205 HeapFree(GetProcessHeap(), 0, lpstr);
1208 /* Free the retrieved property data */
1209 HeapFree(GetProcessHeap(), 0, lpdata);
1211 return hUnicodeText;
1215 /**************************************************************************
1216 * X11DRV_CLIPBOARD_ImportCompoundText
1218 * Import COMPOUND_TEXT to CF_UNICODE
1220 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Window w, Atom prop)
1222 Display *display = thread_display();
1223 int i, j;
1224 char** srcstr;
1225 int count, lcount;
1226 int srclen, destlen;
1227 HANDLE hUnicodeText;
1228 XTextProperty txtprop;
1230 wine_tsx11_lock();
1231 if (!XGetTextProperty(display, w, &txtprop, prop))
1233 wine_tsx11_unlock();
1234 return 0;
1237 XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1238 wine_tsx11_unlock();
1240 TRACE("Importing %d line(s)\n", count);
1242 /* Compute number of lines */
1243 srclen = strlen(srcstr[0]);
1244 for (i = 0, lcount = 0; i <= srclen; i++)
1246 if (srcstr[0][i] == '\n')
1247 lcount++;
1250 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1252 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1254 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1256 WCHAR *deststr = GlobalLock(hUnicodeText);
1257 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1259 if (lcount)
1261 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1263 deststr[j] = deststr[i];
1265 if (deststr[i] == '\n')
1266 deststr[--j] = '\r';
1270 GlobalUnlock(hUnicodeText);
1273 wine_tsx11_lock();
1274 XFreeStringList(srcstr);
1275 XFree(txtprop.value);
1276 wine_tsx11_unlock();
1278 return hUnicodeText;
1282 /**************************************************************************
1283 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1285 * Import XA_PIXMAP, converting the image to CF_DIB.
1287 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Window w, Atom prop)
1289 HWND hwnd;
1290 HDC hdc;
1291 LPBYTE lpdata;
1292 unsigned long cbytes;
1293 Pixmap *pPixmap;
1294 HANDLE hClipData = 0;
1296 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1298 pPixmap = (Pixmap *) lpdata;
1300 hwnd = GetOpenClipboardWindow();
1301 hdc = GetDC(hwnd);
1303 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1304 ReleaseDC(hwnd, hdc);
1306 /* Free the retrieved property data */
1307 HeapFree(GetProcessHeap(), 0, lpdata);
1310 return hClipData;
1314 /**************************************************************************
1315 * X11DRV_CLIPBOARD_ImportMetaFilePict
1317 * Import MetaFilePict.
1319 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Window w, Atom prop)
1321 LPBYTE lpdata;
1322 unsigned long cbytes;
1323 HANDLE hClipData = 0;
1325 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1327 if (cbytes)
1328 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1330 /* Free the retrieved property data */
1331 HeapFree(GetProcessHeap(), 0, lpdata);
1334 return hClipData;
1338 /**************************************************************************
1339 * X11DRV_ImportEnhMetaFile
1341 * Import EnhMetaFile.
1343 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Window w, Atom prop)
1345 LPBYTE lpdata;
1346 unsigned long cbytes;
1347 HANDLE hClipData = 0;
1349 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1351 if (cbytes)
1352 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1354 /* Free the retrieved property data */
1355 HeapFree(GetProcessHeap(), 0, lpdata);
1358 return hClipData;
1362 /**************************************************************************
1363 * X11DRV_ImportClipbordaData
1365 * Generic import clipboard data routine.
1367 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Window w, Atom prop)
1369 LPVOID lpClipData;
1370 LPBYTE lpdata;
1371 unsigned long cbytes;
1372 HANDLE hClipData = 0;
1374 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1376 if (cbytes)
1378 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1379 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1380 if (hClipData == 0)
1381 return NULL;
1383 if ((lpClipData = GlobalLock(hClipData)))
1385 memcpy(lpClipData, lpdata, cbytes);
1386 GlobalUnlock(hClipData);
1388 else
1390 GlobalFree(hClipData);
1391 hClipData = 0;
1395 /* Free the retrieved property data */
1396 HeapFree(GetProcessHeap(), 0, lpdata);
1399 return hClipData;
1403 /**************************************************************************
1404 X11DRV_CLIPBOARD_ExportClipboardData
1406 * Generic export clipboard data routine.
1408 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
1409 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1411 LPVOID lpClipData;
1412 UINT datasize = 0;
1413 HANDLE hClipData = 0;
1415 *lpBytes = 0; /* Assume failure */
1417 if (!X11DRV_CLIPBOARD_RenderFormat(lpData))
1418 ERR("Failed to export %d format\n", lpData->wFormatID);
1419 else
1421 datasize = GlobalSize(lpData->hData32);
1423 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1424 if (hClipData == 0) return NULL;
1426 if ((lpClipData = GlobalLock(hClipData)))
1428 LPVOID lpdata = GlobalLock(lpData->hData32);
1430 memcpy(lpClipData, lpdata, datasize);
1431 *lpBytes = datasize;
1433 GlobalUnlock(lpData->hData32);
1434 GlobalUnlock(hClipData);
1435 } else {
1436 GlobalFree(hClipData);
1437 hClipData = 0;
1441 return hClipData;
1445 /**************************************************************************
1446 * X11DRV_CLIPBOARD_ExportXAString
1448 * Export CF_TEXT converting the string to XA_STRING.
1449 * Helper function for X11DRV_CLIPBOARD_ExportString.
1451 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1453 UINT i, j;
1454 UINT size;
1455 LPSTR text, lpstr = NULL;
1457 *lpBytes = 0; /* Assume return has zero bytes */
1459 text = GlobalLock(lpData->hData32);
1460 size = strlen(text);
1462 /* remove carriage returns */
1463 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1464 if (lpstr == NULL)
1465 goto done;
1467 for (i = 0,j = 0; i < size && text[i]; i++)
1469 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1470 continue;
1471 lpstr[j++] = text[i];
1474 lpstr[j]='\0';
1475 *lpBytes = j; /* Number of bytes in string */
1477 done:
1478 HeapFree(GetProcessHeap(), 0, text);
1479 GlobalUnlock(lpData->hData32);
1481 return lpstr;
1485 /**************************************************************************
1486 * X11DRV_CLIPBOARD_ExportUTF8String
1488 * Export CF_UNICODE converting the string to UTF8.
1489 * Helper function for X11DRV_CLIPBOARD_ExportString.
1491 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1493 UINT i, j;
1494 UINT size;
1495 LPWSTR uni_text;
1496 LPSTR text, lpstr = NULL;
1498 *lpBytes = 0; /* Assume return has zero bytes */
1500 uni_text = GlobalLock(lpData->hData32);
1502 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1504 text = HeapAlloc(GetProcessHeap(), 0, size);
1505 if (!text)
1506 goto done;
1507 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1509 /* remove carriage returns */
1510 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1511 if (lpstr == NULL)
1512 goto done;
1514 for (i = 0,j = 0; i < size && text[i]; i++)
1516 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1517 continue;
1518 lpstr[j++] = text[i];
1520 lpstr[j]='\0';
1522 *lpBytes = j; /* Number of bytes in string */
1524 done:
1525 HeapFree(GetProcessHeap(), 0, text);
1526 GlobalUnlock(lpData->hData32);
1528 return lpstr;
1533 /**************************************************************************
1534 * X11DRV_CLIPBOARD_ExportCompoundText
1536 * Export CF_UNICODE to COMPOUND_TEXT
1537 * Helper function for X11DRV_CLIPBOARD_ExportString.
1539 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Window requestor, Atom aTarget, Atom rprop,
1540 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1542 Display *display = thread_display();
1543 char* lpstr = 0;
1544 XTextProperty prop;
1545 XICCEncodingStyle style;
1546 UINT i, j;
1547 UINT size;
1548 LPWSTR uni_text;
1550 uni_text = GlobalLock(lpData->hData32);
1552 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1553 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1554 if (!lpstr)
1555 return 0;
1557 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1559 /* remove carriage returns */
1560 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1562 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1563 continue;
1564 lpstr[j++] = lpstr[i];
1566 lpstr[j]='\0';
1568 GlobalUnlock(lpData->hData32);
1570 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1571 style = XCompoundTextStyle;
1572 else
1573 style = XStdICCTextStyle;
1575 /* Update the X property */
1576 wine_tsx11_lock();
1577 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1579 XSetTextProperty(display, requestor, &prop, rprop);
1580 XFree(prop.value);
1582 wine_tsx11_unlock();
1584 HeapFree(GetProcessHeap(), 0, lpstr);
1586 return 0;
1589 /**************************************************************************
1590 * X11DRV_CLIPBOARD_ExportString
1592 * Export string
1594 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget, Atom rprop,
1595 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1597 if (X11DRV_CLIPBOARD_RenderFormat(lpData))
1599 if (aTarget == XA_STRING)
1600 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1601 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1602 return X11DRV_CLIPBOARD_ExportCompoundText(requestor, aTarget,
1603 rprop, lpData, lpBytes);
1604 else
1606 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1607 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1610 else
1611 ERR("Failed to render %d format\n", lpData->wFormatID);
1613 return 0;
1617 /**************************************************************************
1618 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1620 * Export CF_DIB to XA_PIXMAP.
1622 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget, Atom rprop,
1623 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1625 HDC hdc;
1626 HANDLE hData;
1627 unsigned char* lpData;
1629 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1631 ERR("Failed to export %d format\n", lpdata->wFormatID);
1632 return 0;
1635 if (!lpdata->drvData) /* If not already rendered */
1637 /* For convert from packed DIB to Pixmap */
1638 hdc = GetDC(0);
1639 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1640 ReleaseDC(0, hdc);
1643 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1645 /* Wrap pixmap so we can return a handle */
1646 hData = GlobalAlloc(0, *lpBytes);
1647 lpData = GlobalLock(hData);
1648 memcpy(lpData, &lpdata->drvData, *lpBytes);
1649 GlobalUnlock(hData);
1651 return (HANDLE) hData;
1655 /**************************************************************************
1656 * X11DRV_CLIPBOARD_ExportMetaFilePict
1658 * Export MetaFilePict.
1660 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget, Atom rprop,
1661 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1663 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1665 ERR("Failed to export %d format\n", lpdata->wFormatID);
1666 return 0;
1669 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata->hData32,
1670 lpBytes, TRUE);
1674 /**************************************************************************
1675 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1677 * Export EnhMetaFile.
1679 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget, Atom rprop,
1680 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1682 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1684 ERR("Failed to export %d format\n", lpdata->wFormatID);
1685 return 0;
1688 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata->hData32,
1689 lpBytes, TRUE);
1693 /**************************************************************************
1694 * X11DRV_CLIPBOARD_QueryTargets
1696 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1697 Atom target, XEvent *xe)
1699 INT i;
1700 Bool res;
1702 wine_tsx11_lock();
1703 XConvertSelection(display, selection, target,
1704 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1705 wine_tsx11_unlock();
1708 * Wait until SelectionNotify is received
1710 for (i = 0; i < SELECTION_RETRIES; i++)
1712 wine_tsx11_lock();
1713 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1714 wine_tsx11_unlock();
1715 if (res && xe->xselection.selection == selection) break;
1717 usleep(SELECTION_WAIT);
1720 /* Verify that the selection returned a valid TARGETS property */
1721 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1723 /* Selection owner failed to respond or we missed the SelectionNotify */
1724 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1725 return FALSE;
1728 return TRUE;
1732 /**************************************************************************
1733 * X11DRV_CLIPBOARD_InsertSelectionProperties
1735 * Mark properties available for future retrieval.
1737 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1739 UINT i, nb_atoms = 0;
1740 Atom *atoms = NULL;
1742 /* Cache these formats in the clipboard cache */
1743 for (i = 0; i < count; i++)
1745 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1747 if (lpFormat)
1749 /* We found at least one Window's format that mapps to the property.
1750 * Continue looking for more.
1752 * If more than one property map to a Window's format then we use the first
1753 * one and ignore the rest.
1755 while (lpFormat)
1757 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1758 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1759 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1760 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1763 else
1765 /* add it to the list of atoms that we don't know about yet */
1766 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1767 (count - i) * sizeof(*atoms) );
1768 if (atoms) atoms[nb_atoms++] = properties[i];
1772 /* query all unknown atoms in one go */
1773 if (atoms)
1775 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1776 if (names)
1778 wine_tsx11_lock();
1779 /* FIXME: we're at the mercy of the app sending the event here.
1780 * Currently if they send a bogus atom, we will crash.
1781 * We should handle BadAtom errors gracefully in this call.
1783 XGetAtomNames( display, atoms, nb_atoms, names );
1784 wine_tsx11_unlock();
1785 for (i = 0; i < nb_atoms; i++)
1787 WINE_CLIPFORMAT *lpFormat;
1788 LPWSTR wname;
1789 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1790 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1791 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1793 lpFormat = register_format( wname, atoms[i] );
1794 HeapFree(GetProcessHeap(), 0, wname);
1795 if (!lpFormat)
1797 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1798 continue;
1800 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1801 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1802 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1804 wine_tsx11_lock();
1805 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1806 wine_tsx11_unlock();
1807 HeapFree( GetProcessHeap(), 0, names );
1809 HeapFree( GetProcessHeap(), 0, atoms );
1814 /**************************************************************************
1815 * X11DRV_CLIPBOARD_QueryAvailableData
1817 * Caches the list of data formats available from the current selection.
1818 * This queries the selection owner for the TARGETS property and saves all
1819 * reported property types.
1821 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo)
1823 Display *display = thread_display();
1824 XEvent xe;
1825 Atom atype=AnyPropertyType;
1826 int aformat;
1827 unsigned long remain;
1828 Atom* targetList=NULL;
1829 Window w;
1830 unsigned long cSelectionTargets = 0;
1832 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1834 ERR("Received request to cache selection but process is owner=(%08x)\n",
1835 (unsigned) selectionWindow);
1836 return -1; /* Prevent self request */
1839 w = thread_selection_wnd();
1840 if (!w)
1842 ERR("No window available to retrieve selection!\n");
1843 return -1;
1847 * Query the selection owner for the TARGETS property
1849 wine_tsx11_lock();
1850 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1851 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1853 wine_tsx11_unlock();
1854 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1855 selectionCacheSrc = XA_PRIMARY;
1856 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1857 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1858 else
1860 Atom xstr = XA_STRING;
1862 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1863 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1865 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1866 selectionCacheSrc = XA_PRIMARY;
1867 return 1;
1869 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1871 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1872 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1873 return 1;
1875 else
1877 WARN("Failed to query selection owner for available data.\n");
1878 return -1;
1882 else /* No selection owner so report 0 targets available */
1884 wine_tsx11_unlock();
1885 return 0;
1888 /* Read the TARGETS property contents */
1889 wine_tsx11_lock();
1890 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1891 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1892 &remain, (unsigned char**)&targetList) != Success)
1894 wine_tsx11_unlock();
1895 WARN("Failed to read TARGETS property\n");
1897 else
1899 wine_tsx11_unlock();
1900 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1901 atype, aformat, cSelectionTargets, remain);
1903 * The TARGETS property should have returned us a list of atoms
1904 * corresponding to each selection target format supported.
1906 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1907 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, (cSelectionTargets * aformat / (8 * sizeof(Atom))));
1909 /* Free the list of targets */
1910 wine_tsx11_lock();
1911 XFree(targetList);
1912 wine_tsx11_unlock();
1915 return cSelectionTargets;
1919 /**************************************************************************
1920 * X11DRV_CLIPBOARD_ReadSelectionData
1922 * This method is invoked only when we DO NOT own the X selection
1924 * We always get the data from the selection client each time,
1925 * since we have no way of determining if the data in our cache is stale.
1927 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(LPWINE_CLIPDATA lpData)
1929 Display *display = thread_display();
1930 Bool res;
1931 DWORD i;
1932 XEvent xe;
1933 BOOL bRet = FALSE;
1935 TRACE("%d\n", lpData->wFormatID);
1937 if (!lpData->lpFormat)
1939 ERR("Requesting format %d but no source format linked to data.\n",
1940 lpData->wFormatID);
1941 return FALSE;
1944 if (!selectionAcquired)
1946 Window w = thread_selection_wnd();
1947 if(!w)
1949 ERR("No window available to read selection data!\n");
1950 return FALSE;
1953 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
1954 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
1956 wine_tsx11_lock();
1957 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
1958 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1959 wine_tsx11_unlock();
1961 /* wait until SelectionNotify is received */
1962 for (i = 0; i < SELECTION_RETRIES; i++)
1964 wine_tsx11_lock();
1965 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1966 wine_tsx11_unlock();
1967 if (res && xe.xselection.selection == selectionCacheSrc) break;
1969 usleep(SELECTION_WAIT);
1972 /* Verify that the selection returned a valid TARGETS property */
1973 if (xe.xselection.property != None)
1976 * Read the contents of the X selection property
1977 * into WINE's clipboard cache and converting the
1978 * data format if necessary.
1980 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(xe.xselection.requestor,
1981 xe.xselection.property);
1983 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
1985 else
1987 TRACE("Failed to convert selection\n");
1990 else
1992 ERR("Received request to cache selection data but process is owner\n");
1995 TRACE("Returning %d\n", bRet);
1997 return bRet;
2001 /**************************************************************************
2002 * X11DRV_CLIPBOARD_ReadProperty
2003 * Reads the contents of the X selection property.
2005 static BOOL X11DRV_CLIPBOARD_ReadProperty(Window w, Atom prop,
2006 unsigned char** data, unsigned long* datasize)
2008 Display *display = thread_display();
2009 Atom atype = AnyPropertyType;
2010 int aformat;
2011 unsigned long total, nitems, remain, val_cnt;
2012 long reqlen, bwc;
2013 unsigned char* val;
2014 unsigned char* buffer;
2016 if (prop == None)
2017 return FALSE;
2019 TRACE("Reading property %d from X window %d\n",
2020 (unsigned int)prop, (unsigned int)w);
2023 * First request a zero length in order to figure out the request size.
2025 wine_tsx11_lock();
2026 if(XGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType,
2027 &atype, &aformat, &nitems, &remain, &buffer) != Success)
2029 wine_tsx11_unlock();
2030 WARN("Failed to get property size\n");
2031 return FALSE;
2034 /* Free zero length return data if any */
2035 if (buffer)
2037 XFree(buffer);
2038 buffer = NULL;
2041 bwc = aformat/8;
2042 reqlen = remain * bwc;
2044 TRACE("Retrieving %ld bytes\n", reqlen);
2046 val = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, reqlen);
2048 /* Read property in 4K blocks */
2049 for (total = 0, val_cnt = 0; remain;)
2051 if (XGetWindowProperty(display, w, prop, (total / 4), 4096, False,
2052 AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
2054 wine_tsx11_unlock();
2055 WARN("Failed to read property\n");
2056 HeapFree(GetProcessHeap(), 0, val);
2057 return FALSE;
2060 bwc = aformat/8;
2061 memcpy(&val[val_cnt], buffer, nitems * bwc);
2062 val_cnt += nitems * bwc;
2063 total += nitems*bwc;
2064 XFree(buffer);
2067 /* Delete the property on the window now that we are done
2068 * This will send a PropertyNotify event to the selection owner. */
2069 XDeleteProperty(display, w, prop);
2071 wine_tsx11_unlock();
2073 *data = val;
2074 *datasize = total;
2076 return TRUE;
2080 /**************************************************************************
2081 * CLIPBOARD_SerializeMetafile
2083 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2085 HANDLE h = 0;
2087 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2089 if (out) /* Serialize out, caller should free memory */
2091 *lpcbytes = 0; /* Assume failure */
2093 if (wformat == CF_METAFILEPICT)
2095 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
2096 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2098 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2099 if (h)
2101 char *pdata = GlobalLock(h);
2103 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2104 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2106 *lpcbytes = size + sizeof(METAFILEPICT);
2108 GlobalUnlock(h);
2111 GlobalUnlock(hdata);
2113 else if (wformat == CF_ENHMETAFILE)
2115 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2117 h = GlobalAlloc(0, size);
2118 if (h)
2120 LPVOID pdata = GlobalLock(h);
2122 GetEnhMetaFileBits(hdata, size, pdata);
2123 *lpcbytes = size;
2125 GlobalUnlock(h);
2129 else
2131 if (wformat == CF_METAFILEPICT)
2133 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2134 if (h)
2136 unsigned int wiresize, size;
2137 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
2139 memcpy(lpmfp, (LPVOID)hdata, sizeof(METAFILEPICT));
2140 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2141 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2142 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2143 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2144 GlobalUnlock(h);
2147 else if (wformat == CF_ENHMETAFILE)
2149 h = SetEnhMetaFileBits(*lpcbytes, (LPVOID)hdata);
2153 return h;
2157 /**************************************************************************
2158 * X11DRV_CLIPBOARD_ReleaseSelection
2160 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2162 static void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd, Time time)
2164 Display *display = thread_display();
2166 /* w is the window that lost the selection
2168 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2169 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2171 if (selectionAcquired && (w == selectionWindow))
2173 CLIPBOARDINFO cbinfo;
2175 /* completely give up the selection */
2176 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2178 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2180 if (cbinfo.flags & CB_PROCESS)
2182 /* Since we're still the owner, this wasn't initiated by
2183 another Wine process */
2184 if (OpenClipboard(hwnd))
2186 /* Destroy private objects */
2187 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2189 /* Give up ownership of the windows clipboard */
2190 X11DRV_CLIPBOARD_ReleaseOwnership();
2191 CloseClipboard();
2195 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2197 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2199 wine_tsx11_lock();
2200 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2202 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2203 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2205 else
2206 TRACE("We no longer own PRIMARY\n");
2207 wine_tsx11_unlock();
2209 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2211 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2213 wine_tsx11_lock();
2214 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2216 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2217 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2219 else
2220 TRACE("We no longer own CLIPBOARD\n");
2221 wine_tsx11_unlock();
2224 selectionWindow = None;
2226 X11DRV_EmptyClipboard(FALSE);
2228 /* Reset the selection flags now that we are done */
2229 selectionAcquired = S_NOSELECTION;
2234 /**************************************************************************
2235 * IsSelectionOwner (X11DRV.@)
2237 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2239 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2241 return selectionAcquired;
2245 /**************************************************************************
2246 * X11DRV Clipboard Exports
2247 **************************************************************************/
2250 /**************************************************************************
2251 * RegisterClipboardFormat (X11DRV.@)
2253 * Registers a custom X clipboard format
2254 * Returns: Format id or 0 on failure
2256 UINT X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2258 LPWINE_CLIPFORMAT lpFormat;
2260 if (FormatName == NULL) return 0;
2261 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2262 return lpFormat->wFormatID;
2266 /**************************************************************************
2267 * X11DRV_GetClipboardFormatName
2269 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2271 LPWINE_CLIPFORMAT lpFormat;
2273 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2275 if (wFormat < 0xc000)
2277 SetLastError(ERROR_INVALID_PARAMETER);
2278 return 0;
2281 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2283 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2285 TRACE("Unknown format 0x%08x!\n", wFormat);
2286 SetLastError(ERROR_INVALID_HANDLE);
2287 return 0;
2290 lstrcpynW(retStr, lpFormat->Name, maxlen);
2292 return strlenW(retStr);
2296 /**************************************************************************
2297 * AcquireClipboard (X11DRV.@)
2299 int X11DRV_AcquireClipboard(HWND hWndClipWindow)
2301 DWORD procid;
2302 Window owner;
2303 Display *display = thread_display();
2305 TRACE(" %p\n", hWndClipWindow);
2308 * It's important that the selection get acquired from the thread
2309 * that owns the clipboard window. The primary reason is that we know
2310 * it is running a message loop and therefore can process the
2311 * X selection events.
2313 if (hWndClipWindow &&
2314 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2316 if (procid != GetCurrentProcessId())
2318 WARN("Setting clipboard owner to other process is not supported\n");
2319 hWndClipWindow = NULL;
2321 else
2323 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2324 GetCurrentThreadId(),
2325 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2327 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2331 owner = thread_selection_wnd();
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(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 memcpy( &event, pevent, sizeof(XSelectionRequestEvent) );
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(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, (unsigned char *)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->selection, event->window, hWnd, event->time );