VirtualBox

source: vbox/trunk/src/VBox/GuestHost/SharedClipboard/clipboard-win.cpp@ 82510

Last change on this file since 82510 was 82510, checked in by vboxsync, 5 years ago

GuestHost/clipboard-win.cpp: Set all incomping formats in SharedClipboardWinAnnounceFormats as windows is totally capable of handling that. bugref:9437

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.5 KB
Line 
1/* $Id: clipboard-win.cpp 82510 2019-12-09 12:15:16Z vboxsync $ */
2/** @file
3 * Shared Clipboard: Windows-specific functions for clipboard handling.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define LOG_GROUP LOG_GROUP_SHARED_CLIPBOARD
19#include <VBox/GuestHost/SharedClipboard.h>
20
21#include <iprt/assert.h>
22#include <iprt/errcore.h>
23#include <iprt/ldr.h>
24#include <iprt/mem.h>
25#include <iprt/thread.h>
26#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
27# include <iprt/win/windows.h>
28# include <iprt/win/shlobj.h> /* For CFSTR_FILEDESCRIPTORXXX + CFSTR_FILECONTENTS. */
29# include <iprt/utf16.h>
30#endif
31
32#include <VBox/log.h>
33
34#include <VBox/HostServices/VBoxClipboardSvc.h>
35#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
36# include <VBox/GuestHost/SharedClipboard-transfers.h>
37#endif
38#include <VBox/GuestHost/SharedClipboard-win.h>
39#include <VBox/GuestHost/clipboard-helper.h>
40
41
42/**
43 * Opens the clipboard of a specific window.
44 *
45 * @returns VBox status code.
46 * @param hWnd Handle of window to open clipboard for.
47 */
48int SharedClipboardWinOpen(HWND hWnd)
49{
50 /* "OpenClipboard fails if another window has the clipboard open."
51 * So try a few times and wait up to 1 second.
52 */
53 BOOL fOpened = FALSE;
54
55 LogFlowFunc(("hWnd=%p\n", hWnd));
56
57 int i = 0;
58 for (;;)
59 {
60 if (OpenClipboard(hWnd))
61 {
62 fOpened = TRUE;
63 break;
64 }
65
66 if (i >= 10) /* sleep interval = [1..512] ms */
67 break;
68
69 RTThreadSleep(1 << i);
70 ++i;
71 }
72
73#ifdef LOG_ENABLED
74 if (i > 0)
75 LogFlowFunc(("%d times tried to open clipboard\n", i + 1));
76#endif
77
78 int rc;
79 if (fOpened)
80 rc = VINF_SUCCESS;
81 else
82 {
83 const DWORD dwLastErr = GetLastError();
84 rc = RTErrConvertFromWin32(dwLastErr);
85 LogFunc(("Failed to open clipboard, rc=%Rrc (0x%x)\n", rc, dwLastErr));
86 }
87
88 return rc;
89}
90
91/**
92 * Closes the clipboard for the current thread.
93 *
94 * @returns VBox status code.
95 */
96int SharedClipboardWinClose(void)
97{
98 int rc;
99
100 const BOOL fRc = CloseClipboard();
101 if (RT_UNLIKELY(!fRc))
102 {
103 const DWORD dwLastErr = GetLastError();
104 if (dwLastErr == ERROR_CLIPBOARD_NOT_OPEN)
105 {
106 rc = VINF_SUCCESS; /* Not important, so just report success instead. */
107 }
108 else
109 {
110 rc = RTErrConvertFromWin32(dwLastErr);
111 LogFunc(("Failed with %Rrc (0x%x)\n", rc, dwLastErr));
112 }
113 }
114 else
115 rc = VINF_SUCCESS;
116
117 LogFlowFuncLeaveRC(rc);
118 return rc;
119}
120
121/**
122 * Clears the clipboard for the current thread.
123 *
124 * @returns VBox status code.
125 */
126int SharedClipboardWinClear(void)
127{
128 int rc;
129
130 LogFlowFuncEnter();
131
132 const BOOL fRc = EmptyClipboard();
133 if (RT_UNLIKELY(!fRc))
134 {
135 const DWORD dwLastErr = GetLastError();
136 if (dwLastErr == ERROR_CLIPBOARD_NOT_OPEN)
137 rc = VERR_INVALID_STATE;
138 else
139 rc = RTErrConvertFromWin32(dwLastErr);
140
141 LogFunc(("Failed with %Rrc (0x%x)\n", rc, dwLastErr));
142 }
143 else
144 rc = VINF_SUCCESS;
145
146 return rc;
147}
148
149/**
150 * Initializes a Shared Clipboard Windows context.
151 *
152 * @returns VBox status code.
153 * @param pWinCtx Shared Clipboard Windows context to initialize.
154 */
155int SharedClipboardWinCtxInit(PSHCLWINCTX pWinCtx)
156{
157 int rc = RTCritSectInit(&pWinCtx->CritSect);
158 if (RT_SUCCESS(rc))
159 {
160 /* Check that new Clipboard API is available. */
161 SharedClipboardWinCheckAndInitNewAPI(&pWinCtx->newAPI);
162 /* Do *not* check the rc, as the call might return VERR_SYMBOL_NOT_FOUND is the new API isn't available. */
163
164 pWinCtx->hWnd = NULL;
165 pWinCtx->hWndClipboardOwnerUs = NULL;
166 pWinCtx->hWndNextInChain = NULL;
167 }
168
169 LogFlowFuncLeaveRC(rc);
170 return rc;
171}
172
173/**
174 * Destroys a Shared Clipboard Windows context.
175 *
176 * @param pWinCtx Shared Clipboard Windows context to destroy.
177 */
178void SharedClipboardWinCtxDestroy(PSHCLWINCTX pWinCtx)
179{
180 if (!pWinCtx)
181 return;
182
183 LogFlowFuncEnter();
184
185 if (RTCritSectIsInitialized(&pWinCtx->CritSect))
186 {
187 int rc2 = RTCritSectDelete(&pWinCtx->CritSect);
188 AssertRC(rc2);
189 }
190}
191
192/**
193 * Checks and initializes function pointer which are required for using
194 * the new clipboard API.
195 *
196 * @returns VBox status code, or VERR_SYMBOL_NOT_FOUND if the new API is not available.
197 * @param pAPI Where to store the retrieved function pointers.
198 * Will be set to NULL if the new API is not available.
199 */
200int SharedClipboardWinCheckAndInitNewAPI(PSHCLWINAPINEW pAPI)
201{
202 RTLDRMOD hUser32 = NIL_RTLDRMOD;
203 int rc = RTLdrLoadSystem("User32.dll", /* fNoUnload = */ true, &hUser32);
204 if (RT_SUCCESS(rc))
205 {
206 rc = RTLdrGetSymbol(hUser32, "AddClipboardFormatListener", (void **)&pAPI->pfnAddClipboardFormatListener);
207 if (RT_SUCCESS(rc))
208 {
209 rc = RTLdrGetSymbol(hUser32, "RemoveClipboardFormatListener", (void **)&pAPI->pfnRemoveClipboardFormatListener);
210 }
211
212 RTLdrClose(hUser32);
213 }
214
215 if (RT_SUCCESS(rc))
216 {
217 LogRel(("Shared Clipboard: New Clipboard API enabled\n"));
218 }
219 else
220 {
221 RT_BZERO(pAPI, sizeof(SHCLWINAPINEW));
222 LogRel(("Shared Clipboard: New Clipboard API not available (%Rrc)\n", rc));
223 }
224
225 LogFlowFuncLeaveRC(rc);
226 return rc;
227}
228
229/**
230 * Returns if the new clipboard API is available or not.
231 *
232 * @returns @c true if the new API is available, or @c false if not.
233 * @param pAPI Structure used for checking if the new clipboard API is available or not.
234 */
235bool SharedClipboardWinIsNewAPI(PSHCLWINAPINEW pAPI)
236{
237 if (!pAPI)
238 return false;
239 return pAPI->pfnAddClipboardFormatListener != NULL;
240}
241
242/**
243 * Adds ourselves into the chain of cliboard listeners.
244 *
245 * @returns VBox status code.
246 * @param pCtx Windows clipboard context to use to add ourselves.
247 */
248int SharedClipboardWinChainAdd(PSHCLWINCTX pCtx)
249{
250 const PSHCLWINAPINEW pAPI = &pCtx->newAPI;
251
252 BOOL fRc;
253 if (SharedClipboardWinIsNewAPI(pAPI))
254 {
255 fRc = pAPI->pfnAddClipboardFormatListener(pCtx->hWnd);
256 }
257 else
258 {
259 pCtx->hWndNextInChain = SetClipboardViewer(pCtx->hWnd);
260 fRc = pCtx->hWndNextInChain != NULL;
261 }
262
263 int rc = VINF_SUCCESS;
264
265 if (!fRc)
266 {
267 const DWORD dwLastErr = GetLastError();
268 rc = RTErrConvertFromWin32(dwLastErr);
269 LogFunc(("Failed with %Rrc (0x%x)\n", rc, dwLastErr));
270 }
271
272 return rc;
273}
274
275/**
276 * Remove ourselves from the chain of cliboard listeners
277 *
278 * @returns VBox status code.
279 * @param pCtx Windows clipboard context to use to remove ourselves.
280 */
281int SharedClipboardWinChainRemove(PSHCLWINCTX pCtx)
282{
283 if (!pCtx->hWnd)
284 return VINF_SUCCESS;
285
286 const PSHCLWINAPINEW pAPI = &pCtx->newAPI;
287
288 BOOL fRc;
289 if (SharedClipboardWinIsNewAPI(pAPI))
290 {
291 fRc = pAPI->pfnRemoveClipboardFormatListener(pCtx->hWnd);
292 }
293 else
294 {
295 fRc = ChangeClipboardChain(pCtx->hWnd, pCtx->hWndNextInChain);
296 if (fRc)
297 pCtx->hWndNextInChain = NULL;
298 }
299
300 int rc = VINF_SUCCESS;
301
302 if (!fRc)
303 {
304 const DWORD dwLastErr = GetLastError();
305 rc = RTErrConvertFromWin32(dwLastErr);
306 LogFunc(("Failed with %Rrc (0x%x)\n", rc, dwLastErr));
307 }
308
309 return rc;
310}
311
312/**
313 * Callback which is invoked when we have successfully pinged ourselves down the
314 * clipboard chain. We simply unset a boolean flag to say that we are responding.
315 * There is a race if a ping returns after the next one is initiated, but nothing
316 * very bad is likely to happen.
317 *
318 * @param hWnd Window handle to use for this callback. Not used currently.
319 * @param uMsg Message to handle. Not used currently.
320 * @param dwData Pointer to user-provided data. Contains our Windows clipboard context.
321 * @param lResult Additional data to pass. Not used currently.
322 */
323VOID CALLBACK SharedClipboardWinChainPingProc(HWND hWnd, UINT uMsg, ULONG_PTR dwData, LRESULT lResult)
324{
325 RT_NOREF(hWnd);
326 RT_NOREF(uMsg);
327 RT_NOREF(lResult);
328
329 /** @todo r=andy Why not using SetWindowLongPtr for keeping the context? */
330 PSHCLWINCTX pCtx = (PSHCLWINCTX)dwData;
331 AssertPtrReturnVoid(pCtx);
332
333 pCtx->oldAPI.fCBChainPingInProcess = FALSE;
334}
335
336/**
337 * Passes a window message to the next window in the clipboard chain.
338 *
339 * @returns LRESULT
340 * @param pWinCtx Window context to use.
341 * @param msg Window message to pass.
342 * @param wParam WPARAM to pass.
343 * @param lParam LPARAM to pass.
344 */
345LRESULT SharedClipboardWinChainPassToNext(PSHCLWINCTX pWinCtx,
346 UINT msg, WPARAM wParam, LPARAM lParam)
347{
348 LogFlowFuncEnter();
349
350 LRESULT lresultRc = 0;
351
352 if (pWinCtx->hWndNextInChain)
353 {
354 LogFunc(("hWndNextInChain=%p\n", pWinCtx->hWndNextInChain));
355
356 /* Pass the message to next window in the clipboard chain. */
357 DWORD_PTR dwResult;
358 lresultRc = SendMessageTimeout(pWinCtx->hWndNextInChain, msg, wParam, lParam, 0,
359 SHCL_WIN_CBCHAIN_TIMEOUT_MS, &dwResult);
360 if (!lresultRc)
361 lresultRc = dwResult;
362 }
363
364 LogFlowFunc(("lresultRc=%ld\n", lresultRc));
365 return lresultRc;
366}
367
368/**
369 * Converts a (registered or standard) Windows clipboard format to a VBox clipboard format.
370 *
371 * @returns Converted VBox clipboard format, or VBOX_SHCL_FMT_NONE if not found.
372 * @param uFormat Windows clipboard format to convert.
373 */
374SHCLFORMAT SharedClipboardWinClipboardFormatToVBox(UINT uFormat)
375{
376 /* Insert the requested clipboard format data into the clipboard. */
377 SHCLFORMAT vboxFormat = VBOX_SHCL_FMT_NONE;
378
379 switch (uFormat)
380 {
381 case CF_UNICODETEXT:
382 vboxFormat = VBOX_SHCL_FMT_UNICODETEXT;
383 break;
384
385 case CF_DIB:
386 vboxFormat = VBOX_SHCL_FMT_BITMAP;
387 break;
388
389#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
390 /* CF_HDROP handles file system entries which are locally present
391 * on source for transferring to the target.
392 *
393 * This does *not* invoke any IDataObject / IStream implementations! */
394 case CF_HDROP:
395 vboxFormat = VBOX_SHCL_FMT_URI_LIST;
396 break;
397#endif
398
399 default:
400 if (uFormat >= 0xC000) /** Formats registered with RegisterClipboardFormat() start at this index. */
401 {
402 TCHAR szFormatName[256]; /** @todo r=andy Do we need Unicode support here as well? */
403 int cActual = GetClipboardFormatName(uFormat, szFormatName, sizeof(szFormatName) / sizeof(TCHAR));
404 if (cActual)
405 {
406 LogFlowFunc(("uFormat=%u -> szFormatName=%s\n", uFormat, szFormatName));
407
408 if (RTStrCmp(szFormatName, SHCL_WIN_REGFMT_HTML) == 0)
409 vboxFormat = VBOX_SHCL_FMT_HTML;
410#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
411 /* These types invoke our IDataObject / IStream implementations. */
412 else if ( (RTStrCmp(szFormatName, CFSTR_FILEDESCRIPTORA) == 0)
413 || (RTStrCmp(szFormatName, CFSTR_FILECONTENTS) == 0))
414 vboxFormat = VBOX_SHCL_FMT_URI_LIST;
415 /** @todo Do we need to handle CFSTR_FILEDESCRIPTORW here as well? */
416#endif
417 }
418 }
419 break;
420 }
421
422 LogFlowFunc(("uFormat=%u -> vboxFormat=0x%x\n", uFormat, vboxFormat));
423 return vboxFormat;
424}
425
426/**
427 * Retrieves all supported clipboard formats of a specific clipboard.
428 *
429 * @returns VBox status code.
430 * @param pCtx Windows clipboard context to retrieve formats for.
431 * @param pFormats Where to store the retrieved formats.
432 */
433int SharedClipboardWinGetFormats(PSHCLWINCTX pCtx, PSHCLFORMATDATA pFormats)
434{
435 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
436 AssertPtrReturn(pFormats, VERR_INVALID_POINTER);
437
438 SHCLFORMATS fFormats = VBOX_SHCL_FMT_NONE;
439
440 /* Query list of available formats and report to host. */
441 int rc = SharedClipboardWinOpen(pCtx->hWnd);
442 if (RT_SUCCESS(rc))
443 {
444 UINT uCurFormat = 0; /* Must be set to zero for EnumClipboardFormats(). */
445 while ((uCurFormat = EnumClipboardFormats(uCurFormat)) != 0)
446 fFormats |= SharedClipboardWinClipboardFormatToVBox(uCurFormat);
447
448 int rc2 = SharedClipboardWinClose();
449 AssertRC(rc2);
450 }
451
452 if (RT_FAILURE(rc))
453 {
454 LogFunc(("Failed with rc=%Rrc\n", rc));
455 }
456 else
457 {
458 LogFlowFunc(("fFormats=0x%08X\n", fFormats));
459
460 pFormats->Formats = fFormats;
461 pFormats->fFlags = 0; /** @todo Handle flags. */
462 }
463
464 return rc;
465}
466
467/**
468 * Extracts a field value from CF_HTML data.
469 *
470 * @returns VBox status code.
471 * @param pszSrc source in CF_HTML format.
472 * @param pszOption Name of CF_HTML field.
473 * @param puValue Where to return extracted value of CF_HTML field.
474 */
475int SharedClipboardWinGetCFHTMLHeaderValue(const char *pszSrc, const char *pszOption, uint32_t *puValue)
476{
477 AssertPtrReturn(pszSrc, VERR_INVALID_POINTER);
478 AssertPtrReturn(pszOption, VERR_INVALID_POINTER);
479
480 int rc = VERR_INVALID_PARAMETER;
481
482 const char *pszOptionValue = RTStrStr(pszSrc, pszOption);
483 if (pszOptionValue)
484 {
485 size_t cchOption = strlen(pszOption);
486 Assert(cchOption);
487
488 rc = RTStrToUInt32Ex(pszOptionValue + cchOption, NULL, 10, puValue);
489 }
490 return rc;
491}
492
493/**
494 * Check that the source string contains CF_HTML struct.
495 *
496 * @returns @c true if the @a pszSource string is in CF_HTML format.
497 * @param pszSource Source string to check.
498 */
499bool SharedClipboardWinIsCFHTML(const char *pszSource)
500{
501 return RTStrStr(pszSource, "Version:") != NULL
502 && RTStrStr(pszSource, "StartHTML:") != NULL;
503}
504
505/**
506 * Converts clipboard data from CF_HTML format to MIME clipboard format.
507 *
508 * Returns allocated buffer that contains html converted to text/html mime type
509 *
510 * @returns VBox status code.
511 * @param pszSource The input.
512 * @param cch The length of the input.
513 * @param ppszOutput Where to return the result. Free using RTMemFree.
514 * @param pcbOutput Where to the return length of the result (bytes/chars).
515 */
516int SharedClipboardWinConvertCFHTMLToMIME(const char *pszSource, const uint32_t cch, char **ppszOutput, uint32_t *pcbOutput)
517{
518 Assert(pszSource);
519 Assert(cch);
520 Assert(ppszOutput);
521 Assert(pcbOutput);
522
523 uint32_t offStart;
524 int rc = SharedClipboardWinGetCFHTMLHeaderValue(pszSource, "StartFragment:", &offStart);
525 if (RT_SUCCESS(rc))
526 {
527 uint32_t offEnd;
528 rc = SharedClipboardWinGetCFHTMLHeaderValue(pszSource, "EndFragment:", &offEnd);
529 if (RT_SUCCESS(rc))
530 {
531 if ( offStart > 0
532 && offEnd > 0
533 && offEnd > offStart
534 && offEnd <= cch)
535 {
536 uint32_t cchSubStr = offEnd - offStart;
537 char *pszResult = (char *)RTMemAlloc(cchSubStr + 1);
538 if (pszResult)
539 {
540 rc = RTStrCopyEx(pszResult, cchSubStr + 1, pszSource + offStart, cchSubStr);
541 if (RT_SUCCESS(rc))
542 {
543 *ppszOutput = pszResult;
544 *pcbOutput = (uint32_t)(cchSubStr + 1);
545 rc = VINF_SUCCESS;
546 }
547 else
548 {
549 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment. rc = %Rrc\n", rc));
550 RTMemFree(pszResult);
551 }
552 }
553 else
554 {
555 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment\n"));
556 rc = VERR_NO_MEMORY;
557 }
558 }
559 else
560 {
561 LogRelFlowFunc(("Error: CF_HTML out of bounds - offStart=%#x offEnd=%#x cch=%#x\n", offStart, offEnd, cch));
562 rc = VERR_INVALID_PARAMETER;
563 }
564 }
565 else
566 {
567 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment. rc = %Rrc\n", rc));
568 rc = VERR_INVALID_PARAMETER;
569 }
570 }
571 else
572 {
573 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected StartFragment. rc = %Rrc\n", rc));
574 rc = VERR_INVALID_PARAMETER;
575 }
576
577 return rc;
578}
579
580/**
581 * Converts source UTF-8 MIME HTML clipboard data to UTF-8 CF_HTML format.
582 *
583 * This is just encapsulation work, slapping a header on the data.
584 *
585 * It allocates [..]
586 *
587 * Calculations:
588 * Header length = format Length + (2*(10 - 5('%010d'))('digits')) - 2('%s') = format length + 8
589 * EndHtml = Header length + fragment length
590 * StartHtml = 105(constant)
591 * StartFragment = 141(constant) may vary if the header html content will be extended
592 * EndFragment = Header length + fragment length - 38(ending length)
593 *
594 * @param pszSource Source buffer that contains utf-16 string in mime html format
595 * @param cb Size of source buffer in bytes
596 * @param ppszOutput Where to return the allocated output buffer to put converted UTF-8
597 * CF_HTML clipboard data. This function allocates memory for this.
598 * @param pcbOutput Where to return the size of allocated result buffer in bytes/chars, including zero terminator
599 *
600 * @note output buffer should be free using RTMemFree()
601 * @note Everything inside of fragment can be UTF8. Windows allows it. Everything in header should be Latin1.
602 */
603int SharedClipboardWinConvertMIMEToCFHTML(const char *pszSource, size_t cb, char **ppszOutput, uint32_t *pcbOutput)
604{
605 Assert(ppszOutput);
606 Assert(pcbOutput);
607 Assert(pszSource);
608 Assert(cb);
609
610 /* construct CF_HTML formatted string */
611 char *pszResult = NULL;
612 size_t cchFragment;
613 int rc = RTStrNLenEx(pszSource, cb, &cchFragment);
614 if (!RT_SUCCESS(rc))
615 {
616 LogRelFlowFunc(("Error: invalid source fragment. rc = %Rrc\n"));
617 return VERR_INVALID_PARAMETER;
618 }
619
620 /*
621 @StartHtml - pos before <html>
622 @EndHtml - whole size of text excluding ending zero char
623 @StartFragment - pos after <!--StartFragment-->
624 @EndFragment - pos before <!--EndFragment-->
625 @note: all values includes CR\LF inserted into text
626 Calculations:
627 Header length = format Length + (3*6('digits')) - 2('%s') = format length + 16 (control value - 183)
628 EndHtml = Header length + fragment length
629 StartHtml = 105(constant)
630 StartFragment = 143(constant)
631 EndFragment = Header length + fragment length - 40(ending length)
632 */
633 static const char s_szFormatSample[] =
634 /* 0: */ "Version:1.0\r\n"
635 /* 13: */ "StartHTML:000000101\r\n"
636 /* 34: */ "EndHTML:%0000009u\r\n" // END HTML = Header length + fragment length
637 /* 53: */ "StartFragment:000000137\r\n"
638 /* 78: */ "EndFragment:%0000009u\r\n"
639 /* 101: */ "<html>\r\n"
640 /* 109: */ "<body>\r\n"
641 /* 117: */ "<!--StartFragment-->"
642 /* 137: */ "%s"
643 /* 137+2: */ "<!--EndFragment-->\r\n"
644 /* 157+2: */ "</body>\r\n"
645 /* 166+2: */ "</html>\r\n";
646 /* 175+2: */
647 AssertCompile(sizeof(s_szFormatSample) == 175 + 2 + 1);
648
649 /* calculate parameters of CF_HTML header */
650 size_t cchHeader = sizeof(s_szFormatSample) - 1;
651 size_t offEndHtml = cchHeader + cchFragment;
652 size_t offEndFragment = cchHeader + cchFragment - 38; /* 175-137 = 38 */
653 pszResult = (char *)RTMemAlloc(offEndHtml + 1);
654 if (pszResult == NULL)
655 {
656 LogRelFlowFunc(("Error: Cannot allocate memory for result buffer. rc = %Rrc\n"));
657 return VERR_NO_MEMORY;
658 }
659
660 /* format result CF_HTML string */
661 size_t cchFormatted = RTStrPrintf(pszResult, offEndHtml + 1,
662 s_szFormatSample, offEndHtml, offEndFragment, pszSource);
663 Assert(offEndHtml == cchFormatted); NOREF(cchFormatted);
664
665#ifdef VBOX_STRICT
666 /* Control calculations. check consistency.*/
667 static const char s_szStartFragment[] = "<!--StartFragment-->";
668 static const char s_szEndFragment[] = "<!--EndFragment-->";
669
670 /* check 'StartFragment:' value */
671 const char *pszRealStartFragment = RTStrStr(pszResult, s_szStartFragment);
672 Assert(&pszRealStartFragment[sizeof(s_szStartFragment) - 1] - pszResult == 137);
673
674 /* check 'EndFragment:' value */
675 const char *pszRealEndFragment = RTStrStr(pszResult, s_szEndFragment);
676 Assert((size_t)(pszRealEndFragment - pszResult) == offEndFragment);
677#endif
678
679 *ppszOutput = pszResult;
680 *pcbOutput = (uint32_t)cchFormatted + 1;
681 Assert(*pcbOutput == cchFormatted + 1);
682
683 return VINF_SUCCESS;
684}
685
686/**
687 * Handles the WM_CHANGECBCHAIN code.
688 *
689 * @returns LRESULT
690 * @param pWinCtx Windows context to use.
691 * @param hWnd Window handle to use.
692 * @param msg Message ID to pass on.
693 * @param wParam wParam to pass on
694 * @param lParam lParam to pass on.
695 */
696LRESULT SharedClipboardWinHandleWMChangeCBChain(PSHCLWINCTX pWinCtx,
697 HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
698{
699 LRESULT lresultRc = 0;
700
701 LogFlowFuncEnter();
702
703 if (SharedClipboardWinIsNewAPI(&pWinCtx->newAPI))
704 {
705 lresultRc = DefWindowProc(hWnd, msg, wParam, lParam);
706 }
707 else /* Old API */
708 {
709 HWND hwndRemoved = (HWND)wParam;
710 HWND hwndNext = (HWND)lParam;
711
712 if (hwndRemoved == pWinCtx->hWndNextInChain)
713 {
714 /* The window that was next to our in the chain is being removed.
715 * Relink to the new next window.
716 */
717 pWinCtx->hWndNextInChain = hwndNext;
718 }
719 else
720 {
721 if (pWinCtx->hWndNextInChain)
722 {
723 /* Pass the message further. */
724 DWORD_PTR dwResult;
725 lresultRc = SendMessageTimeout(pWinCtx->hWndNextInChain, WM_CHANGECBCHAIN, wParam, lParam, 0,
726 SHCL_WIN_CBCHAIN_TIMEOUT_MS,
727 &dwResult);
728 if (!lresultRc)
729 lresultRc = (LRESULT)dwResult;
730 }
731 }
732 }
733
734 LogFlowFunc(("lresultRc=%ld\n", lresultRc));
735 return lresultRc;
736}
737
738/**
739 * Handles the WM_DESTROY code.
740 *
741 * @returns VBox status code.
742 * @param pWinCtx Windows context to use.
743 */
744int SharedClipboardWinHandleWMDestroy(PSHCLWINCTX pWinCtx)
745{
746 LogFlowFuncEnter();
747
748 int rc = VINF_SUCCESS;
749
750 /* MS recommends to remove from Clipboard chain in this callback. */
751 SharedClipboardWinChainRemove(pWinCtx);
752
753 if (pWinCtx->oldAPI.timerRefresh)
754 {
755 Assert(pWinCtx->hWnd);
756 KillTimer(pWinCtx->hWnd, 0);
757 }
758
759 LogFlowFuncLeaveRC(rc);
760 return rc;
761}
762
763/**
764 * Handles the WM_RENDERALLFORMATS message.
765 *
766 * @returns VBox status code.
767 * @param pWinCtx Windows context to use.
768 * @param hWnd Window handle to use.
769 */
770int SharedClipboardWinHandleWMRenderAllFormats(PSHCLWINCTX pWinCtx, HWND hWnd)
771{
772 RT_NOREF(pWinCtx);
773
774 LogFlowFuncEnter();
775
776 /* Do nothing. The clipboard formats will be unavailable now, because the
777 * windows is to be destroyed and therefore the guest side becomes inactive.
778 */
779 int rc = SharedClipboardWinOpen(hWnd);
780 if (RT_SUCCESS(rc))
781 {
782 SharedClipboardWinClear();
783 SharedClipboardWinClose();
784 }
785
786 LogFlowFuncLeaveRC(rc);
787 return rc;
788}
789
790/**
791 * Handles the WM_TIMER code, which is needed if we're running with the so-called "old" Windows clipboard API.
792 * Does nothing if we're running with the "new" Windows API.
793 *
794 * @returns VBox status code.
795 * @param pWinCtx Windows context to use.
796 */
797int SharedClipboardWinHandleWMTimer(PSHCLWINCTX pWinCtx)
798{
799 int rc = VINF_SUCCESS;
800
801 if (!SharedClipboardWinIsNewAPI(&pWinCtx->newAPI)) /* Only run when using the "old" Windows API. */
802 {
803 LogFlowFuncEnter();
804
805 HWND hViewer = GetClipboardViewer();
806
807 /* Re-register ourselves in the clipboard chain if our last ping
808 * timed out or there seems to be no valid chain. */
809 if (!hViewer || pWinCtx->oldAPI.fCBChainPingInProcess)
810 {
811 SharedClipboardWinChainRemove(pWinCtx);
812 SharedClipboardWinChainAdd(pWinCtx);
813 }
814
815 /* Start a new ping by passing a dummy WM_CHANGECBCHAIN to be
816 * processed by ourselves to the chain. */
817 pWinCtx->oldAPI.fCBChainPingInProcess = TRUE;
818
819 hViewer = GetClipboardViewer();
820 if (hViewer)
821 SendMessageCallback(hViewer, WM_CHANGECBCHAIN, (WPARAM)pWinCtx->hWndNextInChain, (LPARAM)pWinCtx->hWndNextInChain,
822 SharedClipboardWinChainPingProc, (ULONG_PTR)pWinCtx);
823 }
824
825 LogFlowFuncLeaveRC(rc);
826 return rc;
827}
828
829/**
830 * Announces a clipboard format to the Windows clipboard.
831 *
832 * The actual rendering (setting) of the clipboard data will be done later with
833 * a separate WM_RENDERFORMAT message.
834 *
835 * @returns VBox status code. VERR_NOT_SUPPORTED if the format is not supported / handled.
836 * @param pWinCtx Windows context to use.
837 * @param fFormats Clipboard format(s) to announce.
838 */
839int SharedClipboardWinAnnounceFormats(PSHCLWINCTX pWinCtx, SHCLFORMATS fFormats)
840{
841 LogFunc(("fFormats=0x%x\n", fFormats));
842
843 /*
844 * Set the clipboard formats.
845 */
846 static struct
847 {
848 uint32_t fVBoxFormat;
849 UINT uWinFormat;
850 const char *pszWinFormat;
851 const char *pszLog;
852 } s_aFormats[] =
853 {
854 { VBOX_SHCL_FMT_UNICODETEXT, CF_UNICODETEXT, NULL, "CF_UNICODETEXT" },
855 { VBOX_SHCL_FMT_BITMAP, CF_DIB, NULL, "CF_DIB" },
856 { VBOX_SHCL_FMT_HTML, 0, SHCL_WIN_REGFMT_HTML, "SHCL_WIN_REGFMT_HTML" },
857 };
858 unsigned cSuccessfullySet = 0;
859 SHCLFORMATS fFormatsLeft = fFormats;
860 int rc = VINF_SUCCESS;
861 for (uintptr_t i = 0; i < RT_ELEMENTS(s_aFormats) && fFormatsLeft != 0; i++)
862 {
863 if (fFormatsLeft & s_aFormats[i].fVBoxFormat)
864 {
865 LogFunc(("%s\n", s_aFormats[i].pszLog));
866 fFormatsLeft &= ~s_aFormats[i].fVBoxFormat;
867
868 /* Reg format if needed: */
869 UINT uWinFormat = s_aFormats[i].uWinFormat;
870 if (!uWinFormat)
871 {
872 uWinFormat = RegisterClipboardFormat(s_aFormats[i].pszWinFormat);
873 AssertContinue(uWinFormat != 0);
874 }
875
876 /* Tell the clipboard we've got data upon a request. We check the
877 last error here as hClip will be NULL even on success (despite
878 what MSDN says). */
879 SetLastError(NO_ERROR);
880 HANDLE hClip = SetClipboardData(uWinFormat, NULL);
881 DWORD dwErr = GetLastError();
882 if (dwErr == NO_ERROR || hClip != NULL)
883 cSuccessfullySet++;
884 else
885 {
886 AssertMsgFailed(("%s/%u: %u\n", s_aFormats[i].pszLog, uWinFormat, dwErr));
887 rc = RTErrConvertFromWin32(dwErr);
888 }
889 }
890 }
891
892 /*
893 * Consider setting anything a success, converting any error into
894 * informational status. Unsupport error only happens if all formats
895 * were unsupported.
896 */
897 if (cSuccessfullySet > 0)
898 {
899 pWinCtx->hWndClipboardOwnerUs = GetClipboardOwner();
900 if (RT_FAILURE(rc))
901 rc = -rc;
902 }
903 else if (RT_SUCCESS(rc) && fFormatsLeft != 0)
904 {
905 LogFunc(("Unsupported formats: %#x (%#x)\n", fFormatsLeft, fFormats));
906 rc = VERR_NOT_SUPPORTED;
907 }
908
909 LogFlowFuncLeaveRC(rc);
910 return rc;
911}
912
913#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
914/**
915 * Creates an Shared Clipboard transfer by announcing transfer data (via IDataObject) to Windows.
916 *
917 * This creates the necessary IDataObject + IStream implementations and initiates the actual transfers required for getting
918 * the meta data. Whether or not the actual (file++) transfer(s) are happening is up to the user (at some point) later then.
919 *
920 * @returns VBox status code.
921 * @param pWinCtx Windows context to use.
922 * @param pTransferCtxCtx Transfer contextto use.
923 * @param pTransfer Shared Clipboard transfer to use.
924 */
925int SharedClipboardWinTransferCreate(PSHCLWINCTX pWinCtx, PSHCLTRANSFER pTransfer)
926{
927 AssertPtrReturn(pTransfer, VERR_INVALID_POINTER);
928
929 LogFlowFunc(("pWinCtx=%p\n", pWinCtx));
930
931 AssertReturn(pTransfer->pvUser == NULL, VERR_WRONG_ORDER);
932
933 /* Make sure to enter the critical section before setting the clipboard data, as otherwise WM_CLIPBOARDUPDATE
934 * might get called *before* we had the opportunity to set pWinCtx->hWndClipboardOwnerUs below. */
935 int rc = RTCritSectEnter(&pWinCtx->CritSect);
936 if (RT_SUCCESS(rc))
937 {
938 SharedClipboardWinTransferCtx *pWinURITransferCtx = new SharedClipboardWinTransferCtx();
939 if (pWinURITransferCtx)
940 {
941 pTransfer->pvUser = pWinURITransferCtx;
942 pTransfer->cbUser = sizeof(SharedClipboardWinTransferCtx);
943
944 pWinURITransferCtx->pDataObj = new SharedClipboardWinDataObject(pTransfer);
945 if (pWinURITransferCtx->pDataObj)
946 {
947 rc = pWinURITransferCtx->pDataObj->Init();
948 if (RT_SUCCESS(rc))
949 {
950 SharedClipboardWinClose();
951 /* Note: Clipboard must be closed first before calling OleSetClipboard(). */
952
953 /** @todo There is a potential race between SharedClipboardWinClose() and OleSetClipboard(),
954 * where another application could own the clipboard (open), and thus the call to
955 * OleSetClipboard() will fail. Needs (better) fixing. */
956 HRESULT hr = S_OK;
957
958 for (unsigned uTries = 0; uTries < 3; uTries++)
959 {
960 hr = OleSetClipboard(pWinURITransferCtx->pDataObj);
961 if (SUCCEEDED(hr))
962 {
963 Assert(OleIsCurrentClipboard(pWinURITransferCtx->pDataObj) == S_OK); /* Sanity. */
964
965 /*
966 * Calling OleSetClipboard() changed the clipboard owner, which in turn will let us receive
967 * a WM_CLIPBOARDUPDATE message. To not confuse ourselves with our own clipboard owner changes,
968 * save a new window handle and deal with it in WM_CLIPBOARDUPDATE.
969 */
970 pWinCtx->hWndClipboardOwnerUs = GetClipboardOwner();
971
972 LogFlowFunc(("hWndClipboardOwnerUs=%p\n", pWinCtx->hWndClipboardOwnerUs));
973 break;
974 }
975
976 LogFlowFunc(("Failed with %Rhrc (try %u/3)\n", hr, uTries + 1));
977 RTThreadSleep(500); /* Wait a bit. */
978 }
979
980 if (FAILED(hr))
981 {
982 rc = VERR_ACCESS_DENIED; /** @todo Fudge; fix this. */
983 LogRel(("Shared Clipboard: Failed with %Rhrc when setting data object to clipboard\n", hr));
984 }
985 }
986 }
987 else
988 rc = VERR_NO_MEMORY;
989 }
990 else
991 rc = VERR_NO_MEMORY;
992
993 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
994 AssertRC(rc2);
995 }
996
997 LogFlowFuncLeaveRC(rc);
998 return rc;
999}
1000
1001/**
1002 * Destroys implementation-specific data for an Shared Clipboard transfer.
1003 *
1004 * @param pWinCtx Windows context to use.
1005 * @param pTransfer Shared Clipboard transfer to create implementation-specific data for.
1006 */
1007void SharedClipboardWinTransferDestroy(PSHCLWINCTX pWinCtx, PSHCLTRANSFER pTransfer)
1008{
1009 RT_NOREF(pWinCtx);
1010
1011 if (!pTransfer)
1012 return;
1013
1014 LogFlowFuncEnter();
1015
1016 if (pTransfer->pvUser)
1017 {
1018 Assert(pTransfer->cbUser == sizeof(SharedClipboardWinTransferCtx));
1019 SharedClipboardWinTransferCtx *pWinURITransferCtx = (SharedClipboardWinTransferCtx *)pTransfer->pvUser;
1020 Assert(pWinURITransferCtx);
1021
1022 if (pWinURITransferCtx->pDataObj)
1023 {
1024 delete pWinURITransferCtx->pDataObj;
1025 pWinURITransferCtx->pDataObj = NULL;
1026 }
1027
1028 delete pWinURITransferCtx;
1029
1030 pTransfer->pvUser = NULL;
1031 pTransfer->cbUser = 0;
1032 }
1033}
1034
1035/**
1036 * Retrieves the roots for a transfer by opening the clipboard and getting the clipboard data
1037 * as string list (CF_HDROP), assigning it to the transfer as roots then.
1038 *
1039 * @returns VBox status code.
1040 * @param pWinCtx Windows context to use.
1041 * @param pTransfer Transfer to get roots for.
1042 */
1043int SharedClipboardWinGetRoots(PSHCLWINCTX pWinCtx, PSHCLTRANSFER pTransfer)
1044{
1045 AssertPtrReturn(pWinCtx, VERR_INVALID_POINTER);
1046 AssertPtrReturn(pTransfer, VERR_INVALID_POINTER);
1047
1048 Assert(ShClTransferGetSource(pTransfer) == SHCLSOURCE_LOCAL); /* Sanity. */
1049
1050 int rc = SharedClipboardWinOpen(pWinCtx->hWnd);
1051 if (RT_SUCCESS(rc))
1052 {
1053 /* The data data in CF_HDROP format, as the files are locally present and don't need to be
1054 * presented as a IDataObject or IStream. */
1055 HANDLE hClip = hClip = GetClipboardData(CF_HDROP);
1056 if (hClip)
1057 {
1058 HDROP hDrop = (HDROP)GlobalLock(hClip);
1059 if (hDrop)
1060 {
1061 char *papszList = NULL;
1062 uint32_t cbList;
1063 rc = SharedClipboardWinDropFilesToStringList((DROPFILES *)hDrop, &papszList, &cbList);
1064
1065 GlobalUnlock(hClip);
1066
1067 if (RT_SUCCESS(rc))
1068 {
1069 rc = ShClTransferRootsSet(pTransfer,
1070 papszList, cbList + 1 /* Include termination */);
1071 RTStrFree(papszList);
1072 }
1073 }
1074 else
1075 LogRel(("Shared Clipboard: Unable to lock clipboard data, last error: %ld\n", GetLastError()));
1076 }
1077 else
1078 LogRel(("Shared Clipboard: Unable to retrieve clipboard data from clipboard (CF_HDROP), last error: %ld\n",
1079 GetLastError()));
1080
1081 SharedClipboardWinClose();
1082 }
1083
1084 LogFlowFuncLeaveRC(rc);
1085 return rc;
1086}
1087
1088/**
1089 * Converts a DROPFILES (HDROP) structure to a string list, separated by \r\n.
1090 * Does not do any locking on the input data.
1091 *
1092 * @returns VBox status code.
1093 * @param pDropFiles Pointer to DROPFILES structure to convert.
1094 * @param papszList Where to store the allocated string list.
1095 * @param pcbList Where to store the size (in bytes) of the allocated string list.
1096 */
1097int SharedClipboardWinDropFilesToStringList(DROPFILES *pDropFiles, char **papszList, uint32_t *pcbList)
1098{
1099 AssertPtrReturn(pDropFiles, VERR_INVALID_POINTER);
1100 AssertPtrReturn(papszList, VERR_INVALID_POINTER);
1101 AssertPtrReturn(pcbList, VERR_INVALID_POINTER);
1102
1103 /* Do we need to do Unicode stuff? */
1104 const bool fUnicode = RT_BOOL(pDropFiles->fWide);
1105
1106 /* Get the offset of the file list. */
1107 Assert(pDropFiles->pFiles >= sizeof(DROPFILES));
1108
1109 /* Note: This is *not* pDropFiles->pFiles! DragQueryFile only
1110 * will work with the plain storage medium pointer! */
1111 HDROP hDrop = (HDROP)(pDropFiles);
1112
1113 int rc = VINF_SUCCESS;
1114
1115 /* First, get the file count. */
1116 /** @todo Does this work on Windows 2000 / NT4? */
1117 char *pszFiles = NULL;
1118 uint32_t cchFiles = 0;
1119 UINT cFiles = DragQueryFile(hDrop, UINT32_MAX /* iFile */, NULL /* lpszFile */, 0 /* cchFile */);
1120
1121 LogFlowFunc(("Got %RU16 file(s), fUnicode=%RTbool\n", cFiles, fUnicode));
1122
1123 for (UINT i = 0; i < cFiles; i++)
1124 {
1125 UINT cchFile = DragQueryFile(hDrop, i /* File index */, NULL /* Query size first */, 0 /* cchFile */);
1126 Assert(cchFile);
1127
1128 if (RT_FAILURE(rc))
1129 break;
1130
1131 char *pszFileUtf8 = NULL; /* UTF-8 version. */
1132 UINT cchFileUtf8 = 0;
1133 if (fUnicode)
1134 {
1135 /* Allocate enough space (including terminator). */
1136 WCHAR *pwszFile = (WCHAR *)RTMemAlloc((cchFile + 1) * sizeof(WCHAR));
1137 if (pwszFile)
1138 {
1139 const UINT cwcFileUtf16 = DragQueryFileW(hDrop, i /* File index */,
1140 pwszFile, cchFile + 1 /* Include terminator */);
1141
1142 AssertMsg(cwcFileUtf16 == cchFile, ("cchFileUtf16 (%RU16) does not match cchFile (%RU16)\n",
1143 cwcFileUtf16, cchFile));
1144 RT_NOREF(cwcFileUtf16);
1145
1146 rc = RTUtf16ToUtf8(pwszFile, &pszFileUtf8);
1147 if (RT_SUCCESS(rc))
1148 {
1149 cchFileUtf8 = (UINT)strlen(pszFileUtf8);
1150 Assert(cchFileUtf8);
1151 }
1152
1153 RTMemFree(pwszFile);
1154 }
1155 else
1156 rc = VERR_NO_MEMORY;
1157 }
1158 else /* ANSI */
1159 {
1160 /* Allocate enough space (including terminator). */
1161 char *pszFileANSI = (char *)RTMemAlloc((cchFile + 1) * sizeof(char));
1162 UINT cchFileANSI = 0;
1163 if (pszFileANSI)
1164 {
1165 cchFileANSI = DragQueryFileA(hDrop, i /* File index */,
1166 pszFileANSI, cchFile + 1 /* Include terminator */);
1167
1168 AssertMsg(cchFileANSI == cchFile, ("cchFileANSI (%RU16) does not match cchFile (%RU16)\n",
1169 cchFileANSI, cchFile));
1170
1171 /* Convert the ANSI codepage to UTF-8. */
1172 rc = RTStrCurrentCPToUtf8(&pszFileUtf8, pszFileANSI);
1173 if (RT_SUCCESS(rc))
1174 {
1175 cchFileUtf8 = (UINT)strlen(pszFileUtf8);
1176 }
1177 }
1178 else
1179 rc = VERR_NO_MEMORY;
1180 }
1181
1182 if (RT_SUCCESS(rc))
1183 {
1184 LogFlowFunc(("\tFile: %s (cchFile=%RU16)\n", pszFileUtf8, cchFileUtf8));
1185
1186 LogRel2(("Shared Clipboard: Adding file '%s' to transfer\n", pszFileUtf8));
1187
1188 rc = RTStrAAppendExN(&pszFiles, 1 /* cPairs */, pszFileUtf8, strlen(pszFileUtf8));
1189 cchFiles += (uint32_t)strlen(pszFileUtf8);
1190 }
1191
1192 if (pszFileUtf8)
1193 RTStrFree(pszFileUtf8);
1194
1195 if (RT_FAILURE(rc))
1196 {
1197 LogFunc(("Error handling file entry #%u, rc=%Rrc\n", i, rc));
1198 break;
1199 }
1200
1201 /* Add separation between filenames.
1202 * Note: Also do this for the last element of the list. */
1203 rc = RTStrAAppendExN(&pszFiles, 1 /* cPairs */, "\r\n", 2 /* Bytes */);
1204 if (RT_SUCCESS(rc))
1205 cchFiles += 2; /* Include \r\n */
1206 }
1207
1208 if (RT_SUCCESS(rc))
1209 {
1210 cchFiles += 1; /* Add string termination. */
1211 uint32_t cbFiles = cchFiles * sizeof(char); /* UTF-8. */
1212
1213 LogFlowFunc(("cFiles=%u, cchFiles=%RU32, cbFiles=%RU32, pszFiles=0x%p\n",
1214 cFiles, cchFiles, cbFiles, pszFiles));
1215
1216 *papszList = pszFiles;
1217 *pcbList = cbFiles;
1218 }
1219 else
1220 {
1221 if (pszFiles)
1222 RTStrFree(pszFiles);
1223 }
1224
1225 LogFlowFuncLeaveRC(rc);
1226 return rc;
1227}
1228#endif /* VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS */
1229
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette