VirtualBox

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

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

SharedClipboardSvc,Vbgl: Reviewed and adjusted the handling of the VBOX_SHCL_GUEST_FN_REPORT_FORMATS message, paddling back the parameter changes from the 6.1 dev cycle and fixing a couple of bugs introduced. Also documented the message and renamed it to a more sensible name. Dropped the new Vbgl method, renaming the old one. bugref:9437

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