VirtualBox

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

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

SharedClipboard: Eliminated SHCLFORMATDATA and did some minor darwin cleanups. bugref:9620

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.3 KB
Line 
1/* $Id: clipboard-win.cpp 83624 2020-04-08 16:29:25Z vboxsync $ */
2/** @file
3 * Shared Clipboard: Windows-specific functions for clipboard handling.
4 */
5
6/*
7 * Copyright (C) 2006-2020 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 pfFormats Where to store the retrieved formats.
423 */
424int SharedClipboardWinGetFormats(PSHCLWINCTX pCtx, PSHCLFORMATS pfFormats)
425{
426 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
427 AssertPtrReturn(pfFormats, 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 LogFlowFunc(("fFormats=%#x\n", fFormats));
442 }
443 else
444 LogFunc(("Failed with rc=%Rrc (fFormats=%#x)\n", rc, fFormats));
445
446 *pfFormats = fFormats;
447 return rc;
448}
449
450/**
451 * Extracts a field value from CF_HTML data.
452 *
453 * @returns VBox status code.
454 * @param pszSrc source in CF_HTML format.
455 * @param pszOption Name of CF_HTML field.
456 * @param puValue Where to return extracted value of CF_HTML field.
457 */
458int SharedClipboardWinGetCFHTMLHeaderValue(const char *pszSrc, const char *pszOption, uint32_t *puValue)
459{
460 AssertPtrReturn(pszSrc, VERR_INVALID_POINTER);
461 AssertPtrReturn(pszOption, VERR_INVALID_POINTER);
462
463 int rc = VERR_INVALID_PARAMETER;
464
465 const char *pszOptionValue = RTStrStr(pszSrc, pszOption);
466 if (pszOptionValue)
467 {
468 size_t cchOption = strlen(pszOption);
469 Assert(cchOption);
470
471 rc = RTStrToUInt32Ex(pszOptionValue + cchOption, NULL, 10, puValue);
472 }
473 return rc;
474}
475
476/**
477 * Check that the source string contains CF_HTML struct.
478 *
479 * @returns @c true if the @a pszSource string is in CF_HTML format.
480 * @param pszSource Source string to check.
481 */
482bool SharedClipboardWinIsCFHTML(const char *pszSource)
483{
484 return RTStrStr(pszSource, "Version:") != NULL
485 && RTStrStr(pszSource, "StartHTML:") != NULL;
486}
487
488/**
489 * Converts clipboard data from CF_HTML format to MIME clipboard format.
490 *
491 * Returns allocated buffer that contains html converted to text/html mime type
492 *
493 * @returns VBox status code.
494 * @param pszSource The input.
495 * @param cch The length of the input.
496 * @param ppszOutput Where to return the result. Free using RTMemFree.
497 * @param pcbOutput Where to the return length of the result (bytes/chars).
498 */
499int SharedClipboardWinConvertCFHTMLToMIME(const char *pszSource, const uint32_t cch, char **ppszOutput, uint32_t *pcbOutput)
500{
501 Assert(pszSource);
502 Assert(cch);
503 Assert(ppszOutput);
504 Assert(pcbOutput);
505
506 uint32_t offStart;
507 int rc = SharedClipboardWinGetCFHTMLHeaderValue(pszSource, "StartFragment:", &offStart);
508 if (RT_SUCCESS(rc))
509 {
510 uint32_t offEnd;
511 rc = SharedClipboardWinGetCFHTMLHeaderValue(pszSource, "EndFragment:", &offEnd);
512 if (RT_SUCCESS(rc))
513 {
514 if ( offStart > 0
515 && offEnd > 0
516 && offEnd > offStart
517 && offEnd <= cch)
518 {
519 uint32_t cchSubStr = offEnd - offStart;
520 char *pszResult = (char *)RTMemAlloc(cchSubStr + 1);
521 if (pszResult)
522 {
523 rc = RTStrCopyEx(pszResult, cchSubStr + 1, pszSource + offStart, cchSubStr);
524 if (RT_SUCCESS(rc))
525 {
526 *ppszOutput = pszResult;
527 *pcbOutput = (uint32_t)(cchSubStr + 1);
528 rc = VINF_SUCCESS;
529 }
530 else
531 {
532 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment. rc = %Rrc\n", rc));
533 RTMemFree(pszResult);
534 }
535 }
536 else
537 {
538 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment\n"));
539 rc = VERR_NO_MEMORY;
540 }
541 }
542 else
543 {
544 LogRelFlowFunc(("Error: CF_HTML out of bounds - offStart=%#x offEnd=%#x cch=%#x\n", offStart, offEnd, cch));
545 rc = VERR_INVALID_PARAMETER;
546 }
547 }
548 else
549 {
550 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment. rc = %Rrc\n", rc));
551 rc = VERR_INVALID_PARAMETER;
552 }
553 }
554 else
555 {
556 LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected StartFragment. rc = %Rrc\n", rc));
557 rc = VERR_INVALID_PARAMETER;
558 }
559
560 return rc;
561}
562
563/**
564 * Converts source UTF-8 MIME HTML clipboard data to UTF-8 CF_HTML format.
565 *
566 * This is just encapsulation work, slapping a header on the data.
567 *
568 * It allocates [..]
569 *
570 * Calculations:
571 * Header length = format Length + (2*(10 - 5('%010d'))('digits')) - 2('%s') = format length + 8
572 * EndHtml = Header length + fragment length
573 * StartHtml = 105(constant)
574 * StartFragment = 141(constant) may vary if the header html content will be extended
575 * EndFragment = Header length + fragment length - 38(ending length)
576 *
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 Assert(ppszOutput);
589 Assert(pcbOutput);
590 Assert(pszSource);
591 Assert(cb);
592
593 /* construct CF_HTML formatted string */
594 char *pszResult = NULL;
595 size_t cchFragment;
596 int rc = RTStrNLenEx(pszSource, cb, &cchFragment);
597 if (!RT_SUCCESS(rc))
598 {
599 LogRelFlowFunc(("Error: invalid source fragment. rc = %Rrc\n"));
600 return VERR_INVALID_PARAMETER;
601 }
602
603 /*
604 @StartHtml - pos before <html>
605 @EndHtml - whole size of text excluding ending zero char
606 @StartFragment - pos after <!--StartFragment-->
607 @EndFragment - pos before <!--EndFragment-->
608 @note: all values includes CR\LF inserted into text
609 Calculations:
610 Header length = format Length + (3*6('digits')) - 2('%s') = format length + 16 (control value - 183)
611 EndHtml = Header length + fragment length
612 StartHtml = 105(constant)
613 StartFragment = 143(constant)
614 EndFragment = Header length + fragment length - 40(ending length)
615 */
616 static const char s_szFormatSample[] =
617 /* 0: */ "Version:1.0\r\n"
618 /* 13: */ "StartHTML:000000101\r\n"
619 /* 34: */ "EndHTML:%0000009u\r\n" // END HTML = Header length + fragment length
620 /* 53: */ "StartFragment:000000137\r\n"
621 /* 78: */ "EndFragment:%0000009u\r\n"
622 /* 101: */ "<html>\r\n"
623 /* 109: */ "<body>\r\n"
624 /* 117: */ "<!--StartFragment-->"
625 /* 137: */ "%s"
626 /* 137+2: */ "<!--EndFragment-->\r\n"
627 /* 157+2: */ "</body>\r\n"
628 /* 166+2: */ "</html>\r\n";
629 /* 175+2: */
630 AssertCompile(sizeof(s_szFormatSample) == 175 + 2 + 1);
631
632 /* calculate parameters of CF_HTML header */
633 size_t cchHeader = sizeof(s_szFormatSample) - 1;
634 size_t offEndHtml = cchHeader + cchFragment;
635 size_t offEndFragment = cchHeader + cchFragment - 38; /* 175-137 = 38 */
636 pszResult = (char *)RTMemAlloc(offEndHtml + 1);
637 if (pszResult == NULL)
638 {
639 LogRelFlowFunc(("Error: Cannot allocate memory for result buffer. rc = %Rrc\n"));
640 return VERR_NO_MEMORY;
641 }
642
643 /* format result CF_HTML string */
644 size_t cchFormatted = RTStrPrintf(pszResult, offEndHtml + 1,
645 s_szFormatSample, offEndHtml, offEndFragment, pszSource);
646 Assert(offEndHtml == cchFormatted); NOREF(cchFormatted);
647
648#ifdef VBOX_STRICT
649 /* Control calculations. check consistency.*/
650 static const char s_szStartFragment[] = "<!--StartFragment-->";
651 static const char s_szEndFragment[] = "<!--EndFragment-->";
652
653 /* check 'StartFragment:' value */
654 const char *pszRealStartFragment = RTStrStr(pszResult, s_szStartFragment);
655 Assert(&pszRealStartFragment[sizeof(s_szStartFragment) - 1] - pszResult == 137);
656
657 /* check 'EndFragment:' value */
658 const char *pszRealEndFragment = RTStrStr(pszResult, s_szEndFragment);
659 Assert((size_t)(pszRealEndFragment - pszResult) == offEndFragment);
660#endif
661
662 *ppszOutput = pszResult;
663 *pcbOutput = (uint32_t)cchFormatted + 1;
664 Assert(*pcbOutput == cchFormatted + 1);
665
666 return VINF_SUCCESS;
667}
668
669/**
670 * Handles the WM_CHANGECBCHAIN code.
671 *
672 * @returns LRESULT
673 * @param pWinCtx Windows context to use.
674 * @param hWnd Window handle to use.
675 * @param msg Message ID to pass on.
676 * @param wParam wParam to pass on
677 * @param lParam lParam to pass on.
678 */
679LRESULT SharedClipboardWinHandleWMChangeCBChain(PSHCLWINCTX pWinCtx,
680 HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
681{
682 LRESULT lresultRc = 0;
683
684 LogFlowFuncEnter();
685
686 if (SharedClipboardWinIsNewAPI(&pWinCtx->newAPI))
687 {
688 lresultRc = DefWindowProc(hWnd, msg, wParam, lParam);
689 }
690 else /* Old API */
691 {
692 HWND hwndRemoved = (HWND)wParam;
693 HWND hwndNext = (HWND)lParam;
694
695 if (hwndRemoved == pWinCtx->hWndNextInChain)
696 {
697 /* The window that was next to our in the chain is being removed.
698 * Relink to the new next window.
699 */
700 pWinCtx->hWndNextInChain = hwndNext;
701 }
702 else
703 {
704 if (pWinCtx->hWndNextInChain)
705 {
706 /* Pass the message further. */
707 DWORD_PTR dwResult;
708 lresultRc = SendMessageTimeout(pWinCtx->hWndNextInChain, WM_CHANGECBCHAIN, wParam, lParam, 0,
709 SHCL_WIN_CBCHAIN_TIMEOUT_MS,
710 &dwResult);
711 if (!lresultRc)
712 lresultRc = (LRESULT)dwResult;
713 }
714 }
715 }
716
717 LogFlowFunc(("lresultRc=%ld\n", lresultRc));
718 return lresultRc;
719}
720
721/**
722 * Handles the WM_DESTROY code.
723 *
724 * @returns VBox status code.
725 * @param pWinCtx Windows context to use.
726 */
727int SharedClipboardWinHandleWMDestroy(PSHCLWINCTX pWinCtx)
728{
729 LogFlowFuncEnter();
730
731 int rc = VINF_SUCCESS;
732
733 /* MS recommends to remove from Clipboard chain in this callback. */
734 SharedClipboardWinChainRemove(pWinCtx);
735
736 if (pWinCtx->oldAPI.timerRefresh)
737 {
738 Assert(pWinCtx->hWnd);
739 KillTimer(pWinCtx->hWnd, 0);
740 }
741
742 LogFlowFuncLeaveRC(rc);
743 return rc;
744}
745
746/**
747 * Handles the WM_RENDERALLFORMATS message.
748 *
749 * @returns VBox status code.
750 * @param pWinCtx Windows context to use.
751 * @param hWnd Window handle to use.
752 */
753int SharedClipboardWinHandleWMRenderAllFormats(PSHCLWINCTX pWinCtx, HWND hWnd)
754{
755 RT_NOREF(pWinCtx);
756
757 LogFlowFuncEnter();
758
759 /* Do nothing. The clipboard formats will be unavailable now, because the
760 * windows is to be destroyed and therefore the guest side becomes inactive.
761 */
762 int rc = SharedClipboardWinOpen(hWnd);
763 if (RT_SUCCESS(rc))
764 {
765 SharedClipboardWinClear();
766 SharedClipboardWinClose();
767 }
768
769 LogFlowFuncLeaveRC(rc);
770 return rc;
771}
772
773/**
774 * Handles the WM_TIMER code, which is needed if we're running with the so-called "old" Windows clipboard API.
775 * Does nothing if we're running with the "new" Windows API.
776 *
777 * @returns VBox status code.
778 * @param pWinCtx Windows context to use.
779 */
780int SharedClipboardWinHandleWMTimer(PSHCLWINCTX pWinCtx)
781{
782 int rc = VINF_SUCCESS;
783
784 if (!SharedClipboardWinIsNewAPI(&pWinCtx->newAPI)) /* Only run when using the "old" Windows API. */
785 {
786 LogFlowFuncEnter();
787
788 HWND hViewer = GetClipboardViewer();
789
790 /* Re-register ourselves in the clipboard chain if our last ping
791 * timed out or there seems to be no valid chain. */
792 if (!hViewer || pWinCtx->oldAPI.fCBChainPingInProcess)
793 {
794 SharedClipboardWinChainRemove(pWinCtx);
795 SharedClipboardWinChainAdd(pWinCtx);
796 }
797
798 /* Start a new ping by passing a dummy WM_CHANGECBCHAIN to be
799 * processed by ourselves to the chain. */
800 pWinCtx->oldAPI.fCBChainPingInProcess = TRUE;
801
802 hViewer = GetClipboardViewer();
803 if (hViewer)
804 SendMessageCallback(hViewer, WM_CHANGECBCHAIN, (WPARAM)pWinCtx->hWndNextInChain, (LPARAM)pWinCtx->hWndNextInChain,
805 SharedClipboardWinChainPingProc, (ULONG_PTR)pWinCtx);
806 }
807
808 LogFlowFuncLeaveRC(rc);
809 return rc;
810}
811
812/**
813 * Announces a clipboard format to the Windows clipboard.
814 *
815 * The actual rendering (setting) of the clipboard data will be done later with
816 * a separate WM_RENDERFORMAT message.
817 *
818 * @returns VBox status code. VERR_NOT_SUPPORTED if the format is not supported / handled.
819 * @param pWinCtx Windows context to use.
820 * @param fFormats Clipboard format(s) to announce.
821 */
822int SharedClipboardWinAnnounceFormats(PSHCLWINCTX pWinCtx, SHCLFORMATS fFormats)
823{
824 LogFunc(("fFormats=0x%x\n", fFormats));
825
826 /*
827 * Set the clipboard formats.
828 */
829 static struct
830 {
831 uint32_t fVBoxFormat;
832 UINT uWinFormat;
833 const char *pszWinFormat;
834 const char *pszLog;
835 } s_aFormats[] =
836 {
837 { VBOX_SHCL_FMT_UNICODETEXT, CF_UNICODETEXT, NULL, "CF_UNICODETEXT" },
838 { VBOX_SHCL_FMT_BITMAP, CF_DIB, NULL, "CF_DIB" },
839 { VBOX_SHCL_FMT_HTML, 0, SHCL_WIN_REGFMT_HTML, "SHCL_WIN_REGFMT_HTML" },
840 };
841 unsigned cSuccessfullySet = 0;
842 SHCLFORMATS fFormatsLeft = fFormats;
843 int rc = VINF_SUCCESS;
844 for (uintptr_t i = 0; i < RT_ELEMENTS(s_aFormats) && fFormatsLeft != 0; i++)
845 {
846 if (fFormatsLeft & s_aFormats[i].fVBoxFormat)
847 {
848 LogFunc(("%s\n", s_aFormats[i].pszLog));
849 fFormatsLeft &= ~s_aFormats[i].fVBoxFormat;
850
851 /* Reg format if needed: */
852 UINT uWinFormat = s_aFormats[i].uWinFormat;
853 if (!uWinFormat)
854 {
855 uWinFormat = RegisterClipboardFormat(s_aFormats[i].pszWinFormat);
856 AssertContinue(uWinFormat != 0);
857 }
858
859 /* Tell the clipboard we've got data upon a request. We check the
860 last error here as hClip will be NULL even on success (despite
861 what MSDN says). */
862 SetLastError(NO_ERROR);
863 HANDLE hClip = SetClipboardData(uWinFormat, NULL);
864 DWORD dwErr = GetLastError();
865 if (dwErr == NO_ERROR || hClip != NULL)
866 cSuccessfullySet++;
867 else
868 {
869 AssertMsgFailed(("%s/%u: %u\n", s_aFormats[i].pszLog, uWinFormat, dwErr));
870 rc = RTErrConvertFromWin32(dwErr);
871 }
872 }
873 }
874
875 /*
876 * Consider setting anything a success, converting any error into
877 * informational status. Unsupport error only happens if all formats
878 * were unsupported.
879 */
880 if (cSuccessfullySet > 0)
881 {
882 pWinCtx->hWndClipboardOwnerUs = GetClipboardOwner();
883 if (RT_FAILURE(rc))
884 rc = -rc;
885 }
886 else if (RT_SUCCESS(rc) && fFormatsLeft != 0)
887 {
888 LogFunc(("Unsupported formats: %#x (%#x)\n", fFormatsLeft, fFormats));
889 rc = VERR_NOT_SUPPORTED;
890 }
891
892 LogFlowFuncLeaveRC(rc);
893 return rc;
894}
895
896#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
897/**
898 * Creates an Shared Clipboard transfer by announcing transfer data (via IDataObject) to Windows.
899 *
900 * This creates the necessary IDataObject + IStream implementations and initiates the actual transfers required for getting
901 * the meta data. Whether or not the actual (file++) transfer(s) are happening is up to the user (at some point) later then.
902 *
903 * @returns VBox status code.
904 * @param pWinCtx Windows context to use.
905 * @param pTransferCtxCtx Transfer contextto use.
906 * @param pTransfer Shared Clipboard transfer to use.
907 */
908int SharedClipboardWinTransferCreate(PSHCLWINCTX pWinCtx, PSHCLTRANSFER pTransfer)
909{
910 AssertPtrReturn(pTransfer, VERR_INVALID_POINTER);
911
912 LogFlowFunc(("pWinCtx=%p\n", pWinCtx));
913
914 AssertReturn(pTransfer->pvUser == NULL, VERR_WRONG_ORDER);
915
916 /* Make sure to enter the critical section before setting the clipboard data, as otherwise WM_CLIPBOARDUPDATE
917 * might get called *before* we had the opportunity to set pWinCtx->hWndClipboardOwnerUs below. */
918 int rc = RTCritSectEnter(&pWinCtx->CritSect);
919 if (RT_SUCCESS(rc))
920 {
921 SharedClipboardWinTransferCtx *pWinURITransferCtx = new SharedClipboardWinTransferCtx();
922 if (pWinURITransferCtx)
923 {
924 pTransfer->pvUser = pWinURITransferCtx;
925 pTransfer->cbUser = sizeof(SharedClipboardWinTransferCtx);
926
927 pWinURITransferCtx->pDataObj = new SharedClipboardWinDataObject(pTransfer);
928 if (pWinURITransferCtx->pDataObj)
929 {
930 rc = pWinURITransferCtx->pDataObj->Init();
931 if (RT_SUCCESS(rc))
932 {
933 SharedClipboardWinClose();
934 /* Note: Clipboard must be closed first before calling OleSetClipboard(). */
935
936 /** @todo There is a potential race between SharedClipboardWinClose() and OleSetClipboard(),
937 * where another application could own the clipboard (open), and thus the call to
938 * OleSetClipboard() will fail. Needs (better) fixing. */
939 HRESULT hr = S_OK;
940
941 for (unsigned uTries = 0; uTries < 3; uTries++)
942 {
943 hr = OleSetClipboard(pWinURITransferCtx->pDataObj);
944 if (SUCCEEDED(hr))
945 {
946 Assert(OleIsCurrentClipboard(pWinURITransferCtx->pDataObj) == S_OK); /* Sanity. */
947
948 /*
949 * Calling OleSetClipboard() changed the clipboard owner, which in turn will let us receive
950 * a WM_CLIPBOARDUPDATE message. To not confuse ourselves with our own clipboard owner changes,
951 * save a new window handle and deal with it in WM_CLIPBOARDUPDATE.
952 */
953 pWinCtx->hWndClipboardOwnerUs = GetClipboardOwner();
954
955 LogFlowFunc(("hWndClipboardOwnerUs=%p\n", pWinCtx->hWndClipboardOwnerUs));
956 break;
957 }
958
959 LogFlowFunc(("Failed with %Rhrc (try %u/3)\n", hr, uTries + 1));
960 RTThreadSleep(500); /* Wait a bit. */
961 }
962
963 if (FAILED(hr))
964 {
965 rc = VERR_ACCESS_DENIED; /** @todo Fudge; fix this. */
966 LogRel(("Shared Clipboard: Failed with %Rhrc when setting data object to clipboard\n", hr));
967 }
968 }
969 }
970 else
971 rc = VERR_NO_MEMORY;
972 }
973 else
974 rc = VERR_NO_MEMORY;
975
976 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
977 AssertRC(rc2);
978 }
979
980 LogFlowFuncLeaveRC(rc);
981 return rc;
982}
983
984/**
985 * Destroys implementation-specific data for an Shared Clipboard transfer.
986 *
987 * @param pWinCtx Windows context to use.
988 * @param pTransfer Shared Clipboard transfer to create implementation-specific data for.
989 */
990void SharedClipboardWinTransferDestroy(PSHCLWINCTX pWinCtx, PSHCLTRANSFER pTransfer)
991{
992 RT_NOREF(pWinCtx);
993
994 if (!pTransfer)
995 return;
996
997 LogFlowFuncEnter();
998
999 if (pTransfer->pvUser)
1000 {
1001 Assert(pTransfer->cbUser == sizeof(SharedClipboardWinTransferCtx));
1002 SharedClipboardWinTransferCtx *pWinURITransferCtx = (SharedClipboardWinTransferCtx *)pTransfer->pvUser;
1003 Assert(pWinURITransferCtx);
1004
1005 if (pWinURITransferCtx->pDataObj)
1006 {
1007 delete pWinURITransferCtx->pDataObj;
1008 pWinURITransferCtx->pDataObj = NULL;
1009 }
1010
1011 delete pWinURITransferCtx;
1012
1013 pTransfer->pvUser = NULL;
1014 pTransfer->cbUser = 0;
1015 }
1016}
1017
1018/**
1019 * Retrieves the roots for a transfer by opening the clipboard and getting the clipboard data
1020 * as string list (CF_HDROP), assigning it to the transfer as roots then.
1021 *
1022 * @returns VBox status code.
1023 * @param pWinCtx Windows context to use.
1024 * @param pTransfer Transfer to get roots for.
1025 */
1026int SharedClipboardWinGetRoots(PSHCLWINCTX pWinCtx, PSHCLTRANSFER pTransfer)
1027{
1028 AssertPtrReturn(pWinCtx, VERR_INVALID_POINTER);
1029 AssertPtrReturn(pTransfer, VERR_INVALID_POINTER);
1030
1031 Assert(ShClTransferGetSource(pTransfer) == SHCLSOURCE_LOCAL); /* Sanity. */
1032
1033 int rc = SharedClipboardWinOpen(pWinCtx->hWnd);
1034 if (RT_SUCCESS(rc))
1035 {
1036 /* The data data in CF_HDROP format, as the files are locally present and don't need to be
1037 * presented as a IDataObject or IStream. */
1038 HANDLE hClip = hClip = GetClipboardData(CF_HDROP);
1039 if (hClip)
1040 {
1041 HDROP hDrop = (HDROP)GlobalLock(hClip);
1042 if (hDrop)
1043 {
1044 char *papszList = NULL;
1045 uint32_t cbList;
1046 rc = SharedClipboardWinDropFilesToStringList((DROPFILES *)hDrop, &papszList, &cbList);
1047
1048 GlobalUnlock(hClip);
1049
1050 if (RT_SUCCESS(rc))
1051 {
1052 rc = ShClTransferRootsSet(pTransfer,
1053 papszList, cbList + 1 /* Include termination */);
1054 RTStrFree(papszList);
1055 }
1056 }
1057 else
1058 LogRel(("Shared Clipboard: Unable to lock clipboard data, last error: %ld\n", GetLastError()));
1059 }
1060 else
1061 LogRel(("Shared Clipboard: Unable to retrieve clipboard data from clipboard (CF_HDROP), last error: %ld\n",
1062 GetLastError()));
1063
1064 SharedClipboardWinClose();
1065 }
1066
1067 LogFlowFuncLeaveRC(rc);
1068 return rc;
1069}
1070
1071/**
1072 * Converts a DROPFILES (HDROP) structure to a string list, separated by \r\n.
1073 * Does not do any locking on the input data.
1074 *
1075 * @returns VBox status code.
1076 * @param pDropFiles Pointer to DROPFILES structure to convert.
1077 * @param papszList Where to store the allocated string list.
1078 * @param pcbList Where to store the size (in bytes) of the allocated string list.
1079 */
1080int SharedClipboardWinDropFilesToStringList(DROPFILES *pDropFiles, char **papszList, uint32_t *pcbList)
1081{
1082 AssertPtrReturn(pDropFiles, VERR_INVALID_POINTER);
1083 AssertPtrReturn(papszList, VERR_INVALID_POINTER);
1084 AssertPtrReturn(pcbList, VERR_INVALID_POINTER);
1085
1086 /* Do we need to do Unicode stuff? */
1087 const bool fUnicode = RT_BOOL(pDropFiles->fWide);
1088
1089 /* Get the offset of the file list. */
1090 Assert(pDropFiles->pFiles >= sizeof(DROPFILES));
1091
1092 /* Note: This is *not* pDropFiles->pFiles! DragQueryFile only
1093 * will work with the plain storage medium pointer! */
1094 HDROP hDrop = (HDROP)(pDropFiles);
1095
1096 int rc = VINF_SUCCESS;
1097
1098 /* First, get the file count. */
1099 /** @todo Does this work on Windows 2000 / NT4? */
1100 char *pszFiles = NULL;
1101 uint32_t cchFiles = 0;
1102 UINT cFiles = DragQueryFile(hDrop, UINT32_MAX /* iFile */, NULL /* lpszFile */, 0 /* cchFile */);
1103
1104 LogFlowFunc(("Got %RU16 file(s), fUnicode=%RTbool\n", cFiles, fUnicode));
1105
1106 for (UINT i = 0; i < cFiles; i++)
1107 {
1108 UINT cchFile = DragQueryFile(hDrop, i /* File index */, NULL /* Query size first */, 0 /* cchFile */);
1109 Assert(cchFile);
1110
1111 if (RT_FAILURE(rc))
1112 break;
1113
1114 char *pszFileUtf8 = NULL; /* UTF-8 version. */
1115 UINT cchFileUtf8 = 0;
1116 if (fUnicode)
1117 {
1118 /* Allocate enough space (including terminator). */
1119 WCHAR *pwszFile = (WCHAR *)RTMemAlloc((cchFile + 1) * sizeof(WCHAR));
1120 if (pwszFile)
1121 {
1122 const UINT cwcFileUtf16 = DragQueryFileW(hDrop, i /* File index */,
1123 pwszFile, cchFile + 1 /* Include terminator */);
1124
1125 AssertMsg(cwcFileUtf16 == cchFile, ("cchFileUtf16 (%RU16) does not match cchFile (%RU16)\n",
1126 cwcFileUtf16, cchFile));
1127 RT_NOREF(cwcFileUtf16);
1128
1129 rc = RTUtf16ToUtf8(pwszFile, &pszFileUtf8);
1130 if (RT_SUCCESS(rc))
1131 {
1132 cchFileUtf8 = (UINT)strlen(pszFileUtf8);
1133 Assert(cchFileUtf8);
1134 }
1135
1136 RTMemFree(pwszFile);
1137 }
1138 else
1139 rc = VERR_NO_MEMORY;
1140 }
1141 else /* ANSI */
1142 {
1143 /* Allocate enough space (including terminator). */
1144 char *pszFileANSI = (char *)RTMemAlloc((cchFile + 1) * sizeof(char));
1145 UINT cchFileANSI = 0;
1146 if (pszFileANSI)
1147 {
1148 cchFileANSI = DragQueryFileA(hDrop, i /* File index */,
1149 pszFileANSI, cchFile + 1 /* Include terminator */);
1150
1151 AssertMsg(cchFileANSI == cchFile, ("cchFileANSI (%RU16) does not match cchFile (%RU16)\n",
1152 cchFileANSI, cchFile));
1153
1154 /* Convert the ANSI codepage to UTF-8. */
1155 rc = RTStrCurrentCPToUtf8(&pszFileUtf8, pszFileANSI);
1156 if (RT_SUCCESS(rc))
1157 {
1158 cchFileUtf8 = (UINT)strlen(pszFileUtf8);
1159 }
1160 }
1161 else
1162 rc = VERR_NO_MEMORY;
1163 }
1164
1165 if (RT_SUCCESS(rc))
1166 {
1167 LogFlowFunc(("\tFile: %s (cchFile=%RU16)\n", pszFileUtf8, cchFileUtf8));
1168
1169 LogRel2(("Shared Clipboard: Adding file '%s' to transfer\n", pszFileUtf8));
1170
1171 rc = RTStrAAppendExN(&pszFiles, 1 /* cPairs */, pszFileUtf8, strlen(pszFileUtf8));
1172 cchFiles += (uint32_t)strlen(pszFileUtf8);
1173 }
1174
1175 if (pszFileUtf8)
1176 RTStrFree(pszFileUtf8);
1177
1178 if (RT_FAILURE(rc))
1179 {
1180 LogFunc(("Error handling file entry #%u, rc=%Rrc\n", i, rc));
1181 break;
1182 }
1183
1184 /* Add separation between filenames.
1185 * Note: Also do this for the last element of the list. */
1186 rc = RTStrAAppendExN(&pszFiles, 1 /* cPairs */, "\r\n", 2 /* Bytes */);
1187 if (RT_SUCCESS(rc))
1188 cchFiles += 2; /* Include \r\n */
1189 }
1190
1191 if (RT_SUCCESS(rc))
1192 {
1193 cchFiles += 1; /* Add string termination. */
1194 uint32_t cbFiles = cchFiles * sizeof(char); /* UTF-8. */
1195
1196 LogFlowFunc(("cFiles=%u, cchFiles=%RU32, cbFiles=%RU32, pszFiles=0x%p\n",
1197 cFiles, cchFiles, cbFiles, pszFiles));
1198
1199 *papszList = pszFiles;
1200 *pcbList = cbFiles;
1201 }
1202 else
1203 {
1204 if (pszFiles)
1205 RTStrFree(pszFiles);
1206 }
1207
1208 LogFlowFuncLeaveRC(rc);
1209 return rc;
1210}
1211#endif /* VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS */
1212
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