VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxClipboard.cpp@ 90714

Last change on this file since 90714 was 90054, checked in by vboxsync, 4 years ago

VBoxSharedClipboard/win: Replaced SharedClipboardWinAnnounceFormats with SharedClipboardWinClearAndAnnounceFormats that does all the necessary work. Documented hWndClipboardOwnerUs more accurately. bugref:9998

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.1 KB
Line 
1/* $Id: VBoxClipboard.cpp 90054 2021-07-06 10:55:23Z vboxsync $ */
2/** @file
3 * VBoxClipboard - Shared clipboard, Windows Guest Implementation.
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
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_SHARED_CLIPBOARD
23#include <VBox/log.h>
24
25#include "VBoxTray.h"
26#include "VBoxHelpers.h"
27
28#include <iprt/asm.h>
29#include <iprt/errcore.h>
30#include <iprt/mem.h>
31#include <iprt/ldr.h>
32
33
34#include <VBox/GuestHost/SharedClipboard.h>
35#include <VBox/GuestHost/SharedClipboard-win.h>
36#include <VBox/GuestHost/clipboard-helper.h>
37#include <VBox/HostServices/VBoxClipboardSvc.h> /* Temp, remove. */
38#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
39# include <VBox/GuestHost/SharedClipboard-transfers.h>
40#endif
41
42#include <strsafe.h>
43
44#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
45# include <iprt/win/shlobj.h>
46# include <iprt/win/shlwapi.h>
47#endif
48
49
50/*********************************************************************************************************************************
51* Structures and Typedefs *
52*********************************************************************************************************************************/
53struct SHCLCONTEXT
54{
55 /** Pointer to the VBoxClient service environment. */
56 const VBOXSERVICEENV *pEnv;
57 /** Command context. */
58 VBGLR3SHCLCMDCTX CmdCtx;
59 /** Windows-specific context data. */
60 SHCLWINCTX Win;
61 /** Thread handle for window thread. */
62 RTTHREAD hThread;
63 /** Start indicator flag. */
64 bool fStarted;
65 /** Shutdown indicator flag. */
66 bool fShutdown;
67#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
68 /** Associated transfer data. */
69 SHCLTRANSFERCTX TransferCtx;
70#endif
71};
72
73
74/*********************************************************************************************************************************
75* Static variables *
76*********************************************************************************************************************************/
77/** Static clipboard context (since it is the single instance). Directly used in the windows proc. */
78static SHCLCONTEXT g_Ctx = { NULL };
79/** Static window class name. */
80static char s_szClipWndClassName[] = SHCL_WIN_WNDCLASS_NAME;
81
82
83/*********************************************************************************************************************************
84* Prototypes *
85*********************************************************************************************************************************/
86#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
87static DECLCALLBACK(int) vboxClipboardOnTransferInitCallback(PSHCLTXPROVIDERCTX pCtx);
88static DECLCALLBACK(int) vboxClipboardOnTransferStartCallback(PSHCLTXPROVIDERCTX pCtx);
89static DECLCALLBACK(void) vboxClipboardOnTransferCompleteCallback(PSHCLTXPROVIDERCTX pCtx, int rc);
90static DECLCALLBACK(void) vboxClipboardOnTransferErrorCallback(PSHCLTXPROVIDERCTX pCtx, int rc);
91#endif
92
93
94#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
95
96/**
97 * Cleanup helper function for transfer callbacks.
98 *
99 * @param pTransferCtx Pointer to transfer context that the transfer contains.
100 * @param pTransfer Pointer to transfer to cleanup.
101 */
102static void vboxClipboardTransferCallbackCleanup(PSHCLTRANSFERCTX pTransferCtx, PSHCLTRANSFER pTransfer)
103{
104 LogFlowFuncEnter();
105
106 if (!pTransferCtx || !pTransfer)
107 return;
108
109 if (pTransfer->pvUser) /* SharedClipboardWinTransferCtx */
110 {
111 delete pTransfer->pvUser;
112 pTransfer->pvUser = NULL;
113 }
114
115 int rc2 = ShClTransferCtxTransferUnregister(pTransferCtx, pTransfer->State.uID);
116 AssertRC(rc2);
117
118 ShClTransferDestroy(pTransfer);
119
120 RTMemFree(pTransfer);
121 pTransfer = NULL;
122}
123
124/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnInitialize */
125static DECLCALLBACK(int) vboxClipboardOnTransferInitCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx)
126{
127 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
128 AssertPtr(pCtx);
129
130 LogFlowFunc(("pCtx=%p\n", pCtx));
131
132 RT_NOREF(pCtx);
133
134 return VINF_SUCCESS;
135}
136
137/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnStart */
138static DECLCALLBACK(int) vboxClipboardOnTransferStartCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx)
139{
140 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
141 AssertPtr(pCtx);
142
143 PSHCLTRANSFER pTransfer = pCbCtx->pTransfer;
144 AssertPtr(pTransfer);
145
146 const SHCLTRANSFERDIR enmDir = ShClTransferGetDir(pTransfer);
147
148 LogFlowFunc(("pCtx=%p, idTransfer=%RU32, enmDir=%RU32\n", pCtx, ShClTransferGetID(pTransfer), enmDir));
149
150 int rc;
151
152 /* The guest wants to write local data to the host? */
153 if (enmDir == SHCLTRANSFERDIR_TO_REMOTE)
154 {
155 rc = SharedClipboardWinGetRoots(&pCtx->Win, pTransfer);
156 }
157 /* The guest wants to read data from a remote source. */
158 else if (enmDir == SHCLTRANSFERDIR_FROM_REMOTE)
159 {
160 /* The IDataObject *must* be created on the same thread as our (proxy) window, so post a message to it
161 * to do the stuff for us. */
162 const SHCLEVENTID idEvent = ShClEventIdGenerateAndRegister(&pTransfer->Events);
163 if (idEvent != NIL_SHCLEVENTID)
164 {
165 /* Don't want to rely on SendMessage (synchronous) here, so just post and wait the event getting signalled. */
166 ::PostMessage(pCtx->Win.hWnd, SHCL_WIN_WM_TRANSFER_START, (WPARAM)pTransfer, (LPARAM)idEvent);
167
168 PSHCLEVENTPAYLOAD pPayload;
169 rc = ShClEventWait(&pTransfer->Events, idEvent, 30 * 1000 /* Timeout in ms */, &pPayload);
170 if (RT_SUCCESS(rc))
171 {
172 Assert(pPayload->cbData == sizeof(int));
173 rc = *(int *)pPayload->pvData;
174
175 ShClPayloadFree(pPayload);
176 }
177
178 ShClEventUnregister(&pTransfer->Events, idEvent);
179 }
180 else
181 AssertFailedStmt(rc = VERR_SHCLPB_MAX_EVENTS_REACHED);
182 }
183 else
184 AssertFailedStmt(rc = VERR_NOT_SUPPORTED);
185
186 if (RT_FAILURE(rc))
187 LogRel(("Shared Clipboard: Starting transfer failed, rc=%Rrc\n", rc));
188
189 LogFlowFunc(("LEAVE: idTransfer=%RU32, rc=%Rrc\n", ShClTransferGetID(pTransfer), rc));
190 return rc;
191}
192
193/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnCompleted */
194static DECLCALLBACK(void) vboxClipboardOnTransferCompletedCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx, int rcCompletion)
195{
196 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
197 AssertPtr(pCtx);
198
199 LogRel2(("Shared Clipboard: Transfer to destination %s\n",
200 rcCompletion == VERR_CANCELLED ? "canceled" : "complete"));
201
202 vboxClipboardTransferCallbackCleanup(&pCtx->TransferCtx, pCbCtx->pTransfer);
203}
204
205/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnError */
206static DECLCALLBACK(void) vboxClipboardOnTransferErrorCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx, int rcError)
207{
208 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
209 AssertPtr(pCtx);
210
211 LogRel(("Shared Clipboard: Transfer to destination failed with %Rrc\n", rcError));
212
213 vboxClipboardTransferCallbackCleanup(&pCtx->TransferCtx, pCbCtx->pTransfer);
214}
215
216#endif /* VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS */
217
218static LRESULT vboxClipboardWinProcessMsg(PSHCLCONTEXT pCtx, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
219{
220 AssertPtr(pCtx);
221
222 const PSHCLWINCTX pWinCtx = &pCtx->Win;
223
224 LRESULT lresultRc = 0;
225
226 switch (msg)
227 {
228 case WM_CLIPBOARDUPDATE:
229 {
230 LogFunc(("WM_CLIPBOARDUPDATE: pWinCtx=%p\n", pWinCtx));
231
232 if (pCtx->fShutdown) /* If we're about to shut down, skip handling stuff here. */
233 break;
234
235 int rc = RTCritSectEnter(&pWinCtx->CritSect);
236 if (RT_SUCCESS(rc))
237 {
238 const HWND hWndClipboardOwner = GetClipboardOwner();
239
240 LogFunc(("WM_CLIPBOARDUPDATE: hWndOldClipboardOwner=%p, hWndNewClipboardOwner=%p\n",
241 pWinCtx->hWndClipboardOwnerUs, hWndClipboardOwner));
242
243 if (pWinCtx->hWndClipboardOwnerUs != hWndClipboardOwner)
244 {
245 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
246 AssertRC(rc2);
247
248 /* Clipboard was updated by another application.
249 * Report available formats to the host. */
250 SHCLFORMATS fFormats;
251 rc = SharedClipboardWinGetFormats(pWinCtx, &fFormats);
252 if (RT_SUCCESS(rc))
253 {
254 LogFunc(("WM_CLIPBOARDUPDATE: Reporting formats %#x\n", fFormats));
255 rc = VbglR3ClipboardReportFormats(pCtx->CmdCtx.idClient, fFormats);
256 }
257 }
258 else
259 {
260 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
261 AssertRC(rc2);
262 }
263 }
264
265 if (RT_FAILURE(rc))
266 LogRel(("Shared Clipboard: WM_CLIPBOARDUPDATE failed with %Rrc\n", rc));
267
268 break;
269 }
270
271 case WM_CHANGECBCHAIN:
272 {
273 LogFunc(("WM_CHANGECBCHAIN\n"));
274 lresultRc = SharedClipboardWinHandleWMChangeCBChain(pWinCtx, hwnd, msg, wParam, lParam);
275 break;
276 }
277
278 case WM_DRAWCLIPBOARD:
279 {
280 LogFlowFunc(("WM_DRAWCLIPBOARD: pWinCtx=%p\n", pWinCtx));
281
282 int rc = RTCritSectEnter(&pWinCtx->CritSect);
283 if (RT_SUCCESS(rc))
284 {
285 const HWND hWndClipboardOwner = GetClipboardOwner();
286
287 LogFunc(("WM_DRAWCLIPBOARD: hWndClipboardOwnerUs=%p, hWndNewClipboardOwner=%p\n",
288 pWinCtx->hWndClipboardOwnerUs, hWndClipboardOwner));
289
290 if (pWinCtx->hWndClipboardOwnerUs != hWndClipboardOwner)
291 {
292 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
293 AssertRC(rc2);
294
295 /* Clipboard was updated by another application. */
296 /* WM_DRAWCLIPBOARD always expects a return code of 0, so don't change "rc" here. */
297 SHCLFORMATS fFormats;
298 rc = SharedClipboardWinGetFormats(pWinCtx, &fFormats);
299 if ( RT_SUCCESS(rc)
300 && fFormats != VBOX_SHCL_FMT_NONE)
301 rc = VbglR3ClipboardReportFormats(pCtx->CmdCtx.idClient, fFormats);
302 }
303 else
304 {
305 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
306 AssertRC(rc2);
307 }
308 }
309
310 lresultRc = SharedClipboardWinChainPassToNext(pWinCtx, msg, wParam, lParam);
311 break;
312 }
313
314 case WM_TIMER:
315 {
316 int rc = SharedClipboardWinHandleWMTimer(pWinCtx);
317 AssertRC(rc);
318
319 break;
320 }
321
322 case WM_CLOSE:
323 {
324 /* Do nothing. Ignore the message. */
325 break;
326 }
327
328 case WM_RENDERFORMAT:
329 {
330 LogFunc(("WM_RENDERFORMAT\n"));
331
332 /* Insert the requested clipboard format data into the clipboard. */
333 const UINT cfFormat = (UINT)wParam;
334
335 const SHCLFORMAT fFormat = SharedClipboardWinClipboardFormatToVBox(cfFormat);
336
337 LogFunc(("WM_RENDERFORMAT: cfFormat=%u -> fFormat=0x%x\n", cfFormat, fFormat));
338
339 if (fFormat == VBOX_SHCL_FMT_NONE)
340 {
341 LogFunc(("WM_RENDERFORMAT: Unsupported format requested\n"));
342 SharedClipboardWinClear();
343 }
344 else
345 {
346 const uint32_t cbPrealloc = _4K;
347 uint32_t cb = 0;
348
349 /* Preallocate a buffer, most of small text transfers will fit into it. */
350 HANDLE hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, cbPrealloc);
351 if (hMem)
352 {
353 void *pMem = GlobalLock(hMem);
354 if (pMem)
355 {
356 /* Read the host data to the preallocated buffer. */
357 int rc = VbglR3ClipboardReadDataEx(&pCtx->CmdCtx, fFormat, pMem, cbPrealloc, &cb);
358 if (RT_SUCCESS(rc))
359 {
360 if (cb == 0)
361 {
362 /* 0 bytes returned means the clipboard is empty.
363 * Deallocate the memory and set hMem to NULL to get to
364 * the clipboard empty code path. */
365 GlobalUnlock(hMem);
366 GlobalFree(hMem);
367 hMem = NULL;
368 }
369 else if (cb > cbPrealloc)
370 {
371 GlobalUnlock(hMem);
372
373 LogRel2(("Shared Clipboard: Buffer too small (%RU32), needs %RU32 bytes\n", cbPrealloc, cb));
374
375 /* The preallocated buffer is too small, adjust the size. */
376 hMem = GlobalReAlloc(hMem, cb, 0);
377 if (hMem)
378 {
379 pMem = GlobalLock(hMem);
380 if (pMem)
381 {
382 /* Read the host data to the preallocated buffer. */
383 uint32_t cbNew = 0;
384 rc = VbglR3ClipboardReadDataEx(&pCtx->CmdCtx, fFormat, pMem, cb, &cbNew);
385 if ( RT_SUCCESS(rc)
386 && cbNew <= cb)
387 {
388 cb = cbNew;
389 }
390 else
391 {
392 LogRel(("Shared Clipboard: Receiving host data failed with %Rrc\n", rc));
393
394 GlobalUnlock(hMem);
395 GlobalFree(hMem);
396 hMem = NULL;
397 }
398 }
399 else
400 {
401 LogRel(("Shared Clipboard: Error locking reallocated host data buffer\n"));
402
403 GlobalFree(hMem);
404 hMem = NULL;
405 }
406 }
407 else
408 LogRel(("Shared Clipboard: No memory for reallocating host data buffer\n"));
409 }
410
411 if (hMem)
412 {
413 /* pMem is the address of the data. cb is the size of returned data. */
414 /* Verify the size of returned text, the memory block for clipboard
415 * must have the exact string size.
416 */
417 if (fFormat == VBOX_SHCL_FMT_UNICODETEXT)
418 {
419 size_t cbActual = 0;
420 HRESULT hrc = StringCbLengthW((LPWSTR)pMem, cb, &cbActual);
421 if (FAILED(hrc))
422 {
423 LogRel(("Shared Clipboard: Received host data is invalid (%RU32 vs. %zu)\n",
424 cb, cbActual));
425
426 /* Discard invalid data. */
427 GlobalUnlock(hMem);
428 GlobalFree(hMem);
429 hMem = NULL;
430 }
431 else
432 {
433 /* cbActual is the number of bytes, excluding those used
434 * for the terminating null character.
435 */
436 cb = (uint32_t)(cbActual + 2);
437 }
438 }
439 }
440
441 if (hMem)
442 {
443 GlobalUnlock(hMem);
444
445 hMem = GlobalReAlloc(hMem, cb, 0);
446 if (hMem)
447 {
448 /* 'hMem' contains the host clipboard data.
449 * size is 'cb' and format is 'format'. */
450 HANDLE hClip = SetClipboardData(cfFormat, hMem);
451 if (hClip)
452 {
453 /* The hMem ownership has gone to the system. Finish the processing. */
454 break;
455 }
456 else
457 LogRel(("Shared Clipboard: Setting host data buffer to clipboard failed with %ld\n",
458 GetLastError()));
459
460 /* Cleanup follows. */
461 }
462 else
463 LogRel(("Shared Clipboard: No memory for allocating final host data buffer\n"));
464 }
465 }
466
467 if (hMem)
468 GlobalUnlock(hMem);
469 }
470 else
471 LogRel(("Shared Clipboard: No memory for allocating host data buffer\n"));
472
473 if (hMem)
474 GlobalFree(hMem);
475 }
476 }
477
478 break;
479 }
480
481 case WM_RENDERALLFORMATS:
482 {
483 LogFunc(("WM_RENDERALLFORMATS\n"));
484
485 int rc = SharedClipboardWinHandleWMRenderAllFormats(pWinCtx, hwnd);
486 AssertRC(rc);
487
488 break;
489 }
490
491 case SHCL_WIN_WM_REPORT_FORMATS:
492 {
493 LogFunc(("SHCL_WIN_WM_REPORT_FORMATS\n"));
494
495 /* Announce available formats. Do not insert data -- will be inserted in WM_RENDERFORMAT. */
496 PVBGLR3CLIPBOARDEVENT pEvent = (PVBGLR3CLIPBOARDEVENT)lParam;
497 AssertPtr(pEvent);
498 Assert(pEvent->enmType == VBGLR3CLIPBOARDEVENTTYPE_REPORT_FORMATS);
499
500 const SHCLFORMATS fFormats = pEvent->u.fReportedFormats;
501
502 if (fFormats != VBOX_SHCL_FMT_NONE) /* Could arrive with some older GA versions. */
503 {
504#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
505 if (fFormats & VBOX_SHCL_FMT_URI_LIST)
506 {
507 LogFunc(("VBOX_SHCL_FMT_URI_LIST\n"));
508
509 /*
510 * Creating and starting the actual transfer will be done in vbglR3ClipboardTransferStart() as soon
511 * as the host announces the start of the transfer via a VBOX_SHCL_HOST_MSG_TRANSFER_STATUS message.
512 * Transfers always are controlled and initiated on the host side!
513 *
514 * So don't announce the transfer to the OS here yet. Don't touch the clipboard in any here; otherwise
515 * this will trigger a WM_DRAWCLIPBOARD or friends, which will result in fun bugs coming up.
516 */
517 }
518 else
519 {
520#endif
521 SharedClipboardWinClearAndAnnounceFormats(pWinCtx, fFormats, hwnd);
522#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
523 }
524#endif
525 }
526
527 LogFunc(("SHCL_WIN_WM_REPORT_FORMATS: fFormats=0x%x, lastErr=%ld\n", fFormats, GetLastError()));
528 break;
529 }
530
531 case SHCL_WIN_WM_READ_DATA:
532 {
533 /* Send data in the specified format to the host. */
534 PVBGLR3CLIPBOARDEVENT pEvent = (PVBGLR3CLIPBOARDEVENT)lParam;
535 AssertPtr(pEvent);
536 Assert(pEvent->enmType == VBGLR3CLIPBOARDEVENTTYPE_READ_DATA);
537
538 const SHCLFORMAT fFormat = (uint32_t)pEvent->u.fReadData;
539
540 HANDLE hClip = NULL;
541
542 LogFlowFunc(("SHCL_WIN_WM_READ_DATA: fFormat=%#x\n", fFormat));
543
544 int rc = SharedClipboardWinOpen(hwnd);
545 if (RT_SUCCESS(rc))
546 {
547 if (fFormat & VBOX_SHCL_FMT_BITMAP)
548 {
549 hClip = GetClipboardData(CF_DIB);
550 if (hClip != NULL)
551 {
552 LPVOID lp = GlobalLock(hClip);
553 if (lp != NULL)
554 {
555 rc = VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx, fFormat, lp, (uint32_t)GlobalSize(hClip));
556
557 GlobalUnlock(hClip);
558 }
559 else
560 {
561 hClip = NULL;
562 }
563 }
564 }
565 else if (fFormat & VBOX_SHCL_FMT_UNICODETEXT)
566 {
567 hClip = GetClipboardData(CF_UNICODETEXT);
568 if (hClip != NULL)
569 {
570 LPWSTR uniString = (LPWSTR)GlobalLock(hClip);
571 if (uniString != NULL)
572 {
573 rc = VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx,
574 fFormat, uniString, ((uint32_t)lstrlenW(uniString) + 1) * 2);
575
576 GlobalUnlock(hClip);
577 }
578 else
579 {
580 hClip = NULL;
581 }
582 }
583 }
584 else if (fFormat & VBOX_SHCL_FMT_HTML)
585 {
586 UINT format = RegisterClipboardFormat(SHCL_WIN_REGFMT_HTML);
587 if (format != 0)
588 {
589 hClip = GetClipboardData(format);
590 if (hClip != NULL)
591 {
592 LPVOID lp = GlobalLock(hClip);
593 if (lp != NULL)
594 {
595 rc = VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx, fFormat, lp, (uint32_t)GlobalSize(hClip));
596
597 GlobalUnlock(hClip);
598 }
599 else
600 {
601 hClip = NULL;
602 }
603 }
604 }
605 }
606 if (hClip == NULL)
607 {
608 LogFunc(("SHCL_WIN_WM_READ_DATA: hClip=NULL, lastError=%ld\n", GetLastError()));
609
610 /* Requested clipboard format is not available, send empty data. */
611 VbglR3ClipboardWriteData(pCtx->CmdCtx.idClient, VBOX_SHCL_FMT_NONE, NULL, 0);
612 }
613
614 SharedClipboardWinClose();
615 }
616 break;
617 }
618
619#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
620 case SHCL_WIN_WM_TRANSFER_START:
621 {
622 LogFunc(("SHCL_WIN_WM_TRANSFER_START\n"));
623
624 PSHCLTRANSFER pTransfer = (PSHCLTRANSFER)wParam;
625 AssertPtr(pTransfer);
626
627 const SHCLEVENTID idEvent = (SHCLEVENTID)lParam;
628
629 Assert(ShClTransferGetSource(pTransfer) == SHCLSOURCE_REMOTE); /* Sanity. */
630
631 int rcTransfer = SharedClipboardWinTransferCreate(pWinCtx, pTransfer);
632
633 PSHCLEVENTPAYLOAD pPayload = NULL;
634 int rc = ShClPayloadAlloc(idEvent, &rcTransfer, sizeof(rcTransfer), &pPayload);
635 if (RT_SUCCESS(rc))
636 {
637 rc = ShClEventSignal(&pTransfer->Events, idEvent, pPayload);
638 if (RT_FAILURE(rc))
639 ShClPayloadFree(pPayload);
640 }
641
642 break;
643 }
644#endif
645 case WM_DESTROY:
646 {
647 LogFunc(("WM_DESTROY\n"));
648
649 int rc = SharedClipboardWinHandleWMDestroy(pWinCtx);
650 AssertRC(rc);
651
652 /*
653 * Don't need to call PostQuitMessage cause
654 * the VBoxTray already finished a message loop.
655 */
656
657 break;
658 }
659
660 default:
661 {
662 LogFunc(("WM_ %p\n", msg));
663 lresultRc = DefWindowProc(hwnd, msg, wParam, lParam);
664 break;
665 }
666 }
667
668 LogFunc(("WM_ rc %d\n", lresultRc));
669 return lresultRc;
670}
671
672static LRESULT CALLBACK vboxClipboardWinWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
673
674static int vboxClipboardCreateWindow(PSHCLCONTEXT pCtx)
675{
676 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
677
678 int rc = VINF_SUCCESS;
679
680 AssertPtr(pCtx->pEnv);
681 HINSTANCE hInstance = pCtx->pEnv->hInstance;
682 Assert(hInstance != 0);
683
684 /* Register the Window Class. */
685 WNDCLASSEX wc;
686 RT_ZERO(wc);
687
688 wc.cbSize = sizeof(WNDCLASSEX);
689
690 if (!GetClassInfoEx(hInstance, s_szClipWndClassName, &wc))
691 {
692 wc.style = CS_NOCLOSE;
693 wc.lpfnWndProc = vboxClipboardWinWndProc;
694 wc.hInstance = pCtx->pEnv->hInstance;
695 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
696 wc.lpszClassName = s_szClipWndClassName;
697
698 ATOM wndClass = RegisterClassEx(&wc);
699 if (wndClass == 0)
700 rc = RTErrConvertFromWin32(GetLastError());
701 }
702
703 if (RT_SUCCESS(rc))
704 {
705 const PSHCLWINCTX pWinCtx = &pCtx->Win;
706
707 /* Create the window. */
708 pWinCtx->hWnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
709 s_szClipWndClassName, s_szClipWndClassName,
710 WS_POPUPWINDOW,
711 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
712 if (pWinCtx->hWnd == NULL)
713 {
714 rc = VERR_NOT_SUPPORTED;
715 }
716 else
717 {
718 SetWindowPos(pWinCtx->hWnd, HWND_TOPMOST, -200, -200, 0, 0,
719 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
720
721 rc = SharedClipboardWinChainAdd(pWinCtx);
722 if (RT_SUCCESS(rc))
723 {
724 if (!SharedClipboardWinIsNewAPI(&pWinCtx->newAPI))
725 pWinCtx->oldAPI.timerRefresh = SetTimer(pWinCtx->hWnd, 0, 10 * 1000 /* 10s */, NULL);
726 }
727 }
728 }
729
730 LogFlowFuncLeaveRC(rc);
731 return rc;
732}
733
734static DECLCALLBACK(int) vboxClipboardWindowThread(RTTHREAD hThread, void *pvUser)
735{
736 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pvUser;
737 AssertPtr(pCtx);
738
739#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
740 HRESULT hr = OleInitialize(NULL);
741 if (FAILED(hr))
742 {
743 LogRel(("Shared Clipboard: Initializing OLE in window thread failed (%Rhrc) -- file transfers unavailable\n", hr));
744 /* Not critical, the rest of the clipboard might work. */
745 }
746 else
747 LogRel(("Shared Clipboard: Initialized OLE in window thread\n"));
748#endif
749
750 int rc = vboxClipboardCreateWindow(pCtx);
751 if (RT_FAILURE(rc))
752 {
753 LogRel(("Shared Clipboard: Unable to create window, rc=%Rrc\n", rc));
754 return rc;
755 }
756
757 pCtx->fStarted = true; /* Set started indicator. */
758
759 int rc2 = RTThreadUserSignal(hThread);
760 bool fSignalled = RT_SUCCESS(rc2);
761
762 LogRel2(("Shared Clipboard: Window thread running\n"));
763
764 if (RT_SUCCESS(rc))
765 {
766 for (;;)
767 {
768 MSG uMsg;
769 BOOL fRet;
770 while ((fRet = GetMessage(&uMsg, 0, 0, 0)) > 0)
771 {
772 TranslateMessage(&uMsg);
773 DispatchMessage(&uMsg);
774 }
775 Assert(fRet >= 0);
776
777 if (ASMAtomicReadBool(&pCtx->fShutdown))
778 break;
779
780 /** @todo Immediately drop on failure? */
781 }
782 }
783
784 if (!fSignalled)
785 {
786 rc2 = RTThreadUserSignal(hThread);
787 AssertRC(rc2);
788 }
789
790#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
791 OleSetClipboard(NULL); /* Make sure to flush the clipboard on destruction. */
792 OleUninitialize();
793#endif
794
795 LogRel(("Shared Clipboard: Window thread ended\n"));
796
797 LogFlowFuncLeaveRC(rc);
798 return rc;
799}
800
801static void vboxClipboardDestroy(PSHCLCONTEXT pCtx)
802{
803 AssertPtrReturnVoid(pCtx);
804
805 LogFlowFunc(("pCtx=%p\n", pCtx));
806
807 LogRel2(("Shared Clipboard: Destroying ...\n"));
808
809 const PSHCLWINCTX pWinCtx = &pCtx->Win;
810
811 if (pCtx->hThread != NIL_RTTHREAD)
812 {
813 int rcThread = VERR_WRONG_ORDER;
814 int rc = RTThreadWait(pCtx->hThread, 60 * 1000 /* Timeout in ms */, &rcThread);
815 LogFlowFunc(("Waiting for thread resulted in %Rrc (thread exited with %Rrc)\n",
816 rc, rcThread));
817 RT_NOREF(rc);
818 }
819
820 if (pWinCtx->hWnd)
821 {
822 DestroyWindow(pWinCtx->hWnd);
823 pWinCtx->hWnd = NULL;
824 }
825
826 UnregisterClass(s_szClipWndClassName, pCtx->pEnv->hInstance);
827
828 SharedClipboardWinCtxDestroy(&pCtx->Win);
829
830 LogRel2(("Shared Clipboard: Destroyed\n"));
831}
832
833static LRESULT CALLBACK vboxClipboardWinWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
834{
835 PSHCLCONTEXT pCtx = &g_Ctx; /** @todo r=andy Make pCtx available through SetWindowLongPtr() / GWL_USERDATA. */
836 AssertPtr(pCtx);
837
838 /* Forward with proper context. */
839 return vboxClipboardWinProcessMsg(pCtx, hWnd, uMsg, wParam, lParam);
840}
841
842DECLCALLBACK(int) VBoxShClInit(const PVBOXSERVICEENV pEnv, void **ppInstance)
843{
844 LogFlowFuncEnter();
845
846 PSHCLCONTEXT pCtx = &g_Ctx; /* Only one instance for now. */
847 AssertPtr(pCtx);
848
849 if (pCtx->pEnv)
850 {
851 /* Clipboard was already initialized. 2 or more instances are not supported. */
852 return VERR_NOT_SUPPORTED;
853 }
854
855 if (VbglR3AutoLogonIsRemoteSession())
856 {
857 /* Do not use clipboard for remote sessions. */
858 LogRel(("Shared Clipboard: Clipboard has been disabled for a remote session\n"));
859 return VERR_NOT_SUPPORTED;
860 }
861
862 pCtx->pEnv = pEnv;
863 pCtx->hThread = NIL_RTTHREAD;
864 pCtx->fStarted = false;
865 pCtx->fShutdown = false;
866
867 int rc = VINF_SUCCESS;
868
869#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
870 /*
871 * Set callbacks.
872 * Those will be registered within VbglR3 when a new transfer gets initialized.
873 */
874 RT_ZERO(pCtx->CmdCtx.Transfers.Callbacks);
875
876 pCtx->CmdCtx.Transfers.Callbacks.pvUser = pCtx; /* Assign context as user-provided callback data. */
877 pCtx->CmdCtx.Transfers.Callbacks.cbUser = sizeof(SHCLCONTEXT);
878
879 pCtx->CmdCtx.Transfers.Callbacks.pfnOnInitialize = vboxClipboardOnTransferInitCallback;
880 pCtx->CmdCtx.Transfers.Callbacks.pfnOnStart = vboxClipboardOnTransferStartCallback;
881 pCtx->CmdCtx.Transfers.Callbacks.pfnOnCompleted = vboxClipboardOnTransferCompletedCallback;
882 pCtx->CmdCtx.Transfers.Callbacks.pfnOnError = vboxClipboardOnTransferErrorCallback;
883#endif
884
885 if (RT_SUCCESS(rc))
886 {
887 rc = SharedClipboardWinCtxInit(&pCtx->Win);
888 if (RT_SUCCESS(rc))
889 rc = VbglR3ClipboardConnectEx(&pCtx->CmdCtx, VBOX_SHCL_GF_0_CONTEXT_ID);
890 if (RT_SUCCESS(rc))
891 {
892#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
893 rc = ShClTransferCtxInit(&pCtx->TransferCtx);
894#endif
895 if (RT_SUCCESS(rc))
896 {
897 /* Message pump thread for our proxy window. */
898 rc = RTThreadCreate(&pCtx->hThread, vboxClipboardWindowThread, pCtx /* pvUser */,
899 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE,
900 "shclwnd");
901 if (RT_SUCCESS(rc))
902 {
903 int rc2 = RTThreadUserWait(pCtx->hThread, 30 * 1000 /* Timeout in ms */);
904 AssertRC(rc2);
905
906 if (!pCtx->fStarted) /* Did the thread fail to start? */
907 rc = VERR_NOT_SUPPORTED; /* Report back Shared Clipboard as not being supported. */
908 }
909 }
910
911 if (RT_SUCCESS(rc))
912 {
913 *ppInstance = pCtx;
914 }
915 else
916 VbglR3ClipboardDisconnectEx(&pCtx->CmdCtx);
917 }
918 }
919
920 if (RT_FAILURE(rc))
921 LogRel(("Shared Clipboard: Unable to initialize, rc=%Rrc\n", rc));
922
923 LogFlowFuncLeaveRC(rc);
924 return rc;
925}
926
927DECLCALLBACK(int) VBoxShClWorker(void *pInstance, bool volatile *pfShutdown)
928{
929 AssertPtr(pInstance);
930 LogFlowFunc(("pInstance=%p\n", pInstance));
931
932 /*
933 * Tell the control thread that it can continue
934 * spawning services.
935 */
936 RTThreadUserSignal(RTThreadSelf());
937
938 const PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pInstance;
939 AssertPtr(pCtx);
940
941 const PSHCLWINCTX pWinCtx = &pCtx->Win;
942
943 LogRel2(("Shared Clipboard: Worker loop running\n"));
944
945#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
946 HRESULT hr = OleInitialize(NULL);
947 if (FAILED(hr))
948 {
949 LogRel(("Shared Clipboard: Initializing OLE in worker thread failed (%Rhrc) -- file transfers unavailable\n", hr));
950 /* Not critical, the rest of the clipboard might work. */
951 }
952 else
953 LogRel(("Shared Clipboard: Initialized OLE in worker thraed\n"));
954#endif
955
956 int rc;
957
958 /* The thread waits for incoming messages from the host. */
959 for (;;)
960 {
961 LogFlowFunc(("Waiting for host message (fUseLegacyProtocol=%RTbool, fHostFeatures=%#RX64) ...\n",
962 pCtx->CmdCtx.fUseLegacyProtocol, pCtx->CmdCtx.fHostFeatures));
963
964 PVBGLR3CLIPBOARDEVENT pEvent = (PVBGLR3CLIPBOARDEVENT)RTMemAllocZ(sizeof(VBGLR3CLIPBOARDEVENT));
965 AssertPtrBreakStmt(pEvent, rc = VERR_NO_MEMORY);
966
967 uint32_t idMsg = 0;
968 uint32_t cParms = 0;
969 rc = VbglR3ClipboardMsgPeekWait(&pCtx->CmdCtx, &idMsg, &cParms, NULL /* pidRestoreCheck */);
970 if (RT_SUCCESS(rc))
971 {
972#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
973 rc = VbglR3ClipboardEventGetNextEx(idMsg, cParms, &pCtx->CmdCtx, &pCtx->TransferCtx, pEvent);
974#else
975 rc = VbglR3ClipboardEventGetNext(idMsg, cParms, &pCtx->CmdCtx, pEvent);
976#endif
977 }
978
979 if (RT_FAILURE(rc))
980 {
981 LogFlowFunc(("Getting next event failed with %Rrc\n", rc));
982
983 VbglR3ClipboardEventFree(pEvent);
984 pEvent = NULL;
985
986 if (*pfShutdown)
987 break;
988
989 /* Wait a bit before retrying. */
990 RTThreadSleep(1000);
991 continue;
992 }
993 else
994 {
995 AssertPtr(pEvent);
996 LogFlowFunc(("Event uType=%RU32\n", pEvent->enmType));
997
998 switch (pEvent->enmType)
999 {
1000 case VBGLR3CLIPBOARDEVENTTYPE_REPORT_FORMATS:
1001 {
1002 /* The host has announced available clipboard formats.
1003 * Forward the information to the window, so it can later
1004 * respond to WM_RENDERFORMAT message. */
1005 ::PostMessage(pWinCtx->hWnd, SHCL_WIN_WM_REPORT_FORMATS,
1006 0 /* wParam */, (LPARAM)pEvent /* lParam */);
1007
1008 pEvent = NULL; /* Consume pointer. */
1009 break;
1010 }
1011
1012 case VBGLR3CLIPBOARDEVENTTYPE_READ_DATA:
1013 {
1014 /* The host needs data in the specified format. */
1015 ::PostMessage(pWinCtx->hWnd, SHCL_WIN_WM_READ_DATA,
1016 0 /* wParam */, (LPARAM)pEvent /* lParam */);
1017
1018 pEvent = NULL; /* Consume pointer. */
1019 break;
1020 }
1021
1022 case VBGLR3CLIPBOARDEVENTTYPE_QUIT:
1023 {
1024 LogRel2(("Shared Clipboard: Host requested termination\n"));
1025 ASMAtomicXchgBool(pfShutdown, true);
1026 break;
1027 }
1028
1029#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1030 case VBGLR3CLIPBOARDEVENTTYPE_TRANSFER_STATUS:
1031 {
1032 /* Nothing to do here. */
1033 rc = VINF_SUCCESS;
1034 break;
1035 }
1036#endif
1037 case VBGLR3CLIPBOARDEVENTTYPE_NONE:
1038 {
1039 /* Nothing to do here. */
1040 rc = VINF_SUCCESS;
1041 break;
1042 }
1043
1044 default:
1045 {
1046 AssertMsgFailedBreakStmt(("Event type %RU32 not implemented\n", pEvent->enmType), rc = VERR_NOT_SUPPORTED);
1047 }
1048 }
1049
1050 if (pEvent)
1051 {
1052 VbglR3ClipboardEventFree(pEvent);
1053 pEvent = NULL;
1054 }
1055 }
1056
1057 if (*pfShutdown)
1058 break;
1059 }
1060
1061 LogRel2(("Shared Clipboard: Worker loop ended\n"));
1062
1063#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1064 OleSetClipboard(NULL); /* Make sure to flush the clipboard on destruction. */
1065 OleUninitialize();
1066#endif
1067
1068 LogFlowFuncLeaveRC(rc);
1069 return rc;
1070}
1071
1072DECLCALLBACK(int) VBoxShClStop(void *pInstance)
1073{
1074 AssertPtrReturn(pInstance, VERR_INVALID_POINTER);
1075
1076 LogFunc(("Stopping pInstance=%p\n", pInstance));
1077
1078 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pInstance;
1079 AssertPtr(pCtx);
1080
1081 /* Set shutdown indicator. */
1082 ASMAtomicWriteBool(&pCtx->fShutdown, true);
1083
1084 /* Let our clipboard know that we're going to shut down. */
1085 PostMessage(pCtx->Win.hWnd, WM_QUIT, 0, 0);
1086
1087 /* Disconnect from the host service.
1088 * This will also send a VBOX_SHCL_HOST_MSG_QUIT from the host so that we can break out from our message worker. */
1089 VbglR3ClipboardDisconnect(pCtx->CmdCtx.idClient);
1090 pCtx->CmdCtx.idClient = 0;
1091
1092 LogFlowFuncLeaveRC(VINF_SUCCESS);
1093 return VINF_SUCCESS;
1094}
1095
1096DECLCALLBACK(void) VBoxShClDestroy(void *pInstance)
1097{
1098 AssertPtrReturnVoid(pInstance);
1099
1100 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pInstance;
1101 AssertPtr(pCtx);
1102
1103 /* Make sure that we are disconnected. */
1104 Assert(pCtx->CmdCtx.idClient == 0);
1105
1106 vboxClipboardDestroy(pCtx);
1107
1108#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1109 ShClTransferCtxDestroy(&pCtx->TransferCtx);
1110#endif
1111
1112 return;
1113}
1114
1115/**
1116 * The service description.
1117 */
1118VBOXSERVICEDESC g_SvcDescClipboard =
1119{
1120 /* pszName. */
1121 "clipboard",
1122 /* pszDescription. */
1123 "Shared Clipboard",
1124 /* methods */
1125 VBoxShClInit,
1126 VBoxShClWorker,
1127 VBoxShClStop,
1128 VBoxShClDestroy
1129};
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