VirtualBox

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

Last change on this file since 85427 was 85121, checked in by vboxsync, 4 years ago

iprt/cdefs.h: Refactored the typedef use of DECLCALLBACK as well as DECLCALLBACKMEMBER to wrap the whole expression, similar to the DECLR?CALLBACKMEMBER macros. This allows adding a throw() at the end when compiling with the VC++ compiler to indicate that the callbacks won't throw anything, so we can stop supressing the C5039 warning about passing functions that can potential throw C++ exceptions to extern C code that can't necessarily cope with such (unwind,++). Introduced a few _EX variations that allows specifying different/no calling convention too, as that's handy when dynamically resolving host APIs. Fixed numerous places missing DECLCALLBACK and such. Left two angry @todos regarding use of CreateThread. bugref:9794

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