Implemented rendering synthesized BITMAP and DIB formats.
[wine/multimedia.git] / dlls / x11drv / clipboard.c
blobe9555a7395a0d4e746f6361921306174c2baba1f
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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>
77 #include "windef.h"
78 #include "winbase.h"
79 #include "winreg.h"
80 #include "wine/wingdi16.h"
81 #include "win.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 static int selectionAcquired = 0; /* Contains the current selection masks */
112 static Window selectionWindow = None; /* The top level X window which owns the selection */
113 static BOOL clearAllSelections = FALSE; /* Always lose all selections */
114 static BOOL usePrimary = FALSE; /* Use primary selection in additon to the clipboard selection */
115 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
116 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
117 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
119 INT X11DRV_RegisterClipboardFormat(LPCSTR FormatName);
120 void X11DRV_EmptyClipboard(void);
121 void X11DRV_EndClipboardUpdate(void);
122 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(LPBYTE lpdata, UINT cBytes);
123 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(LPBYTE lpdata, UINT cBytes);
124 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(LPBYTE lpdata, UINT cBytes);
125 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(LPBYTE lpdata, UINT cBytes);
126 HANDLE X11DRV_CLIPBOARD_ImportXAString(LPBYTE lpdata, UINT cBytes);
127 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
128 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
129 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget,
130 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
131 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget,
132 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
133 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget,
134 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
135 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget,
136 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
137 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCSTR FormatName, Atom prop);
138 static BOOL X11DRV_CLIPBOARD_ReadSelection(LPWINE_CLIPFORMAT lpData, Window w, Atom prop);
139 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID);
140 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
141 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
142 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo);
143 static BOOL X11DRV_CLIPBOARD_ReadClipboardData(UINT wFormat);
144 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData);
145 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
146 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
147 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData);
148 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(void);
149 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(void);
151 /* Clipboard formats
152 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
153 * declared in clipboard.h
155 static WINE_CLIPFORMAT ClipFormats[] =
157 { CF_TEXT, "WCF_TEXT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
158 X11DRV_CLIPBOARD_ExportClipboardData, NULL, &ClipFormats[1]},
160 { CF_BITMAP, "WCF_BITMAP", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
161 NULL, &ClipFormats[0], &ClipFormats[2]},
163 { CF_METAFILEPICT, "WCF_METAFILEPICT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
164 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
166 { CF_SYLK, "WCF_SYLK", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
167 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
169 { CF_DIF, "WCF_DIF", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
170 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
172 { CF_TIFF, "WCF_TIFF", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
173 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
175 { CF_OEMTEXT, "WCF_OEMTEXT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
176 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
178 { CF_DIB, "WCF_DIB", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
179 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
181 { CF_PALETTE, "WCF_PALETTE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
182 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
184 { CF_PENDATA, "WCF_PENDATA", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
185 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
187 { CF_RIFF, "WCF_RIFF", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
188 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
190 { CF_WAVE, "WCF_WAVE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
191 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
193 { CF_UNICODETEXT, "WCF_UNICODETEXT", XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
194 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
196 { CF_ENHMETAFILE, "WCF_ENHMETAFILE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
197 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[12], &ClipFormats[14]},
199 { CF_HDROP, "WCF_HDROP", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
200 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[13], &ClipFormats[15]},
202 { CF_LOCALE, "WCF_LOCALE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
203 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
205 { CF_DIBV5, "WCF_DIBV5", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
206 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
208 { CF_OWNERDISPLAY, "WCF_OWNERDISPLAY", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
209 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
211 { CF_DSPTEXT, "WCF_DSPTEXT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
212 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
214 { CF_DSPBITMAP, "WCF_DSPBITMAP", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
215 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
217 { CF_DSPMETAFILEPICT, "WCF_DSPMETAFILEPICT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
218 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
220 { CF_DSPENHMETAFILE, "WCF_DSPENHMETAFILE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
221 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], NULL}
224 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
226 /* Maps X properties to Windows formats */
227 static const struct
229 LPCSTR lpszFormat;
230 UINT prop;
231 } PropertyFormatMap[] =
233 { "Rich Text Format", XATOM_text_rtf },
234 /* Temporarily disable text/html because Evolution incorrectly pastes strings with extra nulls */
235 /*{ "text/html", "HTML Format" },*/
236 { "GIF", XATOM_image_gif }
240 /* Maps equivalent X properties. It is assumed that lpszProperty must already
241 be in ClipFormats or PropertyFormatMap. */
242 static const struct
244 UINT drvDataProperty;
245 UINT drvDataAlias;
246 } PropertyAliasMap[] =
248 /* DataProperty, DataAlias */
249 { XATOM_text_rtf, XATOM_text_richtext },
250 { XA_STRING, XATOM_COMPOUND_TEXT },
251 { XA_STRING, XATOM_TEXT },
252 { XATOM_WCF_DIB, XA_PIXMAP },
257 * Cached clipboard data.
259 static LPWINE_CLIPDATA ClipData = NULL;
260 static UINT ClipDataCount = 0;
263 * Clipboard sequence number
265 static UINT wSeqNo = 0;
267 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
269 /**************************************************************************
270 * Internal Clipboard implementation methods
271 **************************************************************************/
273 /**************************************************************************
274 * X11DRV_InitClipboard
276 void X11DRV_InitClipboard(void)
278 INT i;
279 HKEY hkey;
281 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
283 char buffer[20];
284 DWORD type, count = sizeof(buffer);
285 if(!RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, buffer, &count))
286 clearAllSelections = IS_OPTION_TRUE( buffer[0] );
287 count = sizeof(buffer);
288 if(!RegQueryValueExA(hkey, "UsePrimary", 0, &type, buffer, &count))
289 usePrimary = IS_OPTION_TRUE( buffer[0] );
290 RegCloseKey(hkey);
293 /* Register known mapping between window formats and X properties */
294 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
295 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat,
296 GET_ATOM(PropertyFormatMap[i].prop));
300 /**************************************************************************
301 * intern_atoms
303 * Intern atoms for formats that don't have one yet.
305 static void intern_atoms(void)
307 LPWINE_CLIPFORMAT format;
308 int i, count;
309 char **names;
310 Atom *atoms;
312 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
313 if (!format->drvData) count++;
314 if (!count) return;
316 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
317 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
319 for (format = ClipFormats, i = 0; format; format = format->NextFormat)
320 if (!format->drvData) names[i++] = format->Name;
322 wine_tsx11_lock();
323 XInternAtoms( thread_display(), names, count, False, atoms );
324 wine_tsx11_unlock();
326 for (format = ClipFormats, i = 0; format; format = format->NextFormat)
327 if (!format->drvData) format->drvData = atoms[i++];
329 HeapFree( GetProcessHeap(), 0, names );
330 HeapFree( GetProcessHeap(), 0, atoms );
334 /**************************************************************************
335 * register_format
337 * Register a custom X clipboard format.
339 static WINE_CLIPFORMAT *register_format( LPCSTR FormatName, Atom prop )
341 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
343 TRACE("'%s'\n", FormatName);
345 /* walk format chain to see if it's already registered */
346 while (lpFormat)
348 if ( !strcasecmp(lpFormat->Name, FormatName) &&
349 (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
350 return lpFormat;
351 lpFormat = lpFormat->NextFormat;
354 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
358 /**************************************************************************
359 * X11DRV_CLIPBOARD_LookupFormat
361 LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
363 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
365 while(lpFormat)
367 if (lpFormat->wFormatID == wID)
368 break;
370 lpFormat = lpFormat->NextFormat;
372 if (!lpFormat->drvData) intern_atoms();
373 return lpFormat;
377 /**************************************************************************
378 * X11DRV_CLIPBOARD_LookupProperty
380 LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(UINT drvData)
382 for (;;)
384 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
385 BOOL need_intern = FALSE;
387 while(lpFormat)
389 if (lpFormat->drvData == drvData) return lpFormat;
390 if (!lpFormat->drvData) need_intern = TRUE;
391 lpFormat = lpFormat->NextFormat;
393 if (!need_intern) return NULL;
394 intern_atoms();
395 /* restart the search for the new atoms */
400 /**************************************************************************
401 * X11DRV_CLIPBOARD_LookupAliasProperty
403 LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupAliasProperty(UINT drvDataAlias)
405 unsigned int i;
406 LPWINE_CLIPFORMAT lpFormat = NULL;
408 for (i = 0; i < sizeof(PropertyAliasMap)/sizeof(PropertyAliasMap[0]); i++)
410 if (GET_ATOM(PropertyAliasMap[i].drvDataAlias) == drvDataAlias)
412 lpFormat = X11DRV_CLIPBOARD_LookupProperty(GET_ATOM(PropertyAliasMap[i].drvDataProperty));
413 break;
417 return lpFormat;
421 /**************************************************************************
422 * X11DRV_CLIPBOARD_LookupPropertyAlias
424 UINT X11DRV_CLIPBOARD_LookupPropertyAlias(UINT drvDataProperty)
426 unsigned int i;
427 UINT alias = 0;
429 for (i = 0; i < sizeof(PropertyAliasMap)/sizeof(PropertyAliasMap[0]); i++)
431 if (GET_ATOM(PropertyAliasMap[i].drvDataProperty) == drvDataProperty)
433 alias = GET_ATOM(PropertyAliasMap[i].drvDataAlias);
434 break;
438 return alias;
442 /**************************************************************************
443 * X11DRV_CLIPBOARD_LookupData
445 LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
447 LPWINE_CLIPDATA lpData = ClipData;
449 if (lpData)
453 if (lpData->wFormatID == wID)
454 break;
456 lpData = lpData->NextData;
458 while(lpData != ClipData);
460 if (lpData->wFormatID != wID)
461 lpData = NULL;
464 return lpData;
468 /**************************************************************************
469 * InsertClipboardFormat
471 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCSTR FormatName, Atom prop)
473 LPWINE_CLIPFORMAT lpFormat;
474 LPWINE_CLIPFORMAT lpNewFormat;
476 /* allocate storage for new format entry */
477 lpNewFormat = (LPWINE_CLIPFORMAT) HeapAlloc(GetProcessHeap(),
478 0, sizeof(WINE_CLIPFORMAT));
480 if(lpNewFormat == NULL)
482 WARN("No more memory for a new format!\n");
483 return NULL;
486 if (!(lpNewFormat->Name = HeapAlloc(GetProcessHeap(), 0, strlen(FormatName)+1)))
488 WARN("No more memory for the new format name!\n");
489 HeapFree(GetProcessHeap(), 0, lpNewFormat);
490 return NULL;
493 strcpy(lpNewFormat->Name, FormatName);
494 lpNewFormat->wFlags = 0;
495 lpNewFormat->wFormatID = GlobalAddAtomA(lpNewFormat->Name);
496 lpNewFormat->drvData = prop;
497 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
498 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
500 /* Link Format */
501 lpFormat = ClipFormats;
503 while(lpFormat->NextFormat) /* Move to last entry */
504 lpFormat = lpFormat->NextFormat;
506 lpNewFormat->NextFormat = NULL;
507 lpFormat->NextFormat = lpNewFormat;
508 lpNewFormat->PrevFormat = lpFormat;
510 TRACE("Registering format(%d): %s drvData %d\n",
511 lpNewFormat->wFormatID, FormatName, lpNewFormat->drvData);
513 return lpNewFormat;
519 /**************************************************************************
520 * X11DRV_CLIPBOARD_GetClipboardInfo
522 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
524 BOOL bRet = FALSE;
526 SERVER_START_REQ( set_clipboard_info )
528 req->flags = 0;
530 if (wine_server_call_err( req ))
532 ERR("Failed to get clipboard owner.\n");
534 else
536 cbInfo->hWndOpen = reply->old_clipboard;
537 cbInfo->hWndOwner = reply->old_owner;
538 cbInfo->hWndViewer = reply->old_viewer;
539 cbInfo->seqno = reply->seqno;
540 cbInfo->flags = reply->flags;
542 bRet = TRUE;
545 SERVER_END_REQ;
547 return bRet;
551 /**************************************************************************
552 * X11DRV_CLIPBOARD_ReleaseOwnership
554 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
556 BOOL bRet = FALSE;
558 SERVER_START_REQ( set_clipboard_info )
560 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
562 if (wine_server_call_err( req ))
564 ERR("Failed to set clipboard.\n");
566 else
568 bRet = TRUE;
571 SERVER_END_REQ;
573 return bRet;
578 /**************************************************************************
579 * X11DRV_CLIPBOARD_InsertClipboardData
581 * Caller *must* have the clipboard open and be the owner.
583 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, DWORD flags)
585 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
587 TRACE("format=%d lpData=%p hData16=%08x hData32=%08x flags=0x%08lx\n",
588 wFormat, lpData, hData16, (unsigned int)hData32, flags);
590 if (lpData)
592 X11DRV_CLIPBOARD_FreeData(lpData);
594 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
595 lpData->hData32 = hData32;
597 else
599 lpData = (LPWINE_CLIPDATA) HeapAlloc(GetProcessHeap(),
600 0, sizeof(WINE_CLIPDATA));
602 lpData->wFormatID = wFormat;
603 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
604 lpData->hData32 = hData32;
605 lpData->drvData = 0;
607 if (ClipData)
609 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
611 lpData->PrevData = lpPrevData;
612 lpData->NextData = ClipData;
614 lpPrevData->NextData = lpData;
615 ClipData->PrevData = lpData;
617 else
619 lpData->NextData = lpData;
620 lpData->PrevData = lpData;
621 ClipData = lpData;
624 ClipDataCount++;
627 lpData->wFlags = flags;
629 return TRUE;
633 /**************************************************************************
634 * X11DRV_CLIPBOARD_FreeData
636 * Free clipboard data handle.
638 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
640 TRACE("%d\n", lpData->wFormatID);
642 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
643 lpData->wFormatID <= CF_GDIOBJLAST) ||
644 lpData->wFormatID == CF_BITMAP ||
645 lpData->wFormatID == CF_DIB ||
646 lpData->wFormatID == CF_PALETTE)
648 if (lpData->hData32)
649 DeleteObject(lpData->hData32);
651 if (lpData->hData16)
652 DeleteObject(HGDIOBJ_32(lpData->hData16));
654 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
655 XFreePixmap(gdi_display, lpData->drvData);
657 else if (lpData->wFormatID == CF_METAFILEPICT)
659 if (lpData->hData32)
661 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
662 GlobalFree(lpData->hData32);
664 if (lpData->hData16)
665 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
666 and a shallow copy is enough to share a METAFILEPICT
667 structure between 16bit and 32bit clipboards. The MetaFile
668 should of course only be deleted once. */
669 GlobalFree16(lpData->hData16);
672 if (lpData->hData16)
674 METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
676 if (lpMetaPict)
678 DeleteMetaFile16(lpMetaPict->hMF);
679 lpMetaPict->hMF = 0;
682 GlobalFree16(lpData->hData16);
685 else if (lpData->wFormatID == CF_ENHMETAFILE)
687 if (lpData->hData32)
688 DeleteEnhMetaFile(lpData->hData32);
690 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
691 lpData->wFormatID > CF_PRIVATELAST)
693 if (lpData->hData32)
694 GlobalFree(lpData->hData32);
696 if (lpData->hData16)
697 GlobalFree16(lpData->hData16);
700 lpData->hData16 = 0;
701 lpData->hData32 = 0;
702 lpData->drvData = 0;
706 /**************************************************************************
707 * X11DRV_CLIPBOARD_UpdateCache
709 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
711 BOOL bret = TRUE;
713 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
715 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
717 ERR("Failed to retrieve clipboard information.\n");
718 bret = FALSE;
720 else if (wSeqNo < lpcbinfo->seqno)
722 X11DRV_EmptyClipboard();
724 if (X11DRV_CLIPBOARD_QueryAvailableData(lpcbinfo) < 0)
726 ERR("Failed to cache clipboard data owned by another process.\n");
727 bret = FALSE;
729 else
731 X11DRV_EndClipboardUpdate();
734 wSeqNo = lpcbinfo->seqno;
738 return bret;
742 /**************************************************************************
743 * X11DRV_CLIPBOARD_RenderFormat
745 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData)
747 BOOL bret = TRUE;
749 TRACE(" 0x%04x hData32(0x%08x) hData16(0x%08x)\n",
750 lpData->wFormatID, (unsigned int)lpData->hData32, lpData->hData16);
752 if (lpData->hData32 || lpData->hData16)
753 return bret; /* Already rendered */
755 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
756 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(lpData);
757 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
759 if (!X11DRV_CLIPBOARD_ReadClipboardData(lpData->wFormatID))
761 ERR("Failed to cache clipboard data owned by another process. Format=%d\n",
762 lpData->wFormatID);
763 bret = FALSE;
766 else
768 CLIPBOARDINFO cbInfo;
770 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
772 /* Send a WM_RENDERFORMAT message to notify the owner to render the
773 * data requested into the clipboard.
775 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
776 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
778 if (!lpData->hData32 && !lpData->hData16)
779 bret = FALSE;
781 else
783 ERR("hWndClipOwner is lost!\n");
784 bret = FALSE;
788 return bret;
792 /**************************************************************************
793 * CLIPBOARD_ConvertText
794 * Returns number of required/converted characters - not bytes!
796 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
797 WORD dst_fmt, void *dst, INT dst_size)
799 UINT cp;
801 if(src_fmt == CF_UNICODETEXT)
803 switch(dst_fmt)
805 case CF_TEXT:
806 cp = CP_ACP;
807 break;
808 case CF_OEMTEXT:
809 cp = CP_OEMCP;
810 break;
811 default:
812 return 0;
814 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
817 if(dst_fmt == CF_UNICODETEXT)
819 switch(src_fmt)
821 case CF_TEXT:
822 cp = CP_ACP;
823 break;
824 case CF_OEMTEXT:
825 cp = CP_OEMCP;
826 break;
827 default:
828 return 0;
830 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
833 if(!dst_size) return src_size;
835 if(dst_size > src_size) dst_size = src_size;
837 if(src_fmt == CF_TEXT )
838 CharToOemBuffA(src, dst, dst_size);
839 else
840 OemToCharBuffA(src, dst, dst_size);
842 return dst_size;
846 /**************************************************************************
847 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
849 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData)
851 BOOL bret = FALSE;
853 TRACE("\n");
855 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
857 UINT wFormatID = lpData->wFormatID;
859 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
860 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(wFormatID);
861 else
863 switch (wFormatID)
865 case CF_DIB:
866 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB();
867 break;
869 case CF_BITMAP:
870 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap();
871 break;
873 case CF_ENHMETAFILE:
874 case CF_METAFILEPICT:
875 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
876 break;
878 default:
879 FIXME("Called to synthesize unknown format\n");
880 break;
884 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
887 return bret;
891 /**************************************************************************
892 * X11DRV_CLIPBOARD_RenderSynthesizedText
894 * Renders synthesized text
896 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID)
898 LPCSTR lpstrS;
899 LPSTR lpstrT;
900 HANDLE hData32;
901 INT src_chars, dst_chars, alloc_size;
902 LPWINE_CLIPDATA lpSource = NULL;
904 TRACE(" %d\n", wFormatID);
906 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
907 lpSource->hData32)
908 return TRUE;
910 /* Look for rendered source or non-synthesized source */
911 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
912 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
914 TRACE("UNICODETEXT -> %d\n", wFormatID);
916 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
917 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
919 TRACE("TEXT -> %d\n", wFormatID);
921 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
922 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
924 TRACE("OEMTEXT -> %d\n", wFormatID);
927 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
928 !lpSource->hData32))
929 return FALSE;
931 /* Ask the clipboard owner to render the source text if necessary */
932 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(lpSource))
933 return FALSE;
935 if (lpSource->hData32)
937 lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
939 else
941 lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
944 if (!lpstrS)
945 return FALSE;
947 /* Text always NULL terminated */
948 if(lpSource->wFormatID == CF_UNICODETEXT)
949 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
950 else
951 src_chars = strlen(lpstrS) + 1;
953 /* Calculate number of characters in the destination buffer */
954 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
955 src_chars, wFormatID, NULL, 0);
957 if (!dst_chars)
958 return FALSE;
960 TRACE("Converting from '%d' to '%d', %i chars\n",
961 lpSource->wFormatID, wFormatID, src_chars);
963 /* Convert characters to bytes */
964 if(wFormatID == CF_UNICODETEXT)
965 alloc_size = dst_chars * sizeof(WCHAR);
966 else
967 alloc_size = dst_chars;
969 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
970 GMEM_DDESHARE, alloc_size);
972 lpstrT = (LPSTR)GlobalLock(hData32);
974 if (lpstrT)
976 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
977 wFormatID, lpstrT, dst_chars);
978 GlobalUnlock(hData32);
981 /* Unlock source */
982 if (lpSource->hData32)
983 GlobalUnlock(lpSource->hData32);
984 else
985 GlobalUnlock16(lpSource->hData16);
987 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0);
991 /**************************************************************************
992 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
994 * Renders synthesized DIB
996 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB()
998 BOOL bret = FALSE;
999 LPWINE_CLIPDATA lpSource = NULL;
1001 TRACE("\n");
1003 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1005 bret = TRUE;
1007 /* If we have a bitmap and it's not synthesized or it has been rendered */
1008 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1009 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1011 /* Render source if required */
1012 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1014 HDC hdc;
1015 HGLOBAL hData32;
1017 hdc = GetDC(NULL);
1018 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1019 ReleaseDC(NULL, hdc);
1021 if (hData32)
1023 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0);
1024 bret = TRUE;
1029 return bret;
1033 /**************************************************************************
1034 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1036 * Renders synthesized bitmap
1038 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap()
1040 BOOL bret = FALSE;
1041 LPWINE_CLIPDATA lpSource = NULL;
1043 TRACE("\n");
1045 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1047 bret = TRUE;
1049 /* If we have a dib and it's not synthesized or it has been rendered */
1050 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1051 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1053 /* Render source if required */
1054 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1056 HDC hdc;
1057 HBITMAP hData32;
1058 unsigned int offset;
1059 LPBITMAPINFOHEADER lpbmih;
1061 hdc = GetDC(NULL);
1062 lpbmih = (LPBITMAPINFOHEADER) GlobalLock(lpSource->hData32);
1064 offset = sizeof(BITMAPINFOHEADER)
1065 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1066 (1 << lpbmih->biBitCount)) : 0);
1068 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1069 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1071 GlobalUnlock(lpSource->hData32);
1072 ReleaseDC(NULL, hdc);
1074 if (hData32)
1076 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0);
1077 bret = TRUE;
1082 return bret;
1086 /**************************************************************************
1087 * X11DRV_CLIPBOARD_ImportXAString
1089 * Import XA_STRING, converting the string to CF_UNICODE.
1091 HANDLE X11DRV_CLIPBOARD_ImportXAString(LPBYTE lpdata, UINT cBytes)
1093 LPSTR lpstr;
1094 UINT i, inlcount = 0;
1095 HANDLE hUnicodeText = 0;
1097 for (i = 0; i <= cBytes; i++)
1099 if (lpdata[i] == '\n')
1100 inlcount++;
1103 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cBytes + inlcount + 1)))
1105 UINT count;
1107 for (i = 0, inlcount = 0; i <= cBytes; i++)
1109 if (lpdata[i] == '\n')
1110 lpstr[inlcount++] = '\r';
1112 lpstr[inlcount++] = lpdata[i];
1115 count = MultiByteToWideChar(CP_UNIXCP, 0, lpstr, -1, NULL, 0);
1116 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1118 if(hUnicodeText)
1120 WCHAR *textW = GlobalLock(hUnicodeText);
1121 MultiByteToWideChar(CP_UNIXCP, 0, lpstr, -1, textW, count);
1122 GlobalUnlock(hUnicodeText);
1125 HeapFree(GetProcessHeap(), 0, lpstr);
1128 return hUnicodeText;
1132 /**************************************************************************
1133 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1135 * Import XA_PIXMAP, converting the image to CF_DIB.
1137 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(LPBYTE lpdata, UINT cBytes)
1139 HANDLE hTargetImage = 0; /* Handle to store the converted DIB */
1140 Pixmap *pPixmap = (Pixmap *) lpdata;
1141 HWND hwnd = GetOpenClipboardWindow();
1142 HDC hdc = GetDC(hwnd);
1144 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
1146 ReleaseDC(hwnd, hdc);
1148 return hTargetImage;
1152 /**************************************************************************
1153 * X11DRV_CLIPBOARD_ImportMetaFilePict
1155 * Import MetaFilePict.
1157 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(LPBYTE lpdata, UINT cBytes)
1159 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cBytes, FALSE);
1163 /**************************************************************************
1164 * X11DRV_ImportEnhMetaFile
1166 * Import EnhMetaFile.
1168 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(LPBYTE lpdata, UINT cBytes)
1170 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cBytes, FALSE);
1174 /**************************************************************************
1175 * X11DRV_ImportClipbordaData
1177 * Generic import clipboard data routine.
1179 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(LPBYTE lpdata, UINT cBytes)
1181 LPVOID lpClipData;
1182 HANDLE hClipData = 0;
1184 if (cBytes)
1186 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1187 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes);
1188 if ((lpClipData = GlobalLock(hClipData)))
1190 memcpy(lpClipData, lpdata, cBytes);
1191 GlobalUnlock(hClipData);
1193 else
1194 hClipData = 0;
1197 return hClipData;
1201 /**************************************************************************
1202 X11DRV_CLIPBOARD_ExportClipboardData
1204 * Generic export clipboard data routine.
1206 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
1207 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1209 LPVOID lpClipData;
1210 UINT cBytes = 0;
1211 HANDLE hClipData = 0;
1213 *lpBytes = 0; /* Assume failure */
1215 if (!X11DRV_CLIPBOARD_RenderFormat(lpData))
1216 ERR("Failed to export %d format\n", lpData->wFormatID);
1217 else
1219 cBytes = GlobalSize(lpData->hData32);
1221 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes);
1223 if ((lpClipData = GlobalLock(hClipData)))
1225 LPVOID lpdata = GlobalLock(lpData->hData32);
1227 memcpy(lpClipData, lpdata, cBytes);
1228 *lpBytes = cBytes;
1230 GlobalUnlock(lpData->hData32);
1231 GlobalUnlock(hClipData);
1235 return hClipData;
1239 /**************************************************************************
1240 * X11DRV_CLIPBOARD_ExportXAString
1242 * Export CF_UNICODE converting the string to XA_STRING.
1243 * Helper function for X11DRV_CLIPBOARD_ExportString.
1245 HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1247 INT i, j;
1248 UINT size;
1249 LPWSTR uni_text;
1250 LPSTR text, lpstr;
1252 *lpBytes = 0; /* Assume return has zero bytes */
1254 uni_text = GlobalLock(lpData->hData32);
1256 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1258 text = HeapAlloc(GetProcessHeap(), 0, size);
1259 if (!text)
1260 return None;
1261 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, text, size, NULL, NULL);
1263 /* remove carriage returns */
1265 lpstr = (char*)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size-- );
1266 if(lpstr == NULL) return None;
1267 for(i = 0,j = 0; i < size && text[i]; i++ )
1269 if( text[i] == '\r' &&
1270 (text[i+1] == '\n' || text[i+1] == '\0') ) continue;
1271 lpstr[j++] = text[i];
1273 lpstr[j]='\0';
1275 *lpBytes = j; /* Number of bytes in string */
1277 HeapFree(GetProcessHeap(), 0, text);
1278 GlobalUnlock(lpData->hData32);
1280 return lpstr;
1284 /**************************************************************************
1285 * X11DRV_CLIPBOARD_ExportCompoundText
1287 * Export CF_UNICODE to COMPOUND_TEXT or TEXT
1288 * Helper function for X11DRV_CLIPBOARD_ExportString.
1290 HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Window requestor, Atom aTarget, Atom rprop,
1291 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1293 Display *display = thread_display();
1294 char* lpstr = 0;
1295 XTextProperty prop;
1296 XICCEncodingStyle style;
1298 lpstr = (char*) X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1300 if (lpstr)
1302 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1303 style = XCompoundTextStyle;
1304 else
1305 style = XStdICCTextStyle;
1307 /* Update the X property */
1308 wine_tsx11_lock();
1309 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1311 XSetTextProperty(display, requestor, &prop, rprop);
1312 XFree(prop.value);
1314 wine_tsx11_unlock();
1316 HeapFree( GetProcessHeap(), 0, lpstr );
1319 return 0;
1322 /**************************************************************************
1323 * X11DRV_CLIPBOARD_ExportString
1325 * Export CF_UNICODE string
1327 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget, Atom rprop,
1328 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1330 if (X11DRV_CLIPBOARD_RenderFormat(lpData))
1332 if (aTarget == XA_STRING)
1333 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1334 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1335 return X11DRV_CLIPBOARD_ExportCompoundText(requestor, aTarget,
1336 rprop, lpData, lpBytes);
1337 else
1338 ERR("Unknown target %ld to %d format\n", aTarget, lpData->wFormatID);
1340 else
1341 ERR("Failed to render %d format\n", lpData->wFormatID);
1343 return 0;
1347 /**************************************************************************
1348 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1350 * Export CF_DIB to XA_PIXMAP.
1352 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget, Atom rprop,
1353 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1355 HDC hdc;
1356 HANDLE hData;
1357 unsigned char* lpData;
1359 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1361 ERR("Failed to export %d format\n", lpdata->wFormatID);
1362 return 0;
1365 if (!lpdata->drvData) /* If not already rendered */
1367 /* For convert from packed DIB to Pixmap */
1368 hdc = GetDC(0);
1369 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1370 ReleaseDC(0, hdc);
1373 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1375 /* Wrap pixmap so we can return a handle */
1376 hData = GlobalAlloc(0, *lpBytes);
1377 lpData = GlobalLock(hData);
1378 memcpy(lpData, &lpdata->drvData, *lpBytes);
1379 GlobalUnlock(hData);
1381 return (HANDLE) hData;
1385 /**************************************************************************
1386 * X11DRV_CLIPBOARD_ExportMetaFilePict
1388 * Export MetaFilePict.
1390 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget, Atom rprop,
1391 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1393 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1395 ERR("Failed to export %d format\n", lpdata->wFormatID);
1396 return 0;
1399 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata->hData32,
1400 lpBytes, TRUE);
1404 /**************************************************************************
1405 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1407 * Export EnhMetaFile.
1409 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget, Atom rprop,
1410 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1412 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1414 ERR("Failed to export %d format\n", lpdata->wFormatID);
1415 return 0;
1418 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata->hData32,
1419 lpBytes, TRUE);
1423 /**************************************************************************
1424 * X11DRV_CLIPBOARD_QueryTargets
1426 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection, XEvent *xe)
1428 INT i;
1429 Bool res;
1431 wine_tsx11_lock();
1432 XConvertSelection(display, selection, x11drv_atom(TARGETS),
1433 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1434 wine_tsx11_unlock();
1437 * Wait until SelectionNotify is received
1439 for (i = 0; i < SELECTION_RETRIES; i++)
1441 wine_tsx11_lock();
1442 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1443 wine_tsx11_unlock();
1444 if (res && xe->xselection.selection == selection) break;
1446 usleep(SELECTION_WAIT);
1449 /* Verify that the selection returned a valid TARGETS property */
1450 if ((xe->xselection.target != x11drv_atom(TARGETS)) || (xe->xselection.property == None))
1452 /* Selection owner failed to respond or we missed the SelectionNotify */
1453 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1454 return FALSE;
1457 return TRUE;
1461 /**************************************************************************
1462 * X11DRV_CLIPBOARD_QueryAvailableData
1464 * Caches the list of data formats available from the current selection.
1465 * This queries the selection owner for the TARGETS property and saves all
1466 * reported property types.
1468 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo)
1470 Display *display = thread_display();
1471 XEvent xe;
1472 Atom atype=AnyPropertyType;
1473 int aformat;
1474 unsigned long remain;
1475 Atom* targetList=NULL;
1476 Window w;
1477 HWND hWndClipWindow;
1478 unsigned long cSelectionTargets = 0;
1480 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1482 ERR("Received request to cache selection but process is owner=(%08x)\n",
1483 (unsigned) selectionWindow);
1485 selectionAcquired = S_NOSELECTION;
1487 wine_tsx11_lock();
1488 if (XGetSelectionOwner(display,XA_PRIMARY) == selectionWindow)
1489 selectionAcquired |= S_PRIMARY;
1491 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == selectionWindow)
1492 selectionAcquired |= S_CLIPBOARD;
1493 wine_tsx11_unlock();
1495 if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
1497 WARN("Lost selection but process didn't process SelectClear\n");
1498 selectionWindow = None;
1500 else
1502 return -1; /* Prevent self request */
1506 if (lpcbinfo->flags & CB_OWNER)
1507 hWndClipWindow = lpcbinfo->hWndOwner;
1508 else if (lpcbinfo->flags & CB_OPEN)
1509 hWndClipWindow = lpcbinfo->hWndOpen;
1510 else
1511 hWndClipWindow = GetActiveWindow();
1513 if (!hWndClipWindow)
1515 WARN("No window available to retrieve selection!\n");
1516 return -1;
1519 w = X11DRV_get_whole_window(GetAncestor(hWndClipWindow, GA_ROOT));
1522 * Query the selection owner for the TARGETS property
1524 wine_tsx11_lock();
1525 if ((usePrimary && XGetSelectionOwner(display,XA_PRIMARY)) ||
1526 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1528 wine_tsx11_unlock();
1529 if (usePrimary && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, &xe)))
1530 selectionCacheSrc = XA_PRIMARY;
1531 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), &xe))
1532 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1533 else
1534 return -1;
1536 else /* No selection owner so report 0 targets available */
1538 wine_tsx11_unlock();
1539 return 0;
1542 /* Read the TARGETS property contents */
1543 wine_tsx11_lock();
1544 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1545 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1546 &remain, (unsigned char**)&targetList) != Success)
1548 wine_tsx11_unlock();
1549 WARN("Failed to read TARGETS property\n");
1551 else
1553 wine_tsx11_unlock();
1554 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1555 atype, aformat, cSelectionTargets, remain);
1557 * The TARGETS property should have returned us a list of atoms
1558 * corresponding to each selection target format supported.
1560 if ((atype == XA_ATOM || atype == x11drv_atom(TARGETS)) && aformat == 32)
1562 INT i, nb_atoms = 0;
1563 Atom *atoms = NULL;
1565 /* Cache these formats in the clipboard cache */
1566 for (i = 0; i < cSelectionTargets; i++)
1568 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(targetList[i]);
1570 if (!lpFormat)
1571 lpFormat = X11DRV_CLIPBOARD_LookupAliasProperty(targetList[i]);
1573 if (!lpFormat)
1575 /* add it to the list of atoms that we don't know about yet */
1576 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1577 (cSelectionTargets - i) * sizeof(*atoms) );
1578 if (atoms) atoms[nb_atoms++] = targetList[i];
1580 else
1582 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1583 i, lpFormat->drvData, lpFormat->wFormatID, lpFormat->Name);
1584 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1588 /* query all unknown atoms in one go */
1589 if (atoms)
1591 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1592 if (names)
1594 wine_tsx11_lock();
1595 XGetAtomNames( display, atoms, nb_atoms, names );
1596 wine_tsx11_unlock();
1597 for (i = 0; i < nb_atoms; i++)
1599 WINE_CLIPFORMAT *lpFormat = register_format( names[i], atoms[i] );
1600 if (!lpFormat)
1602 ERR("Failed to cache %s property\n", names[i]);
1603 continue;
1605 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1606 i, lpFormat->drvData, lpFormat->wFormatID, lpFormat->Name);
1607 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1609 wine_tsx11_lock();
1610 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1611 wine_tsx11_unlock();
1612 HeapFree( GetProcessHeap(), 0, names );
1617 /* Free the list of targets */
1618 wine_tsx11_lock();
1619 XFree(targetList);
1620 wine_tsx11_unlock();
1623 return cSelectionTargets;
1627 /**************************************************************************
1628 * X11DRV_CLIPBOARD_ReadClipboardData
1630 * This method is invoked only when we DO NOT own the X selection
1632 * We always get the data from the selection client each time,
1633 * since we have no way of determining if the data in our cache is stale.
1635 static BOOL X11DRV_CLIPBOARD_ReadClipboardData(UINT wFormat)
1637 Display *display = thread_display();
1638 BOOL bRet = FALSE;
1639 Bool res;
1641 HWND hWndClipWindow = GetOpenClipboardWindow();
1642 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1644 LPWINE_CLIPFORMAT lpFormat;
1646 TRACE("%d\n", wFormat);
1648 if (!selectionAcquired)
1650 Window w = X11DRV_get_whole_window(GetAncestor(hWnd, GA_ROOT));
1651 if(!w)
1653 FIXME("No parent win found %p %p\n", hWnd, hWndClipWindow);
1654 return FALSE;
1657 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
1659 if (lpFormat->drvData)
1661 DWORD i;
1662 UINT alias;
1663 XEvent xe;
1665 TRACE("Requesting %s selection (%d) from win(%08x)\n",
1666 lpFormat->Name, lpFormat->drvData, (UINT)selectionCacheSrc);
1668 wine_tsx11_lock();
1669 XConvertSelection(display, selectionCacheSrc, lpFormat->drvData,
1670 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1671 wine_tsx11_unlock();
1673 /* wait until SelectionNotify is received */
1674 for (i = 0; i < SELECTION_RETRIES; i++)
1676 wine_tsx11_lock();
1677 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1678 wine_tsx11_unlock();
1679 if (res && xe.xselection.selection == selectionCacheSrc) break;
1681 usleep(SELECTION_WAIT);
1684 /* If the property wasn't available check for aliases */
1685 if (xe.xselection.property == None &&
1686 (alias = X11DRV_CLIPBOARD_LookupPropertyAlias(lpFormat->drvData)))
1688 wine_tsx11_lock();
1689 XConvertSelection(display, selectionCacheSrc, alias,
1690 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1691 wine_tsx11_unlock();
1693 /* wait until SelectionNotify is received */
1694 for (i = 0; i < SELECTION_RETRIES; i++)
1696 wine_tsx11_lock();
1697 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1698 wine_tsx11_unlock();
1699 if (res && xe.xselection.selection == selectionCacheSrc) break;
1701 usleep(SELECTION_WAIT);
1705 /* Verify that the selection returned a valid TARGETS property */
1706 if (xe.xselection.property != None)
1709 * Read the contents of the X selection property
1710 * into WINE's clipboard cache converting the
1711 * selection to be compatible if possible.
1713 bRet = X11DRV_CLIPBOARD_ReadSelection(lpFormat, xe.xselection.requestor,
1714 xe.xselection.property);
1718 else
1720 ERR("Received request to cache selection data but process is owner\n");
1723 TRACE("Returning %d\n", bRet);
1725 return bRet;
1729 /**************************************************************************
1730 * X11DRV_CLIPBOARD_ReadSelection
1731 * Reads the contents of the X selection property into the WINE clipboard cache
1732 * converting the selection into a format compatible with the windows clipboard
1733 * if possible.
1734 * This method is invoked only to read the contents of a the selection owned
1735 * by an external application. i.e. when we do not own the X selection.
1737 static BOOL X11DRV_CLIPBOARD_ReadSelection(LPWINE_CLIPFORMAT lpData, Window w, Atom prop)
1739 Display *display = thread_display();
1740 Atom atype=AnyPropertyType;
1741 int aformat;
1742 unsigned long total,nitems,remain,val_cnt;
1743 long reqlen, bwc;
1744 unsigned char* val;
1745 unsigned char* buffer;
1746 BOOL bRet = FALSE;
1748 if(prop == None)
1749 return bRet;
1751 TRACE("Reading X selection type %s\n", lpData->Name);
1754 * First request a zero length in order to figure out the request size.
1756 wine_tsx11_lock();
1757 if(XGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType,
1758 &atype, &aformat, &nitems, &remain, &buffer) != Success)
1760 wine_tsx11_unlock();
1761 WARN("Failed to get property size\n");
1762 return bRet;
1765 /* Free zero length return data if any */
1766 if (buffer)
1768 XFree(buffer);
1769 buffer = NULL;
1772 bwc = aformat/8;
1773 reqlen = remain * bwc;
1775 TRACE("Retrieving %ld bytes\n", reqlen);
1777 val = (char*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, reqlen);
1779 /* Read property in 4K blocks */
1780 for (total = 0, val_cnt = 0; remain;)
1782 if (XGetWindowProperty(display, w, prop, (total / 4), 4096, False,
1783 AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
1785 wine_tsx11_unlock();
1786 WARN("Failed to read property\n");
1787 HeapFree(GetProcessHeap(), 0, val);
1788 return bRet;
1791 bwc = aformat/8;
1792 memcpy(&val[val_cnt], buffer, nitems * bwc);
1793 val_cnt += nitems * bwc;
1794 total += nitems*bwc;
1795 XFree(buffer);
1797 wine_tsx11_unlock();
1799 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, lpData->lpDrvImportFunc(val, total), 0);
1801 /* Delete the property on the window now that we are done
1802 * This will send a PropertyNotify event to the selection owner. */
1803 wine_tsx11_lock();
1804 XDeleteProperty(display,w,prop);
1805 wine_tsx11_unlock();
1807 /* Free the retrieved property data */
1808 HeapFree(GetProcessHeap(),0,val);
1810 return bRet;
1814 /**************************************************************************
1815 * CLIPBOARD_SerializeMetafile
1817 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
1819 HANDLE h = 0;
1821 TRACE(" wFormat=%d hdata=%08x out=%d\n", wformat, (unsigned int) hdata, out);
1823 if (out) /* Serialize out, caller should free memory */
1825 *lpcbytes = 0; /* Assume failure */
1827 if (wformat == CF_METAFILEPICT)
1829 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
1830 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1832 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
1833 if (h)
1835 char *pdata = GlobalLock(h);
1837 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
1838 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
1840 *lpcbytes = size + sizeof(METAFILEPICT);
1842 GlobalUnlock(h);
1845 GlobalUnlock(hdata);
1847 else if (wformat == CF_ENHMETAFILE)
1849 int size = GetEnhMetaFileBits(hdata, 0, NULL);
1851 h = GlobalAlloc(0, size);
1852 if (h)
1854 LPVOID pdata = GlobalLock(h);
1856 GetEnhMetaFileBits(hdata, size, pdata);
1857 *lpcbytes = size;
1859 GlobalUnlock(h);
1863 else
1865 if (wformat == CF_METAFILEPICT)
1867 h = GlobalAlloc(0, sizeof(METAFILEPICT));
1868 if (h)
1870 unsigned int wiresize, size;
1871 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
1873 memcpy(lpmfp, (LPVOID)hdata, sizeof(METAFILEPICT));
1874 wiresize = *lpcbytes - sizeof(METAFILEPICT);
1875 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
1876 ((char *)hdata) + sizeof(METAFILEPICT));
1877 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1878 GlobalUnlock(h);
1881 else if (wformat == CF_ENHMETAFILE)
1883 h = SetEnhMetaFileBits(*lpcbytes, (LPVOID)hdata);
1887 return h;
1891 /**************************************************************************
1892 * X11DRV_CLIPBOARD_ReleaseSelection
1894 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
1895 * to a SelectionClear event.
1896 * This can occur in response to another client grabbing the X selection.
1897 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
1899 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
1901 Display *display = thread_display();
1903 /* w is the window that lost the selection
1905 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
1906 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
1908 if (selectionAcquired)
1910 if (w == selectionWindow)
1912 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
1913 * dictate that *all* selections should be cleared on loss of a selection,
1914 * we must give up all the selections we own.
1916 if (clearAllSelections || (selType == x11drv_atom(CLIPBOARD)))
1918 CLIPBOARDINFO cbinfo;
1920 /* completely give up the selection */
1921 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
1923 /* We are completely giving up the selection. There is a
1924 * potential race condition where the apps that now owns
1925 * the selection has already grabbed both selections. In
1926 * this case, if we clear any selection we may clear the
1927 * new owners selection. To prevent this common case we
1928 * try to open the clipboard. If we can't, we assume it
1929 * was a wine apps that took it and has taken both selections.
1930 * In this case, don't bother releasing the other selection.
1931 * Otherwise only release the selection if we still own it.
1933 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
1935 if (cbinfo.flags & CB_OWNER)
1937 /* Since we're still the owner, this wasn't initiated by
1938 another Wine process */
1939 if (OpenClipboard(hwnd))
1941 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
1942 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
1944 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
1945 wine_tsx11_lock();
1946 if (selectionWindow == XGetSelectionOwner(display,XA_PRIMARY))
1948 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
1949 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
1951 else
1952 TRACE("We no longer own PRIMARY\n");
1953 wine_tsx11_unlock();
1956 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
1957 if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
1959 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
1960 wine_tsx11_lock();
1961 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1963 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
1964 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, CurrentTime);
1966 else
1967 TRACE("We no longer own CLIPBOARD\n");
1968 wine_tsx11_unlock();
1971 /* Destroy private objects */
1972 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
1974 /* Give up ownership of the windows clipboard */
1975 X11DRV_CLIPBOARD_ReleaseOwnership();
1977 CloseClipboard();
1980 else
1982 TRACE("Lost selection to other Wine process.\n");
1985 selectionWindow = None;
1986 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
1988 X11DRV_EmptyClipboard();
1990 /* Reset the selection flags now that we are done */
1991 selectionAcquired = S_NOSELECTION;
1993 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
1995 TRACE("Lost PRIMARY selection\n");
1996 PrimarySelectionOwner = 0;
1997 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
2004 /**************************************************************************
2005 * IsSelectionOwner (X11DRV.@)
2007 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2009 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2011 return selectionAcquired;
2015 /**************************************************************************
2016 * X11DRV Clipboard Exports
2017 **************************************************************************/
2020 /**************************************************************************
2021 * RegisterClipboardFormat (X11DRV.@)
2023 * Registers a custom X clipboard format
2024 * Returns: Format id or 0 on failure
2026 INT X11DRV_RegisterClipboardFormat(LPCSTR FormatName)
2028 LPWINE_CLIPFORMAT lpFormat;
2030 if (FormatName == NULL) return 0;
2031 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2032 return lpFormat->wFormatID;
2036 /**************************************************************************
2037 * X11DRV_GetClipboardFormatName
2039 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPSTR retStr, INT maxlen)
2041 INT len = 0;
2042 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2044 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2046 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2048 TRACE("Unknown format 0x%08x!\n", wFormat);
2049 SetLastError(ERROR_INVALID_PARAMETER);
2051 else
2053 strncpy(retStr, lpFormat->Name, maxlen - 1);
2054 retStr[maxlen - 1] = 0;
2056 len = strlen(retStr);
2059 return len;
2063 /**************************************************************************
2064 * AcquireClipboard (X11DRV.@)
2066 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2068 Display *display = thread_display();
2071 * Acquire X selection if we don't already own it.
2072 * Note that we only acquire the selection if it hasn't been already
2073 * acquired by us, and ignore the fact that another X window may be
2074 * asserting ownership. The reason for this is we need *any* top level
2075 * X window to hold selection ownership. The actual clipboard data requests
2076 * are made via GetClipboardData from EVENT_SelectionRequest and this
2077 * ensures that the real HWND owner services the request.
2078 * If the owning X window gets destroyed the selection ownership is
2079 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
2082 if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
2084 Window owner;
2086 if (!hWndClipWindow)
2087 hWndClipWindow = GetActiveWindow();
2089 owner = X11DRV_get_whole_window(GetAncestor(hWndClipWindow, GA_ROOT));
2091 wine_tsx11_lock();
2092 /* Grab PRIMARY selection if not owned */
2093 if (usePrimary && !(selectionAcquired & S_PRIMARY))
2094 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2096 /* Grab CLIPBOARD selection if not owned */
2097 if (!(selectionAcquired & S_CLIPBOARD))
2098 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2100 if (usePrimary && XGetSelectionOwner(display,XA_PRIMARY) == owner)
2101 selectionAcquired |= S_PRIMARY;
2103 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2104 selectionAcquired |= S_CLIPBOARD;
2105 wine_tsx11_unlock();
2107 if (selectionAcquired)
2109 selectionWindow = owner;
2110 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2113 else
2115 WARN("Received request to acquire selection but process is already owner=(%08x)\n", (unsigned) selectionWindow);
2117 selectionAcquired = S_NOSELECTION;
2119 wine_tsx11_lock();
2120 if (XGetSelectionOwner(display,XA_PRIMARY) == selectionWindow)
2121 selectionAcquired |= S_PRIMARY;
2123 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == selectionWindow)
2124 selectionAcquired |= S_CLIPBOARD;
2125 wine_tsx11_unlock();
2127 if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
2129 WARN("Lost selection but process didn't process SelectClear\n");
2130 selectionWindow = None;
2136 /**************************************************************************
2137 * X11DRV_EmptyClipboard
2139 void X11DRV_EmptyClipboard(void)
2141 if (ClipData)
2143 LPWINE_CLIPDATA lpData;
2144 LPWINE_CLIPDATA lpNext = ClipData;
2148 lpData = lpNext;
2149 lpNext = lpData->NextData;
2150 lpData->PrevData->NextData = lpData->NextData;
2151 lpData->NextData->PrevData = lpData->PrevData;
2152 X11DRV_CLIPBOARD_FreeData(lpData);
2153 HeapFree(GetProcessHeap(), 0, lpData);
2154 } while (lpNext != lpData);
2157 TRACE(" %d entries deleted from cache.\n", ClipDataCount);
2159 ClipData = NULL;
2160 ClipDataCount = 0;
2165 /**************************************************************************
2166 * X11DRV_SetClipboardData
2168 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32)
2170 BOOL bResult = FALSE;
2172 if (X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, 0))
2173 bResult = TRUE;
2175 return bResult;
2179 /**************************************************************************
2180 * CountClipboardFormats
2182 INT X11DRV_CountClipboardFormats(void)
2184 CLIPBOARDINFO cbinfo;
2186 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2188 TRACE(" count=%d\n", ClipDataCount);
2190 return ClipDataCount;
2194 /**************************************************************************
2195 * X11DRV_EnumClipboardFormats
2197 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2199 CLIPBOARDINFO cbinfo;
2200 UINT wNextFormat = 0;
2202 TRACE("(%04X)\n", wFormat);
2204 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2206 if (!wFormat)
2208 if (ClipData)
2209 wNextFormat = ClipData->wFormatID;
2211 else
2213 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2215 if (lpData && lpData->NextData != ClipData)
2216 wNextFormat = lpData->NextData->wFormatID;
2219 return wNextFormat;
2223 /**************************************************************************
2224 * X11DRV_IsClipboardFormatAvailable
2226 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2228 BOOL bRet = FALSE;
2229 CLIPBOARDINFO cbinfo;
2231 TRACE("(%04X)\n", wFormat);
2233 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2235 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2236 bRet = TRUE;
2238 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2240 return bRet;
2244 /**************************************************************************
2245 * GetClipboardData (USER.142)
2247 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2249 CLIPBOARDINFO cbinfo;
2250 LPWINE_CLIPDATA lpRender;
2252 TRACE("(%04X)\n", wFormat);
2254 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2256 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2258 if ( !lpRender->hData32 )
2259 X11DRV_CLIPBOARD_RenderFormat(lpRender);
2261 /* Convert between 32 -> 16 bit data, if necessary */
2262 if (lpRender->hData32 && !lpRender->hData16)
2264 int size;
2266 if (lpRender->wFormatID == CF_METAFILEPICT)
2267 size = sizeof(METAFILEPICT16);
2268 else
2269 size = GlobalSize(lpRender->hData32);
2271 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2273 if (!lpRender->hData16)
2274 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2275 else
2277 if (lpRender->wFormatID == CF_METAFILEPICT)
2279 FIXME("\timplement function CopyMetaFilePict32to16\n");
2280 FIXME("\tin the appropriate file.\n");
2281 #ifdef SOMEONE_IMPLEMENTED_ME
2282 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2283 GlobalLock(lpRender->hData32));
2284 #endif
2286 else
2288 memcpy(GlobalLock16(lpRender->hData16),
2289 GlobalLock(lpRender->hData32), size);
2292 GlobalUnlock16(lpRender->hData16);
2293 GlobalUnlock(lpRender->hData32);
2297 /* Convert between 32 -> 16 bit data, if necessary */
2298 if (lpRender->hData16 && !lpRender->hData32)
2300 int size;
2302 if (lpRender->wFormatID == CF_METAFILEPICT)
2303 size = sizeof(METAFILEPICT16);
2304 else
2305 size = GlobalSize(lpRender->hData32);
2307 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2308 GMEM_DDESHARE, size);
2310 if (lpRender->wFormatID == CF_METAFILEPICT)
2312 FIXME("\timplement function CopyMetaFilePict16to32\n");
2313 FIXME("\tin the appropriate file.\n");
2314 #ifdef SOMEONE_IMPLEMENTED_ME
2315 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2316 GlobalLock(lpRender->hData16));
2317 #endif
2319 else
2321 memcpy(GlobalLock(lpRender->hData32),
2322 GlobalLock16(lpRender->hData16), size);
2325 GlobalUnlock(lpRender->hData32);
2326 GlobalUnlock16(lpRender->hData16);
2329 if (phData16)
2330 *phData16 = lpRender->hData16;
2332 if (phData32)
2333 *phData32 = lpRender->hData32;
2335 TRACE(" returning hData16(%04x) hData32(%04x) (type %d)\n",
2336 lpRender->hData16, (unsigned int) lpRender->hData32, lpRender->wFormatID);
2338 return lpRender->hData16 || lpRender->hData32;
2341 return 0;
2345 /**************************************************************************
2346 * ResetSelectionOwner (X11DRV.@)
2348 * Called from DestroyWindow() to prevent X selection from being lost when
2349 * a top level window is destroyed, by switching ownership to another top
2350 * level window.
2351 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
2352 * for a more detailed description of this.
2354 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
2356 Display *display = thread_display();
2357 HWND hWndClipOwner = 0;
2358 HWND tmp;
2359 Window XWnd = X11DRV_get_whole_window(hwnd);
2360 BOOL bLostSelection = FALSE;
2361 Window selectionPrevWindow;
2363 /* There is nothing to do if we don't own the selection,
2364 * or if the X window which currently owns the selection is different
2365 * from the one passed in.
2367 if (!selectionAcquired || XWnd != selectionWindow
2368 || selectionWindow == None )
2369 return;
2371 if ((bFooBar && XWnd) || (!bFooBar && !XWnd))
2372 return;
2374 hWndClipOwner = GetClipboardOwner();
2376 TRACE("clipboard owner = %p, selection window = %08x\n",
2377 hWndClipOwner, (unsigned)selectionWindow);
2379 /* now try to salvage current selection from being destroyed by X */
2380 TRACE("checking %08x\n", (unsigned) XWnd);
2382 selectionPrevWindow = selectionWindow;
2383 selectionWindow = None;
2385 if (!(tmp = GetWindow(hwnd, GW_HWNDNEXT)))
2386 tmp = GetWindow(hwnd, GW_HWNDFIRST);
2388 if (tmp && tmp != hwnd)
2389 selectionWindow = X11DRV_get_whole_window(tmp);
2391 if (selectionWindow != None)
2393 /* We must pretend that we don't own the selection while making the switch
2394 * since a SelectionClear event will be sent to the last owner.
2395 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
2397 int saveSelectionState = selectionAcquired;
2398 selectionAcquired = S_NOSELECTION;
2400 TRACE("\tswitching selection from %08x to %08x\n",
2401 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
2403 wine_tsx11_lock();
2405 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
2406 if (saveSelectionState & S_PRIMARY)
2407 XSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
2409 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), selectionWindow, CurrentTime);
2411 /* Restore the selection masks */
2412 selectionAcquired = saveSelectionState;
2414 /* Lose the selection if something went wrong */
2415 if (((saveSelectionState & S_PRIMARY) &&
2416 (XGetSelectionOwner(display, XA_PRIMARY) != selectionWindow)) ||
2417 (XGetSelectionOwner(display, x11drv_atom(CLIPBOARD)) != selectionWindow))
2419 bLostSelection = TRUE;
2421 else
2423 /* Update selection state */
2424 if (saveSelectionState & S_PRIMARY)
2425 PrimarySelectionOwner = selectionWindow;
2427 ClipboardSelectionOwner = selectionWindow;
2429 wine_tsx11_unlock();
2431 else
2433 bLostSelection = TRUE;
2436 if (bLostSelection)
2438 TRACE("Lost the selection!\n");
2440 X11DRV_CLIPBOARD_ReleaseOwnership();
2441 selectionAcquired = S_NOSELECTION;
2442 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
2443 selectionWindow = 0;
2448 /**************************************************************************
2449 * X11DRV_CLIPBOARD_SynthesizeData
2451 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2453 BOOL bsyn = TRUE;
2454 LPWINE_CLIPDATA lpSource = NULL;
2456 TRACE(" %d\n", wFormatID);
2458 /* Don't need to synthesize if it already exists */
2459 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2460 return TRUE;
2462 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2464 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2465 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2466 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2467 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2468 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2469 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2471 else if (wFormatID == CF_ENHMETAFILE)
2473 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2474 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2476 else if (wFormatID == CF_METAFILEPICT)
2478 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2479 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2481 else if (wFormatID == CF_DIB)
2483 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2484 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2486 else if (wFormatID == CF_BITMAP)
2488 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2489 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2492 if (bsyn)
2493 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED);
2495 return bsyn;
2500 /**************************************************************************
2501 * X11DRV_EndClipboardUpdate
2502 * TODO:
2503 * Add locale if it hasn't already been added
2505 void X11DRV_EndClipboardUpdate(void)
2507 INT count = ClipDataCount;
2509 /* Do Unicode <-> Text <-> OEM mapping */
2510 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2511 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2512 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2514 /* Enhmetafile <-> MetafilePict mapping */
2515 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2516 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2518 /* DIB <-> Bitmap mapping */
2519 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2520 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2522 TRACE("%d formats added to cached data\n", ClipDataCount - count);