shell32: Add explorer toolbar bitmaps.
[wine/hramrach.git] / dlls / winex11.drv / clipboard.c
blob7cea221b29e8c7422f6f3b67569cae512cccc915
1 /*
2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
5 * 1996 Alex Korobka
6 * 1999 Noel Borthwick
7 * 2003 Ulrich Czekalla for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * NOTES:
24 * This file contains the X specific implementation for the windows
25 * Clipboard API.
27 * Wine's internal clipboard is exposed to external apps via the X
28 * selection mechanism.
29 * Currently the driver asserts ownership via two selection atoms:
30 * 1. PRIMARY(XA_PRIMARY)
31 * 2. CLIPBOARD
33 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
34 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
35 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
36 * While giving up selection ownership, if the CLIPBOARD selection is lost,
37 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
38 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
39 * (leaving the clipboard cache content unaffected).
41 * Every format exposed via a windows clipboard format is also exposed through
42 * a corresponding X selection target. A selection target atom is synthesized
43 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
44 * or when a built-in format is used for the first time.
45 * Windows native format are exposed by prefixing the format name with "<WCF>"
46 * This allows us to uniquely identify windows native formats exposed by other
47 * running WINE apps.
49 * In order to allow external applications to query WINE for supported formats,
50 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
51 * for implementation) We use the same mechanism to query external clients for
52 * availability of a particular format, by caching the list of available targets
53 * by using the clipboard cache's "delayed render" mechanism. If a selection client
54 * does not support the "TARGETS" selection target, we actually attempt to retrieve
55 * the format requested as a fallback mechanism.
57 * Certain Windows native formats are automatically converted to X native formats
58 * and vice versa. If a native format is available in the selection, it takes
59 * precedence, in order to avoid unnecessary conversions.
61 * FIXME: global format list needs a critical section
64 #include "config.h"
65 #include "wine/port.h"
67 #include <string.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #ifdef HAVE_UNISTD_H
72 # include <unistd.h>
73 #endif
74 #include <fcntl.h>
75 #include <limits.h>
76 #include <time.h>
77 #include <assert.h>
79 #include "windef.h"
80 #include "winbase.h"
81 #include "wine/wingdi16.h"
82 #include "x11drv.h"
83 #include "wine/debug.h"
84 #include "wine/unicode.h"
85 #include "wine/server.h"
87 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
89 #define HGDIOBJ_32(handle16) ((HGDIOBJ)(ULONG_PTR)(handle16))
91 /* Maximum wait time for selection notify */
92 #define SELECTION_RETRIES 500 /* wait for .1 seconds */
93 #define SELECTION_WAIT 1000 /* us */
94 /* Minimum seconds that must lapse between owner queries */
95 #define OWNERQUERYLAPSETIME 1
97 /* Selection masks */
98 #define S_NOSELECTION 0
99 #define S_PRIMARY 1
100 #define S_CLIPBOARD 2
102 typedef struct
104 HWND hWndOpen;
105 HWND hWndOwner;
106 HWND hWndViewer;
107 UINT seqno;
108 UINT flags;
109 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
111 struct tagWINE_CLIPDATA; /* Forward */
113 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
114 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
115 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
117 typedef struct tagWINE_CLIPFORMAT {
118 UINT wFormatID;
119 LPCWSTR Name;
120 UINT drvData;
121 UINT wFlags;
122 DRVIMPORTFUNC lpDrvImportFunc;
123 DRVEXPORTFUNC lpDrvExportFunc;
124 struct tagWINE_CLIPFORMAT *PrevFormat;
125 struct tagWINE_CLIPFORMAT *NextFormat;
126 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
128 typedef struct tagWINE_CLIPDATA {
129 UINT wFormatID;
130 HANDLE16 hData16;
131 HANDLE hData32;
132 UINT wFlags;
133 UINT drvData;
134 LPWINE_CLIPFORMAT lpFormat;
135 struct tagWINE_CLIPDATA *PrevData;
136 struct tagWINE_CLIPDATA *NextData;
137 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
139 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
140 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
141 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
142 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
144 static int selectionAcquired = 0; /* Contains the current selection masks */
145 static Window selectionWindow = None; /* The top level X window which owns the selection */
146 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
148 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned);
149 void CDECL X11DRV_EndClipboardUpdate(void);
150 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
157 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
158 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
159 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
160 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
161 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
162 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
163 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
164 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
165 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
166 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
167 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
168 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
169 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
170 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
171 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
172 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
173 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
174 unsigned char** data, unsigned long* datasize);
175 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
176 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
177 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
178 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
180 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
181 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
183 /* Clipboard formats
184 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
185 * declared in clipboard.h
187 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
188 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
189 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
190 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
191 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
192 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
193 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
194 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
195 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
196 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
197 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
198 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
199 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
200 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
201 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
202 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
203 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
204 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
205 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
206 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
207 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
208 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
209 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
211 static WINE_CLIPFORMAT ClipFormats[] =
213 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
214 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
216 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
217 NULL, &ClipFormats[0], &ClipFormats[2]},
219 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
220 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
222 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
223 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
225 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
226 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
228 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
229 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
231 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
232 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
234 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
235 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
237 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
238 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
240 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
241 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
243 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
244 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
246 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
247 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
249 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
250 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
252 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
253 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
254 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
256 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
257 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
259 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
260 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
262 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
263 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
265 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
266 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
268 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
269 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
271 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
272 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
274 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
275 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
277 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
278 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
280 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
281 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], NULL}
284 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
286 /* Maps X properties to Windows formats */
287 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
288 static const WCHAR wszGIF[] = {'G','I','F',0};
289 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
290 static const struct
292 LPCWSTR lpszFormat;
293 UINT prop;
294 } PropertyFormatMap[] =
296 { wszRichTextFormat, XATOM_text_rtf },
297 { wszRichTextFormat, XATOM_text_richtext },
298 { wszGIF, XATOM_image_gif },
299 { wszHTMLFormat, XATOM_text_html },
304 * Cached clipboard data.
306 static LPWINE_CLIPDATA ClipData = NULL;
307 static UINT ClipDataCount = 0;
310 * Clipboard sequence number
312 static UINT wSeqNo = 0;
314 /**************************************************************************
315 * Internal Clipboard implementation methods
316 **************************************************************************/
318 static Window thread_selection_wnd(void)
320 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
321 Window w = thread_data->selection_wnd;
323 if (!w)
325 XSetWindowAttributes attr;
327 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
328 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
330 wine_tsx11_lock();
331 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
332 InputOutput, CopyFromParent, CWEventMask, &attr);
333 wine_tsx11_unlock();
335 if (w)
336 thread_data->selection_wnd = w;
337 else
338 FIXME("Failed to create window. Fetching selection data will fail.\n");
341 return w;
344 /**************************************************************************
345 * X11DRV_InitClipboard
347 void X11DRV_InitClipboard(void)
349 UINT i;
351 /* Register known mapping between window formats and X properties */
352 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
353 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
357 /**************************************************************************
358 * intern_atoms
360 * Intern atoms for formats that don't have one yet.
362 static void intern_atoms(void)
364 LPWINE_CLIPFORMAT format;
365 int i, count, len;
366 char **names;
367 Atom *atoms;
368 Display *display;
370 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
371 if (!format->drvData) count++;
372 if (!count) return;
374 display = thread_init_display();
376 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
377 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
379 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
380 if (!format->drvData) {
381 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
382 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
383 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
387 wine_tsx11_lock();
388 XInternAtoms( display, names, count, False, atoms );
389 wine_tsx11_unlock();
391 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
392 if (!format->drvData) {
393 HeapFree(GetProcessHeap(), 0, names[i]);
394 format->drvData = atoms[i++];
398 HeapFree( GetProcessHeap(), 0, names );
399 HeapFree( GetProcessHeap(), 0, atoms );
403 /**************************************************************************
404 * register_format
406 * Register a custom X clipboard format.
408 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
410 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
412 TRACE("%s\n", debugstr_w(FormatName));
414 /* walk format chain to see if it's already registered */
415 while (lpFormat)
417 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
418 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
419 return lpFormat;
420 lpFormat = lpFormat->NextFormat;
423 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
427 /**************************************************************************
428 * X11DRV_CLIPBOARD_LookupFormat
430 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
432 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
434 while(lpFormat)
436 if (lpFormat->wFormatID == wID)
437 break;
439 lpFormat = lpFormat->NextFormat;
441 if (lpFormat && !lpFormat->drvData) intern_atoms();
442 return lpFormat;
446 /**************************************************************************
447 * X11DRV_CLIPBOARD_LookupProperty
449 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
451 for (;;)
453 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
454 BOOL need_intern = FALSE;
456 if (current)
457 lpFormat = current->NextFormat;
459 while(lpFormat)
461 if (lpFormat->drvData == drvData) return lpFormat;
462 if (!lpFormat->drvData) need_intern = TRUE;
463 lpFormat = lpFormat->NextFormat;
465 if (!need_intern) return NULL;
466 intern_atoms();
467 /* restart the search for the new atoms */
472 /**************************************************************************
473 * X11DRV_CLIPBOARD_LookupData
475 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
477 LPWINE_CLIPDATA lpData = ClipData;
479 if (lpData)
483 if (lpData->wFormatID == wID)
484 break;
486 lpData = lpData->NextData;
488 while(lpData != ClipData);
490 if (lpData->wFormatID != wID)
491 lpData = NULL;
494 return lpData;
498 /**************************************************************************
499 * InsertClipboardFormat
501 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
503 LPWINE_CLIPFORMAT lpFormat;
504 LPWINE_CLIPFORMAT lpNewFormat;
505 LPWSTR new_name;
507 /* allocate storage for new format entry */
508 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
510 if(lpNewFormat == NULL)
512 WARN("No more memory for a new format!\n");
513 return NULL;
516 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
518 WARN("No more memory for the new format name!\n");
519 HeapFree(GetProcessHeap(), 0, lpNewFormat);
520 return NULL;
523 lpNewFormat->Name = strcpyW(new_name, FormatName);
524 lpNewFormat->wFlags = 0;
525 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
526 lpNewFormat->drvData = prop;
527 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
528 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
530 /* Link Format */
531 lpFormat = ClipFormats;
533 while(lpFormat->NextFormat) /* Move to last entry */
534 lpFormat = lpFormat->NextFormat;
536 lpNewFormat->NextFormat = NULL;
537 lpFormat->NextFormat = lpNewFormat;
538 lpNewFormat->PrevFormat = lpFormat;
540 TRACE("Registering format(%d): %s drvData %d\n",
541 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
543 return lpNewFormat;
549 /**************************************************************************
550 * X11DRV_CLIPBOARD_GetClipboardInfo
552 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
554 BOOL bRet = FALSE;
556 SERVER_START_REQ( set_clipboard_info )
558 req->flags = 0;
560 if (wine_server_call_err( req ))
562 ERR("Failed to get clipboard owner.\n");
564 else
566 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
567 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
568 cbInfo->hWndViewer = wine_server_ptr_handle( 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 = 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 = GlobalLock(lpSource->hData32);
975 else
977 lpstrS = 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 = 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 = 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, ret;
1228 char** srcstr;
1229 int count, lcount;
1230 int srclen, destlen;
1231 HANDLE hUnicodeText;
1232 XTextProperty txtprop;
1234 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1236 return 0;
1239 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1240 txtprop.format = 8;
1241 wine_tsx11_lock();
1242 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1243 wine_tsx11_unlock();
1244 HeapFree(GetProcessHeap(), 0, txtprop.value);
1245 if (ret != Success || !count) return 0;
1247 TRACE("Importing %d line(s)\n", count);
1249 /* Compute number of lines */
1250 srclen = strlen(srcstr[0]);
1251 for (i = 0, lcount = 0; i <= srclen; i++)
1253 if (srcstr[0][i] == '\n')
1254 lcount++;
1257 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1259 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1261 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1263 WCHAR *deststr = GlobalLock(hUnicodeText);
1264 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1266 if (lcount)
1268 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1270 deststr[j] = deststr[i];
1272 if (deststr[i] == '\n')
1273 deststr[--j] = '\r';
1277 GlobalUnlock(hUnicodeText);
1280 wine_tsx11_lock();
1281 XFreeStringList(srcstr);
1282 wine_tsx11_unlock();
1284 return hUnicodeText;
1288 /**************************************************************************
1289 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1291 * Import XA_PIXMAP, converting the image to CF_DIB.
1293 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1295 HWND hwnd;
1296 HDC hdc;
1297 LPBYTE lpdata;
1298 unsigned long cbytes;
1299 Pixmap *pPixmap;
1300 HANDLE hClipData = 0;
1302 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1304 pPixmap = (Pixmap *) lpdata;
1306 hwnd = GetOpenClipboardWindow();
1307 hdc = GetDC(hwnd);
1309 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1310 ReleaseDC(hwnd, hdc);
1312 /* Free the retrieved property data */
1313 HeapFree(GetProcessHeap(), 0, lpdata);
1316 return hClipData;
1320 /**************************************************************************
1321 * X11DRV_CLIPBOARD_ImportMetaFilePict
1323 * Import MetaFilePict.
1325 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1327 LPBYTE lpdata;
1328 unsigned long cbytes;
1329 HANDLE hClipData = 0;
1331 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1333 if (cbytes)
1334 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1336 /* Free the retrieved property data */
1337 HeapFree(GetProcessHeap(), 0, lpdata);
1340 return hClipData;
1344 /**************************************************************************
1345 * X11DRV_ImportEnhMetaFile
1347 * Import EnhMetaFile.
1349 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1351 LPBYTE lpdata;
1352 unsigned long cbytes;
1353 HANDLE hClipData = 0;
1355 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1357 if (cbytes)
1358 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1360 /* Free the retrieved property data */
1361 HeapFree(GetProcessHeap(), 0, lpdata);
1364 return hClipData;
1368 /**************************************************************************
1369 * X11DRV_ImportClipbordaData
1371 * Generic import clipboard data routine.
1373 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1375 LPVOID lpClipData;
1376 LPBYTE lpdata;
1377 unsigned long cbytes;
1378 HANDLE hClipData = 0;
1380 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1382 if (cbytes)
1384 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1385 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1386 if (hClipData == 0)
1387 return NULL;
1389 if ((lpClipData = GlobalLock(hClipData)))
1391 memcpy(lpClipData, lpdata, cbytes);
1392 GlobalUnlock(hClipData);
1394 else
1396 GlobalFree(hClipData);
1397 hClipData = 0;
1401 /* Free the retrieved property data */
1402 HeapFree(GetProcessHeap(), 0, lpdata);
1405 return hClipData;
1409 /**************************************************************************
1410 X11DRV_CLIPBOARD_ExportClipboardData
1412 * Generic export clipboard data routine.
1414 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1415 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1417 LPVOID lpClipData;
1418 UINT datasize = 0;
1419 HANDLE hClipData = 0;
1421 *lpBytes = 0; /* Assume failure */
1423 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1424 ERR("Failed to export %d format\n", lpData->wFormatID);
1425 else
1427 datasize = GlobalSize(lpData->hData32);
1429 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1430 if (hClipData == 0) return NULL;
1432 if ((lpClipData = GlobalLock(hClipData)))
1434 LPVOID lpdata = GlobalLock(lpData->hData32);
1436 memcpy(lpClipData, lpdata, datasize);
1437 *lpBytes = datasize;
1439 GlobalUnlock(lpData->hData32);
1440 GlobalUnlock(hClipData);
1441 } else {
1442 GlobalFree(hClipData);
1443 hClipData = 0;
1447 return hClipData;
1451 /**************************************************************************
1452 * X11DRV_CLIPBOARD_ExportXAString
1454 * Export CF_TEXT converting the string to XA_STRING.
1455 * Helper function for X11DRV_CLIPBOARD_ExportString.
1457 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1459 UINT i, j;
1460 UINT size;
1461 LPSTR text, lpstr = NULL;
1463 *lpBytes = 0; /* Assume return has zero bytes */
1465 text = GlobalLock(lpData->hData32);
1466 size = strlen(text);
1468 /* remove carriage returns */
1469 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1470 if (lpstr == NULL)
1471 goto done;
1473 for (i = 0,j = 0; i < size && text[i]; i++)
1475 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1476 continue;
1477 lpstr[j++] = text[i];
1480 lpstr[j]='\0';
1481 *lpBytes = j; /* Number of bytes in string */
1483 done:
1484 HeapFree(GetProcessHeap(), 0, text);
1485 GlobalUnlock(lpData->hData32);
1487 return lpstr;
1491 /**************************************************************************
1492 * X11DRV_CLIPBOARD_ExportUTF8String
1494 * Export CF_UNICODE converting the string to UTF8.
1495 * Helper function for X11DRV_CLIPBOARD_ExportString.
1497 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1499 UINT i, j;
1500 UINT size;
1501 LPWSTR uni_text;
1502 LPSTR text, lpstr = NULL;
1504 *lpBytes = 0; /* Assume return has zero bytes */
1506 uni_text = GlobalLock(lpData->hData32);
1508 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1510 text = HeapAlloc(GetProcessHeap(), 0, size);
1511 if (!text)
1512 goto done;
1513 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1515 /* remove carriage returns */
1516 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1517 if (lpstr == NULL)
1518 goto done;
1520 for (i = 0,j = 0; i < size && text[i]; i++)
1522 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1523 continue;
1524 lpstr[j++] = text[i];
1526 lpstr[j]='\0';
1528 *lpBytes = j; /* Number of bytes in string */
1530 done:
1531 HeapFree(GetProcessHeap(), 0, text);
1532 GlobalUnlock(lpData->hData32);
1534 return lpstr;
1539 /**************************************************************************
1540 * X11DRV_CLIPBOARD_ExportCompoundText
1542 * Export CF_UNICODE to COMPOUND_TEXT
1543 * Helper function for X11DRV_CLIPBOARD_ExportString.
1545 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1546 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1548 char* lpstr = 0;
1549 XTextProperty prop;
1550 XICCEncodingStyle style;
1551 UINT i, j;
1552 UINT size;
1553 LPWSTR uni_text;
1555 uni_text = GlobalLock(lpData->hData32);
1557 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1558 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1559 if (!lpstr)
1560 return 0;
1562 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1564 /* remove carriage returns */
1565 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1567 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1568 continue;
1569 lpstr[j++] = lpstr[i];
1571 lpstr[j]='\0';
1573 GlobalUnlock(lpData->hData32);
1575 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1576 style = XCompoundTextStyle;
1577 else
1578 style = XStdICCTextStyle;
1580 /* Update the X property */
1581 wine_tsx11_lock();
1582 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1584 XSetTextProperty(display, requestor, &prop, rprop);
1585 XFree(prop.value);
1587 wine_tsx11_unlock();
1589 HeapFree(GetProcessHeap(), 0, lpstr);
1591 return 0;
1594 /**************************************************************************
1595 * X11DRV_CLIPBOARD_ExportString
1597 * Export string
1599 HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1600 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1602 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1604 if (aTarget == XA_STRING)
1605 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1606 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1607 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1608 rprop, lpData, lpBytes);
1609 else
1611 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1612 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1615 else
1616 ERR("Failed to render %d format\n", lpData->wFormatID);
1618 return 0;
1622 /**************************************************************************
1623 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1625 * Export CF_DIB to XA_PIXMAP.
1627 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1628 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1630 HDC hdc;
1631 HANDLE hData;
1632 unsigned char* lpData;
1634 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1636 ERR("Failed to export %d format\n", lpdata->wFormatID);
1637 return 0;
1640 if (!lpdata->drvData) /* If not already rendered */
1642 /* For convert from packed DIB to Pixmap */
1643 hdc = GetDC(0);
1644 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1645 ReleaseDC(0, hdc);
1648 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1650 /* Wrap pixmap so we can return a handle */
1651 hData = GlobalAlloc(0, *lpBytes);
1652 lpData = GlobalLock(hData);
1653 memcpy(lpData, &lpdata->drvData, *lpBytes);
1654 GlobalUnlock(hData);
1656 return hData;
1660 /**************************************************************************
1661 * X11DRV_CLIPBOARD_ExportMetaFilePict
1663 * Export MetaFilePict.
1665 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1666 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1668 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1670 ERR("Failed to export %d format\n", lpdata->wFormatID);
1671 return 0;
1674 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1678 /**************************************************************************
1679 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1681 * Export EnhMetaFile.
1683 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1684 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1686 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1688 ERR("Failed to export %d format\n", lpdata->wFormatID);
1689 return 0;
1692 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1696 /**************************************************************************
1697 * X11DRV_CLIPBOARD_QueryTargets
1699 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1700 Atom target, XEvent *xe)
1702 INT i;
1703 Bool res;
1705 wine_tsx11_lock();
1706 XConvertSelection(display, selection, target,
1707 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1708 wine_tsx11_unlock();
1711 * Wait until SelectionNotify is received
1713 for (i = 0; i < SELECTION_RETRIES; i++)
1715 wine_tsx11_lock();
1716 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1717 wine_tsx11_unlock();
1718 if (res && xe->xselection.selection == selection) break;
1720 usleep(SELECTION_WAIT);
1723 /* Verify that the selection returned a valid TARGETS property */
1724 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1726 /* Selection owner failed to respond or we missed the SelectionNotify */
1727 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1728 return FALSE;
1731 return TRUE;
1735 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1737 return (event->error_code == BadAtom);
1740 /**************************************************************************
1741 * X11DRV_CLIPBOARD_InsertSelectionProperties
1743 * Mark properties available for future retrieval.
1745 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1747 UINT i, nb_atoms = 0;
1748 Atom *atoms = NULL;
1750 /* Cache these formats in the clipboard cache */
1751 for (i = 0; i < count; i++)
1753 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1755 if (lpFormat)
1757 /* We found at least one Window's format that mapps to the property.
1758 * Continue looking for more.
1760 * If more than one property map to a Window's format then we use the first
1761 * one and ignore the rest.
1763 while (lpFormat)
1765 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1766 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1767 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1768 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1771 else if (properties[i])
1773 /* add it to the list of atoms that we don't know about yet */
1774 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1775 (count - i) * sizeof(*atoms) );
1776 if (atoms) atoms[nb_atoms++] = properties[i];
1780 /* query all unknown atoms in one go */
1781 if (atoms)
1783 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1784 if (names)
1786 X11DRV_expect_error( display, is_atom_error, NULL );
1787 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1788 if (X11DRV_check_error())
1790 WARN( "got some bad atoms, ignoring\n" );
1791 nb_atoms = 0;
1793 for (i = 0; i < nb_atoms; i++)
1795 WINE_CLIPFORMAT *lpFormat;
1796 LPWSTR wname;
1797 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1798 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1799 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1801 lpFormat = register_format( wname, atoms[i] );
1802 HeapFree(GetProcessHeap(), 0, wname);
1803 if (!lpFormat)
1805 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1806 continue;
1808 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1809 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1810 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1812 wine_tsx11_lock();
1813 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1814 wine_tsx11_unlock();
1815 HeapFree( GetProcessHeap(), 0, names );
1817 HeapFree( GetProcessHeap(), 0, atoms );
1822 /**************************************************************************
1823 * X11DRV_CLIPBOARD_QueryAvailableData
1825 * Caches the list of data formats available from the current selection.
1826 * This queries the selection owner for the TARGETS property and saves all
1827 * reported property types.
1829 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1831 XEvent xe;
1832 Atom atype=AnyPropertyType;
1833 int aformat;
1834 unsigned long remain;
1835 Atom* targetList=NULL;
1836 Window w;
1837 unsigned long cSelectionTargets = 0;
1839 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1841 ERR("Received request to cache selection but process is owner=(%08x)\n",
1842 (unsigned) selectionWindow);
1843 return -1; /* Prevent self request */
1846 w = thread_selection_wnd();
1847 if (!w)
1849 ERR("No window available to retrieve selection!\n");
1850 return -1;
1854 * Query the selection owner for the TARGETS property
1856 wine_tsx11_lock();
1857 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1858 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1860 wine_tsx11_unlock();
1861 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1862 selectionCacheSrc = XA_PRIMARY;
1863 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1864 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1865 else
1867 Atom xstr = XA_STRING;
1869 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1870 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1872 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1873 selectionCacheSrc = XA_PRIMARY;
1874 return 1;
1876 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1878 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1879 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1880 return 1;
1882 else
1884 WARN("Failed to query selection owner for available data.\n");
1885 return -1;
1889 else /* No selection owner so report 0 targets available */
1891 wine_tsx11_unlock();
1892 return 0;
1895 /* Read the TARGETS property contents */
1896 wine_tsx11_lock();
1897 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1898 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1899 &remain, (unsigned char**)&targetList) != Success)
1901 wine_tsx11_unlock();
1902 WARN("Failed to read TARGETS property\n");
1904 else
1906 wine_tsx11_unlock();
1907 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1908 atype, aformat, cSelectionTargets, remain);
1910 * The TARGETS property should have returned us a list of atoms
1911 * corresponding to each selection target format supported.
1913 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1915 if (aformat == 32)
1917 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1919 else if (aformat == 8) /* work around quartz-wm brain damage */
1921 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
1922 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
1923 for (i = 0; i < count; i++)
1924 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
1925 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
1926 HeapFree( GetProcessHeap(), 0, atoms );
1930 /* Free the list of targets */
1931 wine_tsx11_lock();
1932 XFree(targetList);
1933 wine_tsx11_unlock();
1936 return cSelectionTargets;
1940 /**************************************************************************
1941 * X11DRV_CLIPBOARD_ReadSelectionData
1943 * This method is invoked only when we DO NOT own the X selection
1945 * We always get the data from the selection client each time,
1946 * since we have no way of determining if the data in our cache is stale.
1948 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
1950 Bool res;
1951 DWORD i;
1952 XEvent xe;
1953 BOOL bRet = FALSE;
1955 TRACE("%d\n", lpData->wFormatID);
1957 if (!lpData->lpFormat)
1959 ERR("Requesting format %d but no source format linked to data.\n",
1960 lpData->wFormatID);
1961 return FALSE;
1964 if (!selectionAcquired)
1966 Window w = thread_selection_wnd();
1967 if(!w)
1969 ERR("No window available to read selection data!\n");
1970 return FALSE;
1973 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
1974 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
1976 wine_tsx11_lock();
1977 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
1978 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1979 wine_tsx11_unlock();
1981 /* wait until SelectionNotify is received */
1982 for (i = 0; i < SELECTION_RETRIES; i++)
1984 wine_tsx11_lock();
1985 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1986 wine_tsx11_unlock();
1987 if (res && xe.xselection.selection == selectionCacheSrc) break;
1989 usleep(SELECTION_WAIT);
1992 /* Verify that the selection returned a valid TARGETS property */
1993 if (xe.xselection.property != None)
1996 * Read the contents of the X selection property
1997 * into WINE's clipboard cache and converting the
1998 * data format if necessary.
2000 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2001 xe.xselection.property);
2003 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
2005 else
2007 TRACE("Failed to convert selection\n");
2010 else
2012 ERR("Received request to cache selection data but process is owner\n");
2015 TRACE("Returning %d\n", bRet);
2017 return bRet;
2021 /**************************************************************************
2022 * X11DRV_CLIPBOARD_GetProperty
2023 * Gets type, data and size.
2025 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2026 Atom *atype, unsigned char** data, unsigned long* datasize)
2028 int aformat;
2029 unsigned long pos = 0, nitems, remain, count;
2030 unsigned char *val = NULL, *buffer;
2032 TRACE("Reading property %lu from X window %lx\n", prop, w);
2034 for (;;)
2036 wine_tsx11_lock();
2037 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2038 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2040 wine_tsx11_unlock();
2041 WARN("Failed to read property\n");
2042 HeapFree( GetProcessHeap(), 0, val );
2043 return FALSE;
2046 count = get_property_size( aformat, nitems );
2047 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2048 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2050 if (!*data)
2052 XFree( buffer );
2053 wine_tsx11_unlock();
2054 HeapFree( GetProcessHeap(), 0, val );
2055 return FALSE;
2057 val = *data;
2058 memcpy( (int *)val + pos, buffer, count );
2059 XFree( buffer );
2060 wine_tsx11_unlock();
2061 if (!remain)
2063 *datasize = pos * sizeof(int) + count;
2064 val[*datasize] = 0;
2065 break;
2067 pos += count / sizeof(int);
2070 /* Delete the property on the window now that we are done
2071 * This will send a PropertyNotify event to the selection owner. */
2072 wine_tsx11_lock();
2073 XDeleteProperty(display, w, prop);
2074 wine_tsx11_unlock();
2075 return TRUE;
2079 /**************************************************************************
2080 * X11DRV_CLIPBOARD_ReadProperty
2081 * Reads the contents of the X selection property.
2083 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2084 unsigned char** data, unsigned long* datasize)
2086 Atom atype;
2087 XEvent xe;
2089 if (prop == None)
2090 return FALSE;
2092 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2093 return FALSE;
2095 wine_tsx11_lock();
2096 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2098 wine_tsx11_unlock();
2100 if (atype == x11drv_atom(INCR))
2102 unsigned char *buf = *data;
2103 unsigned long bufsize = 0;
2105 for (;;)
2107 int i;
2108 unsigned char *prop_data, *tmp;
2109 unsigned long prop_size;
2111 /* Wait until PropertyNotify is received */
2112 for (i = 0; i < SELECTION_RETRIES; i++)
2114 Bool res;
2116 wine_tsx11_lock();
2117 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2118 wine_tsx11_unlock();
2119 if (res && xe.xproperty.atom == prop &&
2120 xe.xproperty.state == PropertyNewValue)
2121 break;
2122 usleep(SELECTION_WAIT);
2125 if (i >= SELECTION_RETRIES ||
2126 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2128 HeapFree(GetProcessHeap(), 0, buf);
2129 return FALSE;
2132 /* Retrieved entire data. */
2133 if (prop_size == 0)
2135 HeapFree(GetProcessHeap(), 0, prop_data);
2136 *data = buf;
2137 *datasize = bufsize;
2138 return TRUE;
2141 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2142 if (!tmp)
2144 HeapFree(GetProcessHeap(), 0, buf);
2145 return FALSE;
2148 buf = tmp;
2149 memcpy(buf + bufsize, prop_data, prop_size + 1);
2150 bufsize += prop_size;
2151 HeapFree(GetProcessHeap(), 0, prop_data);
2155 return TRUE;
2159 /**************************************************************************
2160 * CLIPBOARD_SerializeMetafile
2162 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2164 HANDLE h = 0;
2166 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2168 if (out) /* Serialize out, caller should free memory */
2170 *lpcbytes = 0; /* Assume failure */
2172 if (wformat == CF_METAFILEPICT)
2174 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2175 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2177 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2178 if (h)
2180 char *pdata = GlobalLock(h);
2182 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2183 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2185 *lpcbytes = size + sizeof(METAFILEPICT);
2187 GlobalUnlock(h);
2190 GlobalUnlock(hdata);
2192 else if (wformat == CF_ENHMETAFILE)
2194 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2196 h = GlobalAlloc(0, size);
2197 if (h)
2199 LPVOID pdata = GlobalLock(h);
2201 GetEnhMetaFileBits(hdata, size, pdata);
2202 *lpcbytes = size;
2204 GlobalUnlock(h);
2208 else
2210 if (wformat == CF_METAFILEPICT)
2212 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2213 if (h)
2215 unsigned int wiresize, size;
2216 LPMETAFILEPICT lpmfp = GlobalLock(h);
2218 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2219 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2220 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2221 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2222 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2223 GlobalUnlock(h);
2226 else if (wformat == CF_ENHMETAFILE)
2228 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2232 return h;
2236 /**************************************************************************
2237 * X11DRV_CLIPBOARD_ReleaseSelection
2239 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2241 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2243 /* w is the window that lost the selection
2245 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2246 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2248 if (selectionAcquired && (w == selectionWindow))
2250 CLIPBOARDINFO cbinfo;
2252 /* completely give up the selection */
2253 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2255 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2257 if (cbinfo.flags & CB_PROCESS)
2259 /* Since we're still the owner, this wasn't initiated by
2260 another Wine process */
2261 if (OpenClipboard(hwnd))
2263 /* Destroy private objects */
2264 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2266 /* Give up ownership of the windows clipboard */
2267 X11DRV_CLIPBOARD_ReleaseOwnership();
2268 CloseClipboard();
2272 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2274 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2276 wine_tsx11_lock();
2277 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2279 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2280 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2282 else
2283 TRACE("We no longer own PRIMARY\n");
2284 wine_tsx11_unlock();
2286 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2288 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2290 wine_tsx11_lock();
2291 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2293 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2294 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2296 else
2297 TRACE("We no longer own CLIPBOARD\n");
2298 wine_tsx11_unlock();
2301 selectionWindow = None;
2303 X11DRV_EmptyClipboard(FALSE);
2305 /* Reset the selection flags now that we are done */
2306 selectionAcquired = S_NOSELECTION;
2311 /**************************************************************************
2312 * IsSelectionOwner (X11DRV.@)
2314 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2316 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2318 return selectionAcquired;
2322 /**************************************************************************
2323 * X11DRV Clipboard Exports
2324 **************************************************************************/
2327 /**************************************************************************
2328 * RegisterClipboardFormat (X11DRV.@)
2330 * Registers a custom X clipboard format
2331 * Returns: Format id or 0 on failure
2333 UINT CDECL X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2335 LPWINE_CLIPFORMAT lpFormat;
2337 if (FormatName == NULL) return 0;
2338 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2339 return lpFormat->wFormatID;
2343 /**************************************************************************
2344 * X11DRV_GetClipboardFormatName
2346 INT CDECL X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2348 LPWINE_CLIPFORMAT lpFormat;
2350 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2352 if (wFormat < 0xc000)
2354 SetLastError(ERROR_INVALID_PARAMETER);
2355 return 0;
2358 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2360 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2362 TRACE("Unknown format 0x%08x!\n", wFormat);
2363 SetLastError(ERROR_INVALID_HANDLE);
2364 return 0;
2367 lstrcpynW(retStr, lpFormat->Name, maxlen);
2369 return strlenW(retStr);
2373 /**************************************************************************
2374 * AcquireClipboard (X11DRV.@)
2376 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2378 DWORD procid;
2379 Window owner;
2380 Display *display;
2382 TRACE(" %p\n", hWndClipWindow);
2385 * It's important that the selection get acquired from the thread
2386 * that owns the clipboard window. The primary reason is that we know
2387 * it is running a message loop and therefore can process the
2388 * X selection events.
2390 if (hWndClipWindow &&
2391 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2393 if (procid != GetCurrentProcessId())
2395 WARN("Setting clipboard owner to other process is not supported\n");
2396 hWndClipWindow = NULL;
2398 else
2400 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2401 GetCurrentThreadId(),
2402 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2404 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2408 owner = thread_selection_wnd();
2409 display = thread_display();
2411 wine_tsx11_lock();
2413 selectionAcquired = 0;
2414 selectionWindow = 0;
2416 /* Grab PRIMARY selection if not owned */
2417 if (use_primary_selection)
2418 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2420 /* Grab CLIPBOARD selection if not owned */
2421 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2423 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2424 selectionAcquired |= S_PRIMARY;
2426 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2427 selectionAcquired |= S_CLIPBOARD;
2429 wine_tsx11_unlock();
2431 if (selectionAcquired)
2433 selectionWindow = owner;
2434 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2437 return 1;
2441 /**************************************************************************
2442 * X11DRV_EmptyClipboard
2444 * Empty cached clipboard data.
2446 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2448 if (ClipData)
2450 LPWINE_CLIPDATA lpData, lpStart;
2451 LPWINE_CLIPDATA lpNext = ClipData;
2453 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2457 lpStart = ClipData;
2458 lpData = lpNext;
2459 lpNext = lpData->NextData;
2461 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2463 lpData->PrevData->NextData = lpData->NextData;
2464 lpData->NextData->PrevData = lpData->PrevData;
2466 if (lpData == ClipData)
2467 ClipData = lpNext != lpData ? lpNext : NULL;
2469 X11DRV_CLIPBOARD_FreeData(lpData);
2470 HeapFree(GetProcessHeap(), 0, lpData);
2472 ClipDataCount--;
2474 } while (lpNext != lpStart);
2477 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2482 /**************************************************************************
2483 * X11DRV_SetClipboardData
2485 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2487 DWORD flags = 0;
2488 BOOL bResult = TRUE;
2490 /* If it's not owned, data can only be set if the format data is not already owned
2491 and its rendering is not delayed */
2492 if (!owner)
2494 CLIPBOARDINFO cbinfo;
2495 LPWINE_CLIPDATA lpRender;
2497 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2499 if ((!hData16 && !hData32) ||
2500 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2501 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2502 bResult = FALSE;
2503 else
2504 flags = CF_FLAG_UNOWNED;
2507 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags, NULL, TRUE);
2509 return bResult;
2513 /**************************************************************************
2514 * CountClipboardFormats
2516 INT CDECL X11DRV_CountClipboardFormats(void)
2518 CLIPBOARDINFO cbinfo;
2520 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2522 TRACE(" count=%d\n", ClipDataCount);
2524 return ClipDataCount;
2528 /**************************************************************************
2529 * X11DRV_EnumClipboardFormats
2531 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2533 CLIPBOARDINFO cbinfo;
2534 UINT wNextFormat = 0;
2536 TRACE("(%04X)\n", wFormat);
2538 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2540 if (!wFormat)
2542 if (ClipData)
2543 wNextFormat = ClipData->wFormatID;
2545 else
2547 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2549 if (lpData && lpData->NextData != ClipData)
2550 wNextFormat = lpData->NextData->wFormatID;
2553 return wNextFormat;
2557 /**************************************************************************
2558 * X11DRV_IsClipboardFormatAvailable
2560 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2562 BOOL bRet = FALSE;
2563 CLIPBOARDINFO cbinfo;
2565 TRACE("(%04X)\n", wFormat);
2567 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2569 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2570 bRet = TRUE;
2572 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2574 return bRet;
2578 /**************************************************************************
2579 * GetClipboardData (USER.142)
2581 BOOL CDECL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2583 CLIPBOARDINFO cbinfo;
2584 LPWINE_CLIPDATA lpRender;
2586 TRACE("(%04X)\n", wFormat);
2588 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2590 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2592 if ( !lpRender->hData32 )
2593 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2595 /* Convert between 32 -> 16 bit data, if necessary */
2596 if (lpRender->hData32 && !lpRender->hData16)
2598 int size;
2600 if (lpRender->wFormatID == CF_METAFILEPICT)
2601 size = sizeof(METAFILEPICT16);
2602 else
2603 size = GlobalSize(lpRender->hData32);
2605 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2607 if (!lpRender->hData16)
2608 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2609 else
2611 if (lpRender->wFormatID == CF_METAFILEPICT)
2613 FIXME("\timplement function CopyMetaFilePict32to16\n");
2614 FIXME("\tin the appropriate file.\n");
2615 #ifdef SOMEONE_IMPLEMENTED_ME
2616 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2617 GlobalLock(lpRender->hData32));
2618 #endif
2620 else
2622 memcpy(GlobalLock16(lpRender->hData16),
2623 GlobalLock(lpRender->hData32), size);
2626 GlobalUnlock16(lpRender->hData16);
2627 GlobalUnlock(lpRender->hData32);
2631 /* Convert between 32 -> 16 bit data, if necessary */
2632 if (lpRender->hData16 && !lpRender->hData32)
2634 int size;
2636 if (lpRender->wFormatID == CF_METAFILEPICT)
2637 size = sizeof(METAFILEPICT16);
2638 else
2639 size = GlobalSize(lpRender->hData32);
2641 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2642 GMEM_DDESHARE, size);
2644 if (lpRender->wFormatID == CF_METAFILEPICT)
2646 FIXME("\timplement function CopyMetaFilePict16to32\n");
2647 FIXME("\tin the appropriate file.\n");
2648 #ifdef SOMEONE_IMPLEMENTED_ME
2649 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2650 GlobalLock(lpRender->hData16));
2651 #endif
2653 else
2655 memcpy(GlobalLock(lpRender->hData32),
2656 GlobalLock16(lpRender->hData16), size);
2659 GlobalUnlock(lpRender->hData32);
2660 GlobalUnlock16(lpRender->hData16);
2663 if (phData16)
2664 *phData16 = lpRender->hData16;
2666 if (phData32)
2667 *phData32 = lpRender->hData32;
2669 TRACE(" returning hData16(%04x) hData32(%p) (type %d)\n",
2670 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2672 return lpRender->hData16 || lpRender->hData32;
2675 return 0;
2679 /**************************************************************************
2680 * ResetSelectionOwner
2682 * Called when the thread owning the selection is destroyed and we need to
2683 * preserve the selection ownership. We look for another top level window
2684 * in this process and send it a message to acquire the selection.
2686 void X11DRV_ResetSelectionOwner(void)
2688 HWND hwnd;
2689 DWORD procid;
2691 TRACE("\n");
2693 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2694 return;
2696 selectionAcquired = S_NOSELECTION;
2697 selectionWindow = 0;
2699 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2702 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2704 if (GetCurrentProcessId() == procid)
2706 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2707 return;
2710 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2712 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2714 X11DRV_CLIPBOARD_ReleaseOwnership();
2715 X11DRV_EmptyClipboard(FALSE);
2719 /**************************************************************************
2720 * X11DRV_CLIPBOARD_SynthesizeData
2722 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2724 BOOL bsyn = TRUE;
2725 LPWINE_CLIPDATA lpSource = NULL;
2727 TRACE(" %d\n", wFormatID);
2729 /* Don't need to synthesize if it already exists */
2730 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2731 return TRUE;
2733 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2735 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2736 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2737 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2738 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2739 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2740 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2742 else if (wFormatID == CF_ENHMETAFILE)
2744 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2745 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2747 else if (wFormatID == CF_METAFILEPICT)
2749 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2750 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2752 else if (wFormatID == CF_DIB)
2754 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2755 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2757 else if (wFormatID == CF_BITMAP)
2759 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2760 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2763 if (bsyn)
2764 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2766 return bsyn;
2771 /**************************************************************************
2772 * X11DRV_EndClipboardUpdate
2773 * TODO:
2774 * Add locale if it hasn't already been added
2776 void CDECL X11DRV_EndClipboardUpdate(void)
2778 INT count = ClipDataCount;
2780 /* Do Unicode <-> Text <-> OEM mapping */
2781 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2782 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2783 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2785 /* Enhmetafile <-> MetafilePict mapping */
2786 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2787 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2789 /* DIB <-> Bitmap mapping */
2790 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2791 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2793 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2797 /***********************************************************************
2798 * X11DRV_SelectionRequest_TARGETS
2799 * Service a TARGETS selection request event
2801 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2802 Atom target, Atom rprop )
2804 UINT i;
2805 Atom* targets;
2806 ULONG cTargets;
2807 LPWINE_CLIPFORMAT lpFormats;
2808 LPWINE_CLIPDATA lpData;
2810 /* Create X atoms for any clipboard types which don't have atoms yet.
2811 * This avoids sending bogus zero atoms.
2812 * Without this, copying might not have access to all clipboard types.
2813 * FIXME: is it safe to call this here?
2815 intern_atoms();
2818 * Count the number of items we wish to expose as selection targets.
2820 cTargets = 1; /* Include TARGETS */
2822 if (!(lpData = ClipData)) return None;
2826 lpFormats = ClipFormats;
2828 while (lpFormats)
2830 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2831 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2832 cTargets++;
2834 lpFormats = lpFormats->NextFormat;
2837 lpData = lpData->NextData;
2839 while (lpData != ClipData);
2841 TRACE(" found %d formats\n", cTargets);
2843 /* Allocate temp buffer */
2844 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2845 if(targets == NULL)
2846 return None;
2848 i = 0;
2849 lpData = ClipData;
2850 targets[i++] = x11drv_atom(TARGETS);
2854 lpFormats = ClipFormats;
2856 while (lpFormats)
2858 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2859 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2860 targets[i++] = lpFormats->drvData;
2862 lpFormats = lpFormats->NextFormat;
2865 lpData = lpData->NextData;
2867 while (lpData != ClipData);
2869 wine_tsx11_lock();
2871 if (TRACE_ON(clipboard))
2873 unsigned int i;
2874 for ( i = 0; i < cTargets; i++)
2876 char *itemFmtName = XGetAtomName(display, targets[i]);
2877 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2878 XFree(itemFmtName);
2882 /* We may want to consider setting the type to xaTargets instead,
2883 * in case some apps expect this instead of XA_ATOM */
2884 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2885 PropModeReplace, (unsigned char *)targets, cTargets);
2886 wine_tsx11_unlock();
2888 HeapFree(GetProcessHeap(), 0, targets);
2890 return rprop;
2894 /***********************************************************************
2895 * X11DRV_SelectionRequest_MULTIPLE
2896 * Service a MULTIPLE selection request event
2897 * rprop contains a list of (target,property) atom pairs.
2898 * The first atom names a target and the second names a property.
2899 * The effect is as if we have received a sequence of SelectionRequest events
2900 * (one for each atom pair) except that:
2901 * 1. We reply with a SelectionNotify only when all the requested conversions
2902 * have been performed.
2903 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2904 * we replace the atom in the property by None.
2906 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2908 Display *display = pevent->display;
2909 Atom rprop;
2910 Atom atype=AnyPropertyType;
2911 int aformat;
2912 unsigned long remain;
2913 Atom* targetPropList=NULL;
2914 unsigned long cTargetPropList = 0;
2916 /* If the specified property is None the requestor is an obsolete client.
2917 * We support these by using the specified target atom as the reply property.
2919 rprop = pevent->property;
2920 if( rprop == None )
2921 rprop = pevent->target;
2922 if (!rprop)
2923 return 0;
2925 /* Read the MULTIPLE property contents. This should contain a list of
2926 * (target,property) atom pairs.
2928 wine_tsx11_lock();
2929 if(XGetWindowProperty(display, pevent->requestor, rprop,
2930 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2931 &cTargetPropList, &remain,
2932 (unsigned char**)&targetPropList) != Success)
2934 wine_tsx11_unlock();
2935 TRACE("\tCouldn't read MULTIPLE property\n");
2937 else
2939 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2940 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2941 wine_tsx11_unlock();
2944 * Make sure we got what we expect.
2945 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2946 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2947 * However some X apps(such as XPaint) are not compliant with this and return
2948 * a user defined atom in atype when XGetWindowProperty is called.
2949 * The data *is* an atom pair but is not denoted as such.
2951 if(aformat == 32 /* atype == xAtomPair */ )
2953 unsigned int i;
2955 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2956 * for each (target,property) pair */
2958 for (i = 0; i < cTargetPropList; i+=2)
2960 XSelectionRequestEvent event;
2962 if (TRACE_ON(clipboard))
2964 char *targetName, *propName;
2965 wine_tsx11_lock();
2966 targetName = XGetAtomName(display, targetPropList[i]);
2967 propName = XGetAtomName(display, targetPropList[i+1]);
2968 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
2969 i/2, targetName, propName);
2970 XFree(targetName);
2971 XFree(propName);
2972 wine_tsx11_unlock();
2975 /* We must have a non "None" property to service a MULTIPLE target atom */
2976 if ( !targetPropList[i+1] )
2978 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
2979 continue;
2982 /* Set up an XSelectionRequestEvent for this (target,property) pair */
2983 event = *pevent;
2984 event.target = targetPropList[i];
2985 event.property = targetPropList[i+1];
2987 /* Fire a SelectionRequest, informing the handler that we are processing
2988 * a MULTIPLE selection request event.
2990 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
2994 /* Free the list of targets/properties */
2995 wine_tsx11_lock();
2996 XFree(targetPropList);
2997 wine_tsx11_unlock();
3000 return rprop;
3004 /***********************************************************************
3005 * X11DRV_HandleSelectionRequest
3006 * Process an event selection request event.
3007 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3008 * recursively while servicing a "MULTIPLE" selection target.
3010 * Note: We only receive this event when WINE owns the X selection
3012 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3014 Display *display = event->display;
3015 XSelectionEvent result;
3016 Atom rprop = None;
3017 Window request = event->requestor;
3019 TRACE("\n");
3022 * We can only handle the selection request if :
3023 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3024 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3025 * since this has been already done.
3027 if ( !bIsMultiple )
3029 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3030 goto END;
3033 /* If the specified property is None the requestor is an obsolete client.
3034 * We support these by using the specified target atom as the reply property.
3036 rprop = event->property;
3037 if( rprop == None )
3038 rprop = event->target;
3040 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3042 /* TARGETS selection request */
3043 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3045 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3047 /* MULTIPLE selection request */
3048 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3050 else
3052 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3054 if (lpFormat && lpFormat->lpDrvExportFunc)
3056 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3058 if (lpData)
3060 unsigned char* lpClipData;
3061 DWORD cBytes;
3062 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3063 rprop, lpData, &cBytes);
3065 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3067 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
3069 wine_tsx11_lock();
3070 XChangeProperty(display, request, rprop, event->target,
3071 8, PropModeReplace, lpClipData, cBytes);
3072 wine_tsx11_unlock();
3074 GlobalUnlock(hClipData);
3075 GlobalFree(hClipData);
3081 END:
3082 /* reply to sender
3083 * SelectionNotify should be sent only at the end of a MULTIPLE request
3085 if ( !bIsMultiple )
3087 result.type = SelectionNotify;
3088 result.display = display;
3089 result.requestor = request;
3090 result.selection = event->selection;
3091 result.property = rprop;
3092 result.target = event->target;
3093 result.time = event->time;
3094 TRACE("Sending SelectionNotify event...\n");
3095 wine_tsx11_lock();
3096 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3097 wine_tsx11_unlock();
3102 /***********************************************************************
3103 * X11DRV_SelectionRequest
3105 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3107 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3111 /***********************************************************************
3112 * X11DRV_SelectionClear
3114 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3116 XSelectionClearEvent *event = &xev->xselectionclear;
3117 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3118 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3119 event->window, hWnd, event->time );