programs/wcmd: Rename to programs/cmd.
[wine.git] / dlls / winex11.drv / clipboard.c
blob8631b6083a9c595d7c7aedc8febe57b988c9ec56
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 "winreg.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)(Window requestor, Atom aTarget, Atom rprop,
114 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
115 typedef HANDLE (*DRVIMPORTFUNC)(Window w, Atom prop);
117 typedef struct tagWINE_CLIPFORMAT {
118 UINT wFormatID;
119 LPCWSTR Name;
120 UINT drvData;
121 UINT wFlags;
122 DRVIMPORTFUNC lpDrvImportFunc;
123 DRVEXPORTFUNC lpDrvExportFunc;
124 struct tagWINE_CLIPFORMAT *PrevFormat;
125 struct tagWINE_CLIPFORMAT *NextFormat;
126 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
128 typedef struct tagWINE_CLIPDATA {
129 UINT wFormatID;
130 HANDLE16 hData16;
131 HANDLE hData32;
132 UINT wFlags;
133 UINT drvData;
134 LPWINE_CLIPFORMAT lpFormat;
135 struct tagWINE_CLIPDATA *PrevData;
136 struct tagWINE_CLIPDATA *NextData;
137 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
139 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
140 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
141 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
142 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
144 static int selectionAcquired = 0; /* Contains the current selection masks */
145 static Window selectionWindow = None; /* The top level X window which owns the selection */
146 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
148 void X11DRV_EmptyClipboard(BOOL keepunowned);
149 void X11DRV_EndClipboardUpdate(void);
150 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Window w, Atom prop);
157 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
158 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
159 static HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget,
160 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
161 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget,
162 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
163 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget,
164 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
165 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(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(UINT wFormatID);
169 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
170 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
171 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo);
172 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(LPWINE_CLIPDATA lpData);
173 static BOOL X11DRV_CLIPBOARD_ReadProperty(Window w, Atom prop,
174 unsigned char** data, unsigned long* datasize);
175 static BOOL X11DRV_CLIPBOARD_RenderFormat(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(LPWINE_CLIPDATA lpData);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(void);
180 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(void);
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 WCHAR wszRICHHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
291 static const struct
293 LPCWSTR lpszFormat;
294 UINT prop;
295 } PropertyFormatMap[] =
297 { wszRichTextFormat, XATOM_text_rtf },
298 { wszRichTextFormat, XATOM_text_richtext },
299 { wszGIF, XATOM_image_gif },
300 { wszHTMLFormat, XATOM_text_html },
304 /* Maps equivalent X properties. It is assumed that lpszProperty must already
305 be in ClipFormats or PropertyFormatMap. */
306 static const struct
308 UINT drvDataProperty;
309 UINT drvDataAlias;
310 } PropertyAliasMap[] =
312 /* DataProperty, DataAlias */
317 * Cached clipboard data.
319 static LPWINE_CLIPDATA ClipData = NULL;
320 static UINT ClipDataCount = 0;
323 * Clipboard sequence number
325 static UINT wSeqNo = 0;
327 /**************************************************************************
328 * Internal Clipboard implementation methods
329 **************************************************************************/
331 static Window thread_selection_wnd(void)
333 Window w = x11drv_thread_data()->selection_wnd;
335 if (!w)
337 XSetWindowAttributes attr;
339 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
340 ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
342 wine_tsx11_lock();
343 w = XCreateWindow(thread_display(), root_window, 0, 0, 1, 1, 0, screen_depth,
344 InputOutput, CopyFromParent, CWEventMask, &attr);
345 wine_tsx11_unlock();
347 if (w)
348 x11drv_thread_data()->selection_wnd = w;
349 else
350 FIXME("Failed to create window. Fetching selection data will fail.\n");
353 return w;
356 /**************************************************************************
357 * X11DRV_InitClipboard
359 void X11DRV_InitClipboard(void)
361 UINT i;
363 /* Register known mapping between window formats and X properties */
364 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
365 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
369 /**************************************************************************
370 * intern_atoms
372 * Intern atoms for formats that don't have one yet.
374 static void intern_atoms(void)
376 LPWINE_CLIPFORMAT format;
377 int i, count, len;
378 char **names;
379 Atom *atoms;
381 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
382 if (!format->drvData) count++;
383 if (!count) return;
385 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
386 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
388 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
389 if (!format->drvData) {
390 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
391 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
392 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
396 wine_tsx11_lock();
397 XInternAtoms( thread_display(), names, count, False, atoms );
398 wine_tsx11_unlock();
400 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
401 if (!format->drvData) {
402 HeapFree(GetProcessHeap(), 0, names[i]);
403 format->drvData = atoms[i++];
407 HeapFree( GetProcessHeap(), 0, names );
408 HeapFree( GetProcessHeap(), 0, atoms );
412 /**************************************************************************
413 * register_format
415 * Register a custom X clipboard format.
417 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
419 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
421 TRACE("%s\n", debugstr_w(FormatName));
423 /* walk format chain to see if it's already registered */
424 while (lpFormat)
426 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
427 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
428 return lpFormat;
429 lpFormat = lpFormat->NextFormat;
432 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
436 /**************************************************************************
437 * X11DRV_CLIPBOARD_LookupFormat
439 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
441 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
443 while(lpFormat)
445 if (lpFormat->wFormatID == wID)
446 break;
448 lpFormat = lpFormat->NextFormat;
450 if (lpFormat && !lpFormat->drvData) intern_atoms();
451 return lpFormat;
455 /**************************************************************************
456 * X11DRV_CLIPBOARD_LookupProperty
458 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
460 for (;;)
462 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
463 BOOL need_intern = FALSE;
465 if (current)
466 lpFormat = current->NextFormat;
468 while(lpFormat)
470 if (lpFormat->drvData == drvData) return lpFormat;
471 if (!lpFormat->drvData) need_intern = TRUE;
472 lpFormat = lpFormat->NextFormat;
474 if (!need_intern) return NULL;
475 intern_atoms();
476 /* restart the search for the new atoms */
481 /**************************************************************************
482 * X11DRV_CLIPBOARD_LookupData
484 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
486 LPWINE_CLIPDATA lpData = ClipData;
488 if (lpData)
492 if (lpData->wFormatID == wID)
493 break;
495 lpData = lpData->NextData;
497 while(lpData != ClipData);
499 if (lpData->wFormatID != wID)
500 lpData = NULL;
503 return lpData;
507 /**************************************************************************
508 * InsertClipboardFormat
510 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
512 LPWINE_CLIPFORMAT lpFormat;
513 LPWINE_CLIPFORMAT lpNewFormat;
515 /* allocate storage for new format entry */
516 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
518 if(lpNewFormat == NULL)
520 WARN("No more memory for a new format!\n");
521 return NULL;
524 if (!(lpNewFormat->Name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
526 WARN("No more memory for the new format name!\n");
527 HeapFree(GetProcessHeap(), 0, lpNewFormat);
528 return NULL;
531 strcpyW((LPWSTR)lpNewFormat->Name, FormatName);
532 lpNewFormat->wFlags = 0;
533 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
534 lpNewFormat->drvData = prop;
535 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
536 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
538 /* Link Format */
539 lpFormat = ClipFormats;
541 while(lpFormat->NextFormat) /* Move to last entry */
542 lpFormat = lpFormat->NextFormat;
544 lpNewFormat->NextFormat = NULL;
545 lpFormat->NextFormat = lpNewFormat;
546 lpNewFormat->PrevFormat = lpFormat;
548 TRACE("Registering format(%d): %s drvData %d\n",
549 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
551 return lpNewFormat;
557 /**************************************************************************
558 * X11DRV_CLIPBOARD_GetClipboardInfo
560 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
562 BOOL bRet = FALSE;
564 SERVER_START_REQ( set_clipboard_info )
566 req->flags = 0;
568 if (wine_server_call_err( req ))
570 ERR("Failed to get clipboard owner.\n");
572 else
574 cbInfo->hWndOpen = reply->old_clipboard;
575 cbInfo->hWndOwner = reply->old_owner;
576 cbInfo->hWndViewer = reply->old_viewer;
577 cbInfo->seqno = reply->seqno;
578 cbInfo->flags = reply->flags;
580 bRet = TRUE;
583 SERVER_END_REQ;
585 return bRet;
589 /**************************************************************************
590 * X11DRV_CLIPBOARD_ReleaseOwnership
592 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
594 BOOL bRet = FALSE;
596 SERVER_START_REQ( set_clipboard_info )
598 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
600 if (wine_server_call_err( req ))
602 ERR("Failed to set clipboard.\n");
604 else
606 bRet = TRUE;
609 SERVER_END_REQ;
611 return bRet;
616 /**************************************************************************
617 * X11DRV_CLIPBOARD_InsertClipboardData
619 * Caller *must* have the clipboard open and be the owner.
621 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
622 HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
624 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
626 TRACE("format=%d lpData=%p hData16=%08x hData32=%p flags=0x%08lx lpFormat=%p override=%d\n",
627 wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
629 if (lpData && !override)
630 return TRUE;
632 if (lpData)
634 X11DRV_CLIPBOARD_FreeData(lpData);
636 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
637 lpData->hData32 = hData32;
639 else
641 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
643 lpData->wFormatID = wFormatID;
644 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
645 lpData->hData32 = hData32;
646 lpData->lpFormat = lpFormat;
647 lpData->drvData = 0;
649 if (ClipData)
651 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
653 lpData->PrevData = lpPrevData;
654 lpData->NextData = ClipData;
656 lpPrevData->NextData = lpData;
657 ClipData->PrevData = lpData;
659 else
661 lpData->NextData = lpData;
662 lpData->PrevData = lpData;
663 ClipData = lpData;
666 ClipDataCount++;
669 lpData->wFlags = flags;
671 return TRUE;
675 /**************************************************************************
676 * X11DRV_CLIPBOARD_FreeData
678 * Free clipboard data handle.
680 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
682 TRACE("%d\n", lpData->wFormatID);
684 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
685 lpData->wFormatID <= CF_GDIOBJLAST) ||
686 lpData->wFormatID == CF_BITMAP ||
687 lpData->wFormatID == CF_DIB ||
688 lpData->wFormatID == CF_PALETTE)
690 if (lpData->hData32)
691 DeleteObject(lpData->hData32);
693 if (lpData->hData16)
694 DeleteObject(HGDIOBJ_32(lpData->hData16));
696 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
697 XFreePixmap(gdi_display, lpData->drvData);
699 else if (lpData->wFormatID == CF_METAFILEPICT)
701 if (lpData->hData32)
703 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
704 GlobalFree(lpData->hData32);
706 if (lpData->hData16)
707 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
708 and a shallow copy is enough to share a METAFILEPICT
709 structure between 16bit and 32bit clipboards. The MetaFile
710 should of course only be deleted once. */
711 GlobalFree16(lpData->hData16);
714 if (lpData->hData16)
716 METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
718 if (lpMetaPict)
720 /* To delete 16-bit meta file, we just need to free the associated
721 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
722 GlobalFree16(lpMetaPict->hMF);
723 lpMetaPict->hMF = 0;
726 GlobalFree16(lpData->hData16);
729 else if (lpData->wFormatID == CF_ENHMETAFILE)
731 if (lpData->hData32)
732 DeleteEnhMetaFile(lpData->hData32);
734 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
735 lpData->wFormatID > CF_PRIVATELAST)
737 if (lpData->hData32)
738 GlobalFree(lpData->hData32);
740 if (lpData->hData16)
741 GlobalFree16(lpData->hData16);
744 lpData->hData16 = 0;
745 lpData->hData32 = 0;
746 lpData->drvData = 0;
750 /**************************************************************************
751 * X11DRV_CLIPBOARD_UpdateCache
753 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
755 BOOL bret = TRUE;
757 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
759 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
761 ERR("Failed to retrieve clipboard information.\n");
762 bret = FALSE;
764 else if (wSeqNo < lpcbinfo->seqno)
766 X11DRV_EmptyClipboard(TRUE);
768 if (X11DRV_CLIPBOARD_QueryAvailableData(lpcbinfo) < 0)
770 ERR("Failed to cache clipboard data owned by another process.\n");
771 bret = FALSE;
773 else
775 X11DRV_EndClipboardUpdate();
778 wSeqNo = lpcbinfo->seqno;
782 return bret;
786 /**************************************************************************
787 * X11DRV_CLIPBOARD_RenderFormat
789 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData)
791 BOOL bret = TRUE;
793 TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
794 lpData->wFormatID, lpData->hData32, lpData->hData16);
796 if (lpData->hData32 || lpData->hData16)
797 return bret; /* Already rendered */
799 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
800 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(lpData);
801 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
803 if (!X11DRV_CLIPBOARD_ReadSelectionData(lpData))
805 ERR("Failed to cache clipboard data owned by another process. Format=%d\n",
806 lpData->wFormatID);
807 bret = FALSE;
810 else
812 CLIPBOARDINFO cbInfo;
814 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
816 /* Send a WM_RENDERFORMAT message to notify the owner to render the
817 * data requested into the clipboard.
819 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
820 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
822 if (!lpData->hData32 && !lpData->hData16)
823 bret = FALSE;
825 else
827 ERR("hWndClipOwner is lost!\n");
828 bret = FALSE;
832 return bret;
836 /**************************************************************************
837 * CLIPBOARD_ConvertText
838 * Returns number of required/converted characters - not bytes!
840 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
841 WORD dst_fmt, void *dst, INT dst_size)
843 UINT cp;
845 if(src_fmt == CF_UNICODETEXT)
847 switch(dst_fmt)
849 case CF_TEXT:
850 cp = CP_ACP;
851 break;
852 case CF_OEMTEXT:
853 cp = CP_OEMCP;
854 break;
855 default:
856 return 0;
858 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
861 if(dst_fmt == CF_UNICODETEXT)
863 switch(src_fmt)
865 case CF_TEXT:
866 cp = CP_ACP;
867 break;
868 case CF_OEMTEXT:
869 cp = CP_OEMCP;
870 break;
871 default:
872 return 0;
874 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
877 if(!dst_size) return src_size;
879 if(dst_size > src_size) dst_size = src_size;
881 if(src_fmt == CF_TEXT )
882 CharToOemBuffA(src, dst, dst_size);
883 else
884 OemToCharBuffA(src, dst, dst_size);
886 return dst_size;
890 /**************************************************************************
891 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
893 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData)
895 BOOL bret = FALSE;
897 TRACE("\n");
899 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
901 UINT wFormatID = lpData->wFormatID;
903 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
904 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(wFormatID);
905 else
907 switch (wFormatID)
909 case CF_DIB:
910 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB();
911 break;
913 case CF_BITMAP:
914 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap();
915 break;
917 case CF_ENHMETAFILE:
918 case CF_METAFILEPICT:
919 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
920 break;
922 default:
923 FIXME("Called to synthesize unknown format\n");
924 break;
928 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
931 return bret;
935 /**************************************************************************
936 * X11DRV_CLIPBOARD_RenderSynthesizedText
938 * Renders synthesized text
940 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID)
942 LPCSTR lpstrS;
943 LPSTR lpstrT;
944 HANDLE hData32;
945 INT src_chars, dst_chars, alloc_size;
946 LPWINE_CLIPDATA lpSource = NULL;
948 TRACE(" %d\n", wFormatID);
950 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
951 lpSource->hData32)
952 return TRUE;
954 /* Look for rendered source or non-synthesized source */
955 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
956 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
958 TRACE("UNICODETEXT -> %d\n", wFormatID);
960 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
961 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
963 TRACE("TEXT -> %d\n", wFormatID);
965 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
966 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
968 TRACE("OEMTEXT -> %d\n", wFormatID);
971 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
972 !lpSource->hData32))
973 return FALSE;
975 /* Ask the clipboard owner to render the source text if necessary */
976 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(lpSource))
977 return FALSE;
979 if (lpSource->hData32)
981 lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
983 else
985 lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
988 if (!lpstrS)
989 return FALSE;
991 /* Text always NULL terminated */
992 if(lpSource->wFormatID == CF_UNICODETEXT)
993 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
994 else
995 src_chars = strlen(lpstrS) + 1;
997 /* Calculate number of characters in the destination buffer */
998 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
999 src_chars, wFormatID, NULL, 0);
1001 if (!dst_chars)
1002 return FALSE;
1004 TRACE("Converting from '%d' to '%d', %i chars\n",
1005 lpSource->wFormatID, wFormatID, src_chars);
1007 /* Convert characters to bytes */
1008 if(wFormatID == CF_UNICODETEXT)
1009 alloc_size = dst_chars * sizeof(WCHAR);
1010 else
1011 alloc_size = dst_chars;
1013 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1014 GMEM_DDESHARE, alloc_size);
1016 lpstrT = (LPSTR)GlobalLock(hData32);
1018 if (lpstrT)
1020 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1021 wFormatID, lpstrT, dst_chars);
1022 GlobalUnlock(hData32);
1025 /* Unlock source */
1026 if (lpSource->hData32)
1027 GlobalUnlock(lpSource->hData32);
1028 else
1029 GlobalUnlock16(lpSource->hData16);
1031 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1035 /**************************************************************************
1036 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1038 * Renders synthesized DIB
1040 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB()
1042 BOOL bret = FALSE;
1043 LPWINE_CLIPDATA lpSource = NULL;
1045 TRACE("\n");
1047 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1049 bret = TRUE;
1051 /* If we have a bitmap and it's not synthesized or it has been rendered */
1052 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1053 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1055 /* Render source if required */
1056 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1058 HDC hdc;
1059 HGLOBAL hData32;
1061 hdc = GetDC(NULL);
1062 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1063 ReleaseDC(NULL, hdc);
1065 if (hData32)
1067 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1068 bret = TRUE;
1073 return bret;
1077 /**************************************************************************
1078 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1080 * Renders synthesized bitmap
1082 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap()
1084 BOOL bret = FALSE;
1085 LPWINE_CLIPDATA lpSource = NULL;
1087 TRACE("\n");
1089 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1091 bret = TRUE;
1093 /* If we have a dib and it's not synthesized or it has been rendered */
1094 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1095 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1097 /* Render source if required */
1098 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1100 HDC hdc;
1101 HBITMAP hData32;
1102 unsigned int offset;
1103 LPBITMAPINFOHEADER lpbmih;
1105 hdc = GetDC(NULL);
1106 lpbmih = (LPBITMAPINFOHEADER) GlobalLock(lpSource->hData32);
1108 offset = sizeof(BITMAPINFOHEADER)
1109 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1110 (1 << lpbmih->biBitCount)) : 0);
1112 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1113 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1115 GlobalUnlock(lpSource->hData32);
1116 ReleaseDC(NULL, hdc);
1118 if (hData32)
1120 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1121 bret = TRUE;
1126 return bret;
1130 /**************************************************************************
1131 * X11DRV_CLIPBOARD_ImportXAString
1133 * Import XA_STRING, converting the string to CF_TEXT.
1135 HANDLE X11DRV_CLIPBOARD_ImportXAString(Window w, Atom prop)
1137 LPBYTE lpdata;
1138 unsigned long cbytes;
1139 LPSTR lpstr;
1140 unsigned long i, inlcount = 0;
1141 HANDLE hText = 0;
1143 if (!X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1144 return 0;
1146 for (i = 0; i <= cbytes; i++)
1148 if (lpdata[i] == '\n')
1149 inlcount++;
1152 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1154 lpstr = GlobalLock(hText);
1156 for (i = 0, inlcount = 0; i <= cbytes; i++)
1158 if (lpdata[i] == '\n')
1159 lpstr[inlcount++] = '\r';
1161 lpstr[inlcount++] = lpdata[i];
1164 GlobalUnlock(hText);
1167 /* Free the retrieved property data */
1168 HeapFree(GetProcessHeap(), 0, lpdata);
1170 return hText;
1174 /**************************************************************************
1175 * X11DRV_CLIPBOARD_ImportUTF8
1177 * Import XA_STRING, converting the string to CF_UNICODE.
1179 HANDLE X11DRV_CLIPBOARD_ImportUTF8(Window w, Atom prop)
1181 LPBYTE lpdata;
1182 unsigned long cbytes;
1183 LPSTR lpstr;
1184 unsigned long i, inlcount = 0;
1185 HANDLE hUnicodeText = 0;
1187 if (!X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1188 return 0;
1190 for (i = 0; i <= cbytes; i++)
1192 if (lpdata[i] == '\n')
1193 inlcount++;
1196 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1198 UINT count;
1200 for (i = 0, inlcount = 0; i <= cbytes; i++)
1202 if (lpdata[i] == '\n')
1203 lpstr[inlcount++] = '\r';
1205 lpstr[inlcount++] = lpdata[i];
1208 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1209 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1211 if (hUnicodeText)
1213 WCHAR *textW = GlobalLock(hUnicodeText);
1214 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1215 GlobalUnlock(hUnicodeText);
1218 HeapFree(GetProcessHeap(), 0, lpstr);
1221 /* Free the retrieved property data */
1222 HeapFree(GetProcessHeap(), 0, lpdata);
1224 return hUnicodeText;
1228 /**************************************************************************
1229 * X11DRV_CLIPBOARD_ImportCompoundText
1231 * Import COMPOUND_TEXT to CF_UNICODE
1233 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Window w, Atom prop)
1235 Display *display = thread_display();
1236 int i, j;
1237 char** srcstr;
1238 int count, lcount;
1239 int srclen, destlen;
1240 HANDLE hUnicodeText;
1241 XTextProperty txtprop;
1243 wine_tsx11_lock();
1244 if (!XGetTextProperty(display, w, &txtprop, prop))
1246 wine_tsx11_unlock();
1247 return 0;
1250 XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1251 wine_tsx11_unlock();
1253 TRACE("Importing %d line(s)\n", count);
1255 /* Compute number of lines */
1256 srclen = strlen(srcstr[0]);
1257 for (i = 0, lcount = 0; i <= srclen; i++)
1259 if (srcstr[0][i] == '\n')
1260 lcount++;
1263 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1265 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1267 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1269 WCHAR *deststr = GlobalLock(hUnicodeText);
1270 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1272 if (lcount)
1274 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1276 deststr[j] = deststr[i];
1278 if (deststr[i] == '\n')
1279 deststr[--j] = '\r';
1283 GlobalUnlock(hUnicodeText);
1286 wine_tsx11_lock();
1287 XFreeStringList(srcstr);
1288 XFree(txtprop.value);
1289 wine_tsx11_unlock();
1291 return hUnicodeText;
1295 /**************************************************************************
1296 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1298 * Import XA_PIXMAP, converting the image to CF_DIB.
1300 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Window w, Atom prop)
1302 HWND hwnd;
1303 HDC hdc;
1304 LPBYTE lpdata;
1305 unsigned long cbytes;
1306 Pixmap *pPixmap;
1307 HANDLE hClipData = 0;
1309 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1311 pPixmap = (Pixmap *) lpdata;
1313 hwnd = GetOpenClipboardWindow();
1314 hdc = GetDC(hwnd);
1316 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1317 ReleaseDC(hwnd, hdc);
1319 /* Free the retrieved property data */
1320 HeapFree(GetProcessHeap(), 0, lpdata);
1323 return hClipData;
1327 /**************************************************************************
1328 * X11DRV_CLIPBOARD_ImportMetaFilePict
1330 * Import MetaFilePict.
1332 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Window w, Atom prop)
1334 LPBYTE lpdata;
1335 unsigned long cbytes;
1336 HANDLE hClipData = 0;
1338 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1340 if (cbytes)
1341 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1343 /* Free the retrieved property data */
1344 HeapFree(GetProcessHeap(), 0, lpdata);
1347 return hClipData;
1351 /**************************************************************************
1352 * X11DRV_ImportEnhMetaFile
1354 * Import EnhMetaFile.
1356 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Window w, Atom prop)
1358 LPBYTE lpdata;
1359 unsigned long cbytes;
1360 HANDLE hClipData = 0;
1362 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1364 if (cbytes)
1365 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1367 /* Free the retrieved property data */
1368 HeapFree(GetProcessHeap(), 0, lpdata);
1371 return hClipData;
1375 /**************************************************************************
1376 * X11DRV_ImportClipbordaData
1378 * Generic import clipboard data routine.
1380 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Window w, Atom prop)
1382 LPVOID lpClipData;
1383 LPBYTE lpdata;
1384 unsigned long cbytes;
1385 HANDLE hClipData = 0;
1387 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1389 if (cbytes)
1391 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1392 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1393 if (hClipData == 0)
1394 return NULL;
1396 if ((lpClipData = GlobalLock(hClipData)))
1398 memcpy(lpClipData, lpdata, cbytes);
1399 GlobalUnlock(hClipData);
1401 else
1403 GlobalFree(hClipData);
1404 hClipData = 0;
1408 /* Free the retrieved property data */
1409 HeapFree(GetProcessHeap(), 0, lpdata);
1412 return hClipData;
1416 /**************************************************************************
1417 X11DRV_CLIPBOARD_ExportClipboardData
1419 * Generic export clipboard data routine.
1421 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
1422 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1424 LPVOID lpClipData;
1425 UINT datasize = 0;
1426 HANDLE hClipData = 0;
1428 *lpBytes = 0; /* Assume failure */
1430 if (!X11DRV_CLIPBOARD_RenderFormat(lpData))
1431 ERR("Failed to export %d format\n", lpData->wFormatID);
1432 else
1434 datasize = GlobalSize(lpData->hData32);
1436 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1437 if (hClipData == 0) return NULL;
1439 if ((lpClipData = GlobalLock(hClipData)))
1441 LPVOID lpdata = GlobalLock(lpData->hData32);
1443 memcpy(lpClipData, lpdata, datasize);
1444 *lpBytes = datasize;
1446 GlobalUnlock(lpData->hData32);
1447 GlobalUnlock(hClipData);
1448 } else {
1449 GlobalFree(hClipData);
1450 hClipData = 0;
1454 return hClipData;
1458 /**************************************************************************
1459 * X11DRV_CLIPBOARD_ExportXAString
1461 * Export CF_TEXT converting the string to XA_STRING.
1462 * Helper function for X11DRV_CLIPBOARD_ExportString.
1464 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1466 UINT i, j;
1467 UINT size;
1468 LPSTR text, lpstr = NULL;
1470 *lpBytes = 0; /* Assume return has zero bytes */
1472 text = GlobalLock(lpData->hData32);
1473 size = strlen(text);
1475 /* remove carriage returns */
1476 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1477 if (lpstr == NULL)
1478 goto done;
1480 for (i = 0,j = 0; i < size && text[i]; i++)
1482 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1483 continue;
1484 lpstr[j++] = text[i];
1487 lpstr[j]='\0';
1488 *lpBytes = j; /* Number of bytes in string */
1490 done:
1491 HeapFree(GetProcessHeap(), 0, text);
1492 GlobalUnlock(lpData->hData32);
1494 return lpstr;
1498 /**************************************************************************
1499 * X11DRV_CLIPBOARD_ExportUTF8String
1501 * Export CF_UNICODE converting the string to UTF8.
1502 * Helper function for X11DRV_CLIPBOARD_ExportString.
1504 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1506 UINT i, j;
1507 UINT size;
1508 LPWSTR uni_text;
1509 LPSTR text, lpstr = NULL;
1511 *lpBytes = 0; /* Assume return has zero bytes */
1513 uni_text = GlobalLock(lpData->hData32);
1515 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1517 text = HeapAlloc(GetProcessHeap(), 0, size);
1518 if (!text)
1519 goto done;
1520 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1522 /* remove carriage returns */
1523 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1524 if (lpstr == NULL)
1525 goto done;
1527 for (i = 0,j = 0; i < size && text[i]; i++)
1529 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1530 continue;
1531 lpstr[j++] = text[i];
1533 lpstr[j]='\0';
1535 *lpBytes = j; /* Number of bytes in string */
1537 done:
1538 HeapFree(GetProcessHeap(), 0, text);
1539 GlobalUnlock(lpData->hData32);
1541 return lpstr;
1546 /**************************************************************************
1547 * X11DRV_CLIPBOARD_ExportCompoundText
1549 * Export CF_UNICODE to COMPOUND_TEXT
1550 * Helper function for X11DRV_CLIPBOARD_ExportString.
1552 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Window requestor, Atom aTarget, Atom rprop,
1553 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1555 Display *display = thread_display();
1556 char* lpstr = 0;
1557 XTextProperty prop;
1558 XICCEncodingStyle style;
1559 UINT i, j;
1560 UINT size;
1561 LPWSTR uni_text;
1563 uni_text = GlobalLock(lpData->hData32);
1565 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1566 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1567 if (!lpstr)
1568 return 0;
1570 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1572 /* remove carriage returns */
1573 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1575 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1576 continue;
1577 lpstr[j++] = lpstr[i];
1579 lpstr[j]='\0';
1581 GlobalUnlock(lpData->hData32);
1583 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1584 style = XCompoundTextStyle;
1585 else
1586 style = XStdICCTextStyle;
1588 /* Update the X property */
1589 wine_tsx11_lock();
1590 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1592 XSetTextProperty(display, requestor, &prop, rprop);
1593 XFree(prop.value);
1595 wine_tsx11_unlock();
1597 HeapFree(GetProcessHeap(), 0, lpstr);
1599 return 0;
1602 /**************************************************************************
1603 * X11DRV_CLIPBOARD_ExportString
1605 * Export string
1607 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget, Atom rprop,
1608 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1610 if (X11DRV_CLIPBOARD_RenderFormat(lpData))
1612 if (aTarget == XA_STRING)
1613 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1614 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1615 return X11DRV_CLIPBOARD_ExportCompoundText(requestor, aTarget,
1616 rprop, lpData, lpBytes);
1617 else
1619 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1620 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1623 else
1624 ERR("Failed to render %d format\n", lpData->wFormatID);
1626 return 0;
1630 /**************************************************************************
1631 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1633 * Export CF_DIB to XA_PIXMAP.
1635 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget, Atom rprop,
1636 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1638 HDC hdc;
1639 HANDLE hData;
1640 unsigned char* lpData;
1642 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1644 ERR("Failed to export %d format\n", lpdata->wFormatID);
1645 return 0;
1648 if (!lpdata->drvData) /* If not already rendered */
1650 /* For convert from packed DIB to Pixmap */
1651 hdc = GetDC(0);
1652 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1653 ReleaseDC(0, hdc);
1656 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1658 /* Wrap pixmap so we can return a handle */
1659 hData = GlobalAlloc(0, *lpBytes);
1660 lpData = GlobalLock(hData);
1661 memcpy(lpData, &lpdata->drvData, *lpBytes);
1662 GlobalUnlock(hData);
1664 return (HANDLE) hData;
1668 /**************************************************************************
1669 * X11DRV_CLIPBOARD_ExportMetaFilePict
1671 * Export MetaFilePict.
1673 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget, Atom rprop,
1674 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1676 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1678 ERR("Failed to export %d format\n", lpdata->wFormatID);
1679 return 0;
1682 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata->hData32,
1683 lpBytes, TRUE);
1687 /**************************************************************************
1688 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1690 * Export EnhMetaFile.
1692 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget, Atom rprop,
1693 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1695 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1697 ERR("Failed to export %d format\n", lpdata->wFormatID);
1698 return 0;
1701 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata->hData32,
1702 lpBytes, TRUE);
1706 /**************************************************************************
1707 * X11DRV_CLIPBOARD_QueryTargets
1709 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1710 Atom target, XEvent *xe)
1712 INT i;
1713 Bool res;
1715 wine_tsx11_lock();
1716 XConvertSelection(display, selection, target,
1717 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1718 wine_tsx11_unlock();
1721 * Wait until SelectionNotify is received
1723 for (i = 0; i < SELECTION_RETRIES; i++)
1725 wine_tsx11_lock();
1726 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1727 wine_tsx11_unlock();
1728 if (res && xe->xselection.selection == selection) break;
1730 usleep(SELECTION_WAIT);
1733 /* Verify that the selection returned a valid TARGETS property */
1734 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1736 /* Selection owner failed to respond or we missed the SelectionNotify */
1737 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1738 return FALSE;
1741 return TRUE;
1745 /**************************************************************************
1746 * X11DRV_CLIPBOARD_InsertSelectionProperties
1748 * Mark properties available for future retrieval.
1750 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1752 UINT i, nb_atoms = 0;
1753 Atom *atoms = NULL;
1755 /* Cache these formats in the clipboard cache */
1756 for (i = 0; i < count; i++)
1758 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1760 if (lpFormat)
1762 /* We found at least one Window's format that mapps to the property.
1763 * Continue looking for more.
1765 * If more than one property map to a Window's format then we use the first
1766 * one and ignore the rest.
1768 while (lpFormat)
1770 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1771 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1772 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1773 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1776 else
1778 /* add it to the list of atoms that we don't know about yet */
1779 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1780 (count - i) * sizeof(*atoms) );
1781 if (atoms) atoms[nb_atoms++] = properties[i];
1785 /* query all unknown atoms in one go */
1786 if (atoms)
1788 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1789 if (names)
1791 wine_tsx11_lock();
1792 /* FIXME: we're at the mercy of the app sending the event here.
1793 * Currently if they send a bogus atom, we will crash.
1794 * We should handle BadAtom errors gracefully in this call.
1796 XGetAtomNames( display, atoms, nb_atoms, names );
1797 wine_tsx11_unlock();
1798 for (i = 0; i < nb_atoms; i++)
1800 WINE_CLIPFORMAT *lpFormat;
1801 LPWSTR wname;
1802 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1803 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1804 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1806 lpFormat = register_format( wname, atoms[i] );
1807 HeapFree(GetProcessHeap(), 0, wname);
1808 if (!lpFormat)
1810 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1811 continue;
1813 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1814 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1815 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1817 wine_tsx11_lock();
1818 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1819 wine_tsx11_unlock();
1820 HeapFree( GetProcessHeap(), 0, names );
1822 HeapFree( GetProcessHeap(), 0, atoms );
1827 /**************************************************************************
1828 * X11DRV_CLIPBOARD_QueryAvailableData
1830 * Caches the list of data formats available from the current selection.
1831 * This queries the selection owner for the TARGETS property and saves all
1832 * reported property types.
1834 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo)
1836 Display *display = thread_display();
1837 XEvent xe;
1838 Atom atype=AnyPropertyType;
1839 int aformat;
1840 unsigned long remain;
1841 Atom* targetList=NULL;
1842 Window w;
1843 unsigned long cSelectionTargets = 0;
1845 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1847 ERR("Received request to cache selection but process is owner=(%08x)\n",
1848 (unsigned) selectionWindow);
1849 return -1; /* Prevent self request */
1852 w = thread_selection_wnd();
1853 if (!w)
1855 ERR("No window available to retrieve selection!\n");
1856 return -1;
1860 * Query the selection owner for the TARGETS property
1862 wine_tsx11_lock();
1863 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1864 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1866 wine_tsx11_unlock();
1867 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1868 selectionCacheSrc = XA_PRIMARY;
1869 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1870 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1871 else
1873 Atom xstr = XA_STRING;
1875 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1876 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1878 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1879 selectionCacheSrc = XA_PRIMARY;
1880 return 1;
1882 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1884 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1885 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1886 return 1;
1888 else
1890 WARN("Failed to query selection owner for available data.\n");
1891 return -1;
1895 else /* No selection owner so report 0 targets available */
1897 wine_tsx11_unlock();
1898 return 0;
1901 /* Read the TARGETS property contents */
1902 wine_tsx11_lock();
1903 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1904 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1905 &remain, (unsigned char**)&targetList) != Success)
1907 wine_tsx11_unlock();
1908 WARN("Failed to read TARGETS property\n");
1910 else
1912 wine_tsx11_unlock();
1913 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1914 atype, aformat, cSelectionTargets, remain);
1916 * The TARGETS property should have returned us a list of atoms
1917 * corresponding to each selection target format supported.
1919 if ((atype == XA_ATOM || atype == x11drv_atom(TARGETS)) && aformat == 32)
1920 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1922 /* Free the list of targets */
1923 wine_tsx11_lock();
1924 XFree(targetList);
1925 wine_tsx11_unlock();
1928 return cSelectionTargets;
1932 /**************************************************************************
1933 * X11DRV_CLIPBOARD_ReadSelectionData
1935 * This method is invoked only when we DO NOT own the X selection
1937 * We always get the data from the selection client each time,
1938 * since we have no way of determining if the data in our cache is stale.
1940 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(LPWINE_CLIPDATA lpData)
1942 Display *display = thread_display();
1943 Bool res;
1944 DWORD i;
1945 XEvent xe;
1946 BOOL bRet = FALSE;
1948 TRACE("%d\n", lpData->wFormatID);
1950 if (!lpData->lpFormat)
1952 ERR("Requesting format %d but no source format linked to data.\n",
1953 lpData->wFormatID);
1954 return FALSE;
1957 if (!selectionAcquired)
1959 Window w = thread_selection_wnd();
1960 if(!w)
1962 ERR("No window available to read selection data!\n");
1963 return FALSE;
1966 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
1967 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
1969 wine_tsx11_lock();
1970 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
1971 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1972 wine_tsx11_unlock();
1974 /* wait until SelectionNotify is received */
1975 for (i = 0; i < SELECTION_RETRIES; i++)
1977 wine_tsx11_lock();
1978 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1979 wine_tsx11_unlock();
1980 if (res && xe.xselection.selection == selectionCacheSrc) break;
1982 usleep(SELECTION_WAIT);
1985 /* Verify that the selection returned a valid TARGETS property */
1986 if (xe.xselection.property != None)
1989 * Read the contents of the X selection property
1990 * into WINE's clipboard cache and converting the
1991 * data format if necessary.
1993 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(xe.xselection.requestor,
1994 xe.xselection.property);
1996 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
1998 else
2000 TRACE("Failed to convert selection\n");
2003 else
2005 ERR("Received request to cache selection data but process is owner\n");
2008 TRACE("Returning %d\n", bRet);
2010 return bRet;
2014 /**************************************************************************
2015 * X11DRV_CLIPBOARD_ReadProperty
2016 * Reads the contents of the X selection property.
2018 static BOOL X11DRV_CLIPBOARD_ReadProperty(Window w, Atom prop,
2019 unsigned char** data, unsigned long* datasize)
2021 Display *display = thread_display();
2022 Atom atype = AnyPropertyType;
2023 int aformat;
2024 unsigned long total, nitems, remain, val_cnt;
2025 long reqlen, bwc;
2026 unsigned char* val;
2027 unsigned char* buffer;
2029 if (prop == None)
2030 return FALSE;
2032 TRACE("Reading property %d from X window %d\n",
2033 (unsigned int)prop, (unsigned int)w);
2036 * First request a zero length in order to figure out the request size.
2038 wine_tsx11_lock();
2039 if(XGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType,
2040 &atype, &aformat, &nitems, &remain, &buffer) != Success)
2042 wine_tsx11_unlock();
2043 WARN("Failed to get property size\n");
2044 return FALSE;
2047 /* Free zero length return data if any */
2048 if (buffer)
2050 XFree(buffer);
2051 buffer = NULL;
2054 bwc = aformat/8;
2055 reqlen = remain * bwc;
2057 TRACE("Retrieving %ld bytes\n", reqlen);
2059 val = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, reqlen);
2061 /* Read property in 4K blocks */
2062 for (total = 0, val_cnt = 0; remain;)
2064 if (XGetWindowProperty(display, w, prop, (total / 4), 4096, False,
2065 AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
2067 wine_tsx11_unlock();
2068 WARN("Failed to read property\n");
2069 HeapFree(GetProcessHeap(), 0, val);
2070 return FALSE;
2073 bwc = aformat/8;
2074 memcpy(&val[val_cnt], buffer, nitems * bwc);
2075 val_cnt += nitems * bwc;
2076 total += nitems*bwc;
2077 XFree(buffer);
2080 /* Delete the property on the window now that we are done
2081 * This will send a PropertyNotify event to the selection owner. */
2082 XDeleteProperty(display, w, prop);
2084 wine_tsx11_unlock();
2086 *data = val;
2087 *datasize = total;
2089 return TRUE;
2093 /**************************************************************************
2094 * CLIPBOARD_SerializeMetafile
2096 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2098 HANDLE h = 0;
2100 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2102 if (out) /* Serialize out, caller should free memory */
2104 *lpcbytes = 0; /* Assume failure */
2106 if (wformat == CF_METAFILEPICT)
2108 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
2109 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2111 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2112 if (h)
2114 char *pdata = GlobalLock(h);
2116 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2117 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2119 *lpcbytes = size + sizeof(METAFILEPICT);
2121 GlobalUnlock(h);
2124 GlobalUnlock(hdata);
2126 else if (wformat == CF_ENHMETAFILE)
2128 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2130 h = GlobalAlloc(0, size);
2131 if (h)
2133 LPVOID pdata = GlobalLock(h);
2135 GetEnhMetaFileBits(hdata, size, pdata);
2136 *lpcbytes = size;
2138 GlobalUnlock(h);
2142 else
2144 if (wformat == CF_METAFILEPICT)
2146 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2147 if (h)
2149 unsigned int wiresize, size;
2150 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
2152 memcpy(lpmfp, (LPVOID)hdata, sizeof(METAFILEPICT));
2153 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2154 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2155 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2156 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2157 GlobalUnlock(h);
2160 else if (wformat == CF_ENHMETAFILE)
2162 h = SetEnhMetaFileBits(*lpcbytes, (LPVOID)hdata);
2166 return h;
2170 /**************************************************************************
2171 * X11DRV_CLIPBOARD_ReleaseSelection
2173 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2175 static void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd, Time time)
2177 Display *display = thread_display();
2179 /* w is the window that lost the selection
2181 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2182 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2184 if (selectionAcquired && (w == selectionWindow))
2186 CLIPBOARDINFO cbinfo;
2188 /* completely give up the selection */
2189 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2191 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2193 if (cbinfo.flags & CB_PROCESS)
2195 /* Since we're still the owner, this wasn't initiated by
2196 another Wine process */
2197 if (OpenClipboard(hwnd))
2199 /* Destroy private objects */
2200 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2202 /* Give up ownership of the windows clipboard */
2203 X11DRV_CLIPBOARD_ReleaseOwnership();
2204 CloseClipboard();
2208 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2210 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2212 wine_tsx11_lock();
2213 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2215 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2216 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2218 else
2219 TRACE("We no longer own PRIMARY\n");
2220 wine_tsx11_unlock();
2222 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2224 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2226 wine_tsx11_lock();
2227 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2229 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2230 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2232 else
2233 TRACE("We no longer own CLIPBOARD\n");
2234 wine_tsx11_unlock();
2237 selectionWindow = None;
2239 X11DRV_EmptyClipboard(FALSE);
2241 /* Reset the selection flags now that we are done */
2242 selectionAcquired = S_NOSELECTION;
2247 /**************************************************************************
2248 * IsSelectionOwner (X11DRV.@)
2250 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2252 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2254 return selectionAcquired;
2258 /**************************************************************************
2259 * X11DRV Clipboard Exports
2260 **************************************************************************/
2263 /**************************************************************************
2264 * RegisterClipboardFormat (X11DRV.@)
2266 * Registers a custom X clipboard format
2267 * Returns: Format id or 0 on failure
2269 UINT X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2271 LPWINE_CLIPFORMAT lpFormat;
2273 if (FormatName == NULL) return 0;
2274 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2275 return lpFormat->wFormatID;
2279 /**************************************************************************
2280 * X11DRV_GetClipboardFormatName
2282 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2284 LPWINE_CLIPFORMAT lpFormat;
2286 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2288 if (wFormat < 0xc000)
2290 SetLastError(ERROR_INVALID_PARAMETER);
2291 return 0;
2294 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2296 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2298 TRACE("Unknown format 0x%08x!\n", wFormat);
2299 SetLastError(ERROR_INVALID_HANDLE);
2300 return 0;
2303 lstrcpynW(retStr, lpFormat->Name, maxlen);
2305 return strlenW(retStr);
2309 /**************************************************************************
2310 * AcquireClipboard (X11DRV.@)
2312 int X11DRV_AcquireClipboard(HWND hWndClipWindow)
2314 DWORD procid;
2315 Window owner;
2316 Display *display = thread_display();
2318 TRACE(" %p\n", hWndClipWindow);
2321 * It's important that the selection get acquired from the thread
2322 * that owns the clipboard window. The primary reason is that we know
2323 * it is running a message loop and therefore can process the
2324 * X selection events.
2326 if (hWndClipWindow &&
2327 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2329 if (procid != GetCurrentProcessId())
2331 WARN("Setting clipboard owner to other process is not supported\n");
2332 hWndClipWindow = NULL;
2334 else
2336 TRACE("Thread %lx is acquiring selection with thread %lx's window %p\n",
2337 GetCurrentThreadId(),
2338 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2340 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2344 owner = thread_selection_wnd();
2346 wine_tsx11_lock();
2348 selectionAcquired = 0;
2349 selectionWindow = 0;
2351 /* Grab PRIMARY selection if not owned */
2352 if (use_primary_selection)
2353 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2355 /* Grab CLIPBOARD selection if not owned */
2356 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2358 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2359 selectionAcquired |= S_PRIMARY;
2361 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2362 selectionAcquired |= S_CLIPBOARD;
2364 wine_tsx11_unlock();
2366 if (selectionAcquired)
2368 selectionWindow = owner;
2369 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2372 return 1;
2376 /**************************************************************************
2377 * X11DRV_EmptyClipboard
2379 * Empty cached clipboard data.
2381 void X11DRV_EmptyClipboard(BOOL keepunowned)
2383 if (ClipData)
2385 LPWINE_CLIPDATA lpData, lpStart;
2386 LPWINE_CLIPDATA lpNext = ClipData;
2388 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2392 lpStart = ClipData;
2393 lpData = lpNext;
2394 lpNext = lpData->NextData;
2396 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2398 lpData->PrevData->NextData = lpData->NextData;
2399 lpData->NextData->PrevData = lpData->PrevData;
2401 if (lpData == ClipData)
2402 ClipData = lpNext != lpData ? lpNext : NULL;
2404 X11DRV_CLIPBOARD_FreeData(lpData);
2405 HeapFree(GetProcessHeap(), 0, lpData);
2407 ClipDataCount--;
2409 } while (lpNext != lpStart);
2412 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2417 /**************************************************************************
2418 * X11DRV_SetClipboardData
2420 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2422 DWORD flags = 0;
2423 BOOL bResult = TRUE;
2425 /* If it's not owned, data can only be set if the format data is not already owned
2426 and its rendering is not delayed */
2427 if (!owner)
2429 CLIPBOARDINFO cbinfo;
2430 LPWINE_CLIPDATA lpRender;
2432 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2434 if ((!hData16 && !hData32) ||
2435 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2436 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2437 bResult = FALSE;
2438 else
2439 flags = CF_FLAG_UNOWNED;
2442 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags, NULL, TRUE);
2444 return bResult;
2448 /**************************************************************************
2449 * CountClipboardFormats
2451 INT X11DRV_CountClipboardFormats(void)
2453 CLIPBOARDINFO cbinfo;
2455 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2457 TRACE(" count=%d\n", ClipDataCount);
2459 return ClipDataCount;
2463 /**************************************************************************
2464 * X11DRV_EnumClipboardFormats
2466 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2468 CLIPBOARDINFO cbinfo;
2469 UINT wNextFormat = 0;
2471 TRACE("(%04X)\n", wFormat);
2473 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2475 if (!wFormat)
2477 if (ClipData)
2478 wNextFormat = ClipData->wFormatID;
2480 else
2482 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2484 if (lpData && lpData->NextData != ClipData)
2485 wNextFormat = lpData->NextData->wFormatID;
2488 return wNextFormat;
2492 /**************************************************************************
2493 * X11DRV_IsClipboardFormatAvailable
2495 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2497 BOOL bRet = FALSE;
2498 CLIPBOARDINFO cbinfo;
2500 TRACE("(%04X)\n", wFormat);
2502 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2504 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2505 bRet = TRUE;
2507 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2509 return bRet;
2513 /**************************************************************************
2514 * GetClipboardData (USER.142)
2516 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2518 CLIPBOARDINFO cbinfo;
2519 LPWINE_CLIPDATA lpRender;
2521 TRACE("(%04X)\n", wFormat);
2523 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2525 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2527 if ( !lpRender->hData32 )
2528 X11DRV_CLIPBOARD_RenderFormat(lpRender);
2530 /* Convert between 32 -> 16 bit data, if necessary */
2531 if (lpRender->hData32 && !lpRender->hData16)
2533 int size;
2535 if (lpRender->wFormatID == CF_METAFILEPICT)
2536 size = sizeof(METAFILEPICT16);
2537 else
2538 size = GlobalSize(lpRender->hData32);
2540 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2542 if (!lpRender->hData16)
2543 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2544 else
2546 if (lpRender->wFormatID == CF_METAFILEPICT)
2548 FIXME("\timplement function CopyMetaFilePict32to16\n");
2549 FIXME("\tin the appropriate file.\n");
2550 #ifdef SOMEONE_IMPLEMENTED_ME
2551 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2552 GlobalLock(lpRender->hData32));
2553 #endif
2555 else
2557 memcpy(GlobalLock16(lpRender->hData16),
2558 GlobalLock(lpRender->hData32), size);
2561 GlobalUnlock16(lpRender->hData16);
2562 GlobalUnlock(lpRender->hData32);
2566 /* Convert between 32 -> 16 bit data, if necessary */
2567 if (lpRender->hData16 && !lpRender->hData32)
2569 int size;
2571 if (lpRender->wFormatID == CF_METAFILEPICT)
2572 size = sizeof(METAFILEPICT16);
2573 else
2574 size = GlobalSize(lpRender->hData32);
2576 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2577 GMEM_DDESHARE, size);
2579 if (lpRender->wFormatID == CF_METAFILEPICT)
2581 FIXME("\timplement function CopyMetaFilePict16to32\n");
2582 FIXME("\tin the appropriate file.\n");
2583 #ifdef SOMEONE_IMPLEMENTED_ME
2584 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2585 GlobalLock(lpRender->hData16));
2586 #endif
2588 else
2590 memcpy(GlobalLock(lpRender->hData32),
2591 GlobalLock16(lpRender->hData16), size);
2594 GlobalUnlock(lpRender->hData32);
2595 GlobalUnlock16(lpRender->hData16);
2598 if (phData16)
2599 *phData16 = lpRender->hData16;
2601 if (phData32)
2602 *phData32 = lpRender->hData32;
2604 TRACE(" returning hData16(%04x) hData32(%p) (type %d)\n",
2605 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2607 return lpRender->hData16 || lpRender->hData32;
2610 return 0;
2614 /**************************************************************************
2615 * ResetSelectionOwner
2617 * Called when the thread owning the selection is destroyed and we need to
2618 * preserve the selection ownership. We look for another top level window
2619 * in this process and send it a message to acquire the selection.
2621 void X11DRV_ResetSelectionOwner(void)
2623 HWND hwnd;
2624 DWORD procid;
2626 TRACE("\n");
2628 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2629 return;
2631 selectionAcquired = S_NOSELECTION;
2632 selectionWindow = 0;
2634 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2637 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2639 if (GetCurrentProcessId() == procid)
2641 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2642 return;
2645 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2647 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2649 X11DRV_CLIPBOARD_ReleaseOwnership();
2650 X11DRV_EmptyClipboard(FALSE);
2654 /**************************************************************************
2655 * X11DRV_CLIPBOARD_SynthesizeData
2657 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2659 BOOL bsyn = TRUE;
2660 LPWINE_CLIPDATA lpSource = NULL;
2662 TRACE(" %d\n", wFormatID);
2664 /* Don't need to synthesize if it already exists */
2665 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2666 return TRUE;
2668 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2670 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2671 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2672 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2673 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2674 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2675 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2677 else if (wFormatID == CF_ENHMETAFILE)
2679 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2680 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2682 else if (wFormatID == CF_METAFILEPICT)
2684 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2685 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2687 else if (wFormatID == CF_DIB)
2689 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2690 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2692 else if (wFormatID == CF_BITMAP)
2694 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2695 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2698 if (bsyn)
2699 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2701 return bsyn;
2706 /**************************************************************************
2707 * X11DRV_EndClipboardUpdate
2708 * TODO:
2709 * Add locale if it hasn't already been added
2711 void X11DRV_EndClipboardUpdate(void)
2713 INT count = ClipDataCount;
2715 /* Do Unicode <-> Text <-> OEM mapping */
2716 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2717 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2718 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2720 /* Enhmetafile <-> MetafilePict mapping */
2721 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2722 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2724 /* DIB <-> Bitmap mapping */
2725 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2726 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2728 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2732 /***********************************************************************
2733 * X11DRV_SelectionRequest_TARGETS
2734 * Service a TARGETS selection request event
2736 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2737 Atom target, Atom rprop )
2739 UINT i;
2740 Atom* targets;
2741 ULONG cTargets;
2742 LPWINE_CLIPFORMAT lpFormats;
2743 LPWINE_CLIPDATA lpData;
2745 /* Create X atoms for any clipboard types which don't have atoms yet.
2746 * This avoids sending bogus zero atoms.
2747 * Without this, copying might not have access to all clipboard types.
2748 * FIXME: is it safe to call this here?
2750 intern_atoms();
2753 * Count the number of items we wish to expose as selection targets.
2755 cTargets = 1; /* Include TARGETS */
2757 if (!(lpData = ClipData)) return None;
2761 lpFormats = ClipFormats;
2763 while (lpFormats)
2765 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2766 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2767 cTargets++;
2769 lpFormats = lpFormats->NextFormat;
2772 lpData = lpData->NextData;
2774 while (lpData != ClipData);
2776 TRACE(" found %ld formats\n", cTargets);
2778 /* Allocate temp buffer */
2779 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2780 if(targets == NULL)
2781 return None;
2783 i = 0;
2784 lpData = ClipData;
2785 targets[i++] = x11drv_atom(TARGETS);
2789 lpFormats = ClipFormats;
2791 while (lpFormats)
2793 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2794 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2795 targets[i++] = lpFormats->drvData;
2797 lpFormats = lpFormats->NextFormat;
2800 lpData = lpData->NextData;
2802 while (lpData != ClipData);
2804 wine_tsx11_lock();
2806 if (TRACE_ON(clipboard))
2808 unsigned int i;
2809 for ( i = 0; i < cTargets; i++)
2811 char *itemFmtName = XGetAtomName(display, targets[i]);
2812 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2813 XFree(itemFmtName);
2817 /* We may want to consider setting the type to xaTargets instead,
2818 * in case some apps expect this instead of XA_ATOM */
2819 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2820 PropModeReplace, (unsigned char *)targets, cTargets);
2821 wine_tsx11_unlock();
2823 HeapFree(GetProcessHeap(), 0, targets);
2825 return rprop;
2829 /***********************************************************************
2830 * X11DRV_SelectionRequest_MULTIPLE
2831 * Service a MULTIPLE selection request event
2832 * rprop contains a list of (target,property) atom pairs.
2833 * The first atom names a target and the second names a property.
2834 * The effect is as if we have received a sequence of SelectionRequest events
2835 * (one for each atom pair) except that:
2836 * 1. We reply with a SelectionNotify only when all the requested conversions
2837 * have been performed.
2838 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2839 * we replace the atom in the property by None.
2841 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2843 Display *display = pevent->display;
2844 Atom rprop;
2845 Atom atype=AnyPropertyType;
2846 int aformat;
2847 unsigned long remain;
2848 Atom* targetPropList=NULL;
2849 unsigned long cTargetPropList = 0;
2851 /* If the specified property is None the requestor is an obsolete client.
2852 * We support these by using the specified target atom as the reply property.
2854 rprop = pevent->property;
2855 if( rprop == None )
2856 rprop = pevent->target;
2857 if (!rprop)
2858 return 0;
2860 /* Read the MULTIPLE property contents. This should contain a list of
2861 * (target,property) atom pairs.
2863 wine_tsx11_lock();
2864 if(XGetWindowProperty(display, pevent->requestor, rprop,
2865 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2866 &cTargetPropList, &remain,
2867 (unsigned char**)&targetPropList) != Success)
2869 wine_tsx11_unlock();
2870 TRACE("\tCouldn't read MULTIPLE property\n");
2872 else
2874 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2875 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2876 wine_tsx11_unlock();
2879 * Make sure we got what we expect.
2880 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2881 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2882 * However some X apps(such as XPaint) are not compliant with this and return
2883 * a user defined atom in atype when XGetWindowProperty is called.
2884 * The data *is* an atom pair but is not denoted as such.
2886 if(aformat == 32 /* atype == xAtomPair */ )
2888 unsigned int i;
2890 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2891 * for each (target,property) pair */
2893 for (i = 0; i < cTargetPropList; i+=2)
2895 XSelectionRequestEvent event;
2897 if (TRACE_ON(clipboard))
2899 char *targetName, *propName;
2900 wine_tsx11_lock();
2901 targetName = XGetAtomName(display, targetPropList[i]);
2902 propName = XGetAtomName(display, targetPropList[i+1]);
2903 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
2904 i/2, targetName, propName);
2905 XFree(targetName);
2906 XFree(propName);
2907 wine_tsx11_unlock();
2910 /* We must have a non "None" property to service a MULTIPLE target atom */
2911 if ( !targetPropList[i+1] )
2913 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
2914 continue;
2917 /* Set up an XSelectionRequestEvent for this (target,property) pair */
2918 memcpy( &event, pevent, sizeof(XSelectionRequestEvent) );
2919 event.target = targetPropList[i];
2920 event.property = targetPropList[i+1];
2922 /* Fire a SelectionRequest, informing the handler that we are processing
2923 * a MULTIPLE selection request event.
2925 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
2929 /* Free the list of targets/properties */
2930 wine_tsx11_lock();
2931 XFree(targetPropList);
2932 wine_tsx11_unlock();
2935 return rprop;
2939 /***********************************************************************
2940 * X11DRV_HandleSelectionRequest
2941 * Process an event selection request event.
2942 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
2943 * recursively while servicing a "MULTIPLE" selection target.
2945 * Note: We only receive this event when WINE owns the X selection
2947 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
2949 Display *display = event->display;
2950 XSelectionEvent result;
2951 Atom rprop = None;
2952 Window request = event->requestor;
2954 TRACE("\n");
2957 * We can only handle the selection request if :
2958 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
2959 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
2960 * since this has been already done.
2962 if ( !bIsMultiple )
2964 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
2965 goto END;
2968 /* If the specified property is None the requestor is an obsolete client.
2969 * We support these by using the specified target atom as the reply property.
2971 rprop = event->property;
2972 if( rprop == None )
2973 rprop = event->target;
2975 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
2977 /* TARGETS selection request */
2978 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
2980 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
2982 /* MULTIPLE selection request */
2983 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
2985 else
2987 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
2989 if (lpFormat && lpFormat->lpDrvExportFunc)
2991 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
2993 if (lpData)
2995 unsigned char* lpClipData;
2996 DWORD cBytes;
2997 HANDLE hClipData = lpFormat->lpDrvExportFunc(request, event->target,
2998 rprop, lpData, &cBytes);
3000 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3002 TRACE("\tUpdating property %s, %ld bytes\n", debugstr_w(lpFormat->Name), cBytes);
3004 wine_tsx11_lock();
3005 XChangeProperty(display, request, rprop, event->target,
3006 8, PropModeReplace, (unsigned char *)lpClipData, cBytes);
3007 wine_tsx11_unlock();
3009 GlobalUnlock(hClipData);
3010 GlobalFree(hClipData);
3016 END:
3017 /* reply to sender
3018 * SelectionNotify should be sent only at the end of a MULTIPLE request
3020 if ( !bIsMultiple )
3022 result.type = SelectionNotify;
3023 result.display = display;
3024 result.requestor = request;
3025 result.selection = event->selection;
3026 result.property = rprop;
3027 result.target = event->target;
3028 result.time = event->time;
3029 TRACE("Sending SelectionNotify event...\n");
3030 wine_tsx11_lock();
3031 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3032 wine_tsx11_unlock();
3037 /***********************************************************************
3038 * X11DRV_SelectionRequest
3040 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3042 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3046 /***********************************************************************
3047 * X11DRV_SelectionClear
3049 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3051 XSelectionClearEvent *event = &xev->xselectionclear;
3052 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3053 X11DRV_CLIPBOARD_ReleaseSelection( event->selection, event->window, hWnd, event->time );