VirtualBox

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

Last change on this file since 98988 was 98103, checked in by vboxsync, 23 months ago

Copyright year updates by scm.

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