VirtualBox

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

Last change on this file since 93288 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

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