VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDnD.cpp@ 76103

Last change on this file since 76103 was 76103, checked in by vboxsync, 6 years ago

DnD/VBoxTray: Don't try to (debug) log event type in VBoxDnDWorker() if event retrieval fails (will be NULL).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 58.0 KB
Line 
1/* $Id: VBoxDnD.cpp 76103 2018-12-10 11:01:56Z vboxsync $ */
2/** @file
3 * VBoxDnD.cpp - Windows-specific bits of the drag and drop service.
4 */
5
6/*
7 * Copyright (C) 2013-2018 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_GUEST_DND
23#include <iprt/win/windows.h>
24#include "VBoxTray.h"
25#include "VBoxHelpers.h"
26#include "VBoxDnD.h"
27
28#include <VBox/VBoxGuestLib.h>
29#include "VBox/HostServices/DragAndDropSvc.h"
30
31using namespace DragAndDropSvc;
32
33#include <iprt/asm.h>
34#include <iprt/assert.h>
35#include <iprt/err.h>
36#include <iprt/ldr.h>
37#include <iprt/list.h>
38#include <iprt/mem.h>
39
40#include <iprt/cpp/mtlist.h>
41#include <iprt/cpp/ministring.h>
42
43#include <iprt/cpp/mtlist.h>
44
45#include <VBox/log.h>
46
47
48/*********************************************************************************************************************************
49* Defined Constants And Macros *
50*********************************************************************************************************************************/
51/* Enable this define to see the proxy window(s) when debugging
52 * their behavior. Don't have this enabled in release builds! */
53#ifdef DEBUG
54//# define VBOX_DND_DEBUG_WND
55#endif
56
57/** The drag and drop window's window class. */
58#define VBOX_DND_WND_CLASS "VBoxTrayDnDWnd"
59
60/** @todo Merge this with messages from VBoxTray.h. */
61#define WM_VBOXTRAY_DND_MESSAGE WM_APP + 401
62
63
64/*********************************************************************************************************************************
65* Structures and Typedefs *
66*********************************************************************************************************************************/
67/** Function pointer for SendInput(). This only is available starting
68 * at NT4 SP3+. */
69typedef BOOL (WINAPI *PFNSENDINPUT)(UINT, LPINPUT, int);
70typedef BOOL (WINAPI* PFNENUMDISPLAYMONITORS)(HDC, LPCRECT, MONITORENUMPROC, LPARAM);
71
72
73/*********************************************************************************************************************************
74* Global Variables *
75*********************************************************************************************************************************/
76/** Static pointer to SendInput() function. */
77static PFNSENDINPUT g_pfnSendInput = NULL;
78static PFNENUMDISPLAYMONITORS g_pfnEnumDisplayMonitors = NULL;
79
80static VBOXDNDCONTEXT g_Ctx = { 0 };
81
82
83/*********************************************************************************************************************************
84* Internal Functions *
85*********************************************************************************************************************************/
86static LRESULT CALLBACK vboxDnDWndProcInstance(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
87static LRESULT CALLBACK vboxDnDWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
88
89
90
91
92VBoxDnDWnd::VBoxDnDWnd(void)
93 : hThread(NIL_RTTHREAD),
94 mEventSem(NIL_RTSEMEVENT),
95 hWnd(NULL),
96 dndLstActionsAllowed(VBOX_DND_ACTION_IGNORE),
97 mfMouseButtonDown(false),
98#ifdef VBOX_WITH_DRAG_AND_DROP_GH
99 pDropTarget(NULL),
100#endif
101 mMode(Unknown),
102 mState(Uninitialized)
103{
104 RT_ZERO(startupInfo);
105
106 LogFlowFunc(("Supported formats:\n"));
107 const RTCString arrEntries[] = { VBOX_DND_FORMATS_DEFAULT };
108 for (size_t i = 0; i < RT_ELEMENTS(arrEntries); i++)
109 {
110 LogFlowFunc(("\t%s\n", arrEntries[i].c_str()));
111 this->lstFmtSup.append(arrEntries[i]);
112 }
113}
114
115VBoxDnDWnd::~VBoxDnDWnd(void)
116{
117 Destroy();
118}
119
120/**
121 * Initializes the proxy window with a given DnD context.
122 *
123 * @return IPRT status code.
124 * @param pCtx Pointer to context to use.
125 */
126int VBoxDnDWnd::Initialize(PVBOXDNDCONTEXT pCtx)
127{
128 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
129
130 /* Save the context. */
131 this->pCtx = pCtx;
132
133 int rc = RTSemEventCreate(&mEventSem);
134 if (RT_SUCCESS(rc))
135 rc = RTCritSectInit(&mCritSect);
136
137 if (RT_SUCCESS(rc))
138 {
139 /* Message pump thread for our proxy window. */
140 rc = RTThreadCreate(&hThread, VBoxDnDWnd::Thread, this,
141 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE,
142 "dndwnd"); /** @todo Include ID if there's more than one proxy window. */
143 if (RT_SUCCESS(rc))
144 {
145 int rc2 = RTThreadUserWait(hThread, 30 * 1000 /* Timeout in ms */);
146 AssertRC(rc2);
147
148 if (!pCtx->fStarted) /* Did the thread fail to start? */
149 rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
150 }
151 }
152
153 if (RT_FAILURE(rc))
154 LogRel(("DnD: Failed to initialize proxy window, rc=%Rrc\n", rc));
155
156 LogFlowThisFunc(("Returning rc=%Rrc\n", rc));
157 return rc;
158}
159
160/**
161 * Destroys the proxy window and releases all remaining
162 * resources again.
163 */
164void VBoxDnDWnd::Destroy(void)
165{
166 if (hThread != NIL_RTTHREAD)
167 {
168 int rcThread = VERR_WRONG_ORDER;
169 int rc = RTThreadWait(hThread, 60 * 1000 /* Timeout in ms */, &rcThread);
170 LogFlowFunc(("Waiting for thread resulted in %Rrc (thread exited with %Rrc)\n",
171 rc, rcThread));
172 NOREF(rc);
173 }
174
175 Reset();
176
177 RTCritSectDelete(&mCritSect);
178 if (mEventSem != NIL_RTSEMEVENT)
179 {
180 RTSemEventDestroy(mEventSem);
181 mEventSem = NIL_RTSEMEVENT;
182 }
183
184 if (pCtx->wndClass != 0)
185 {
186 UnregisterClass(VBOX_DND_WND_CLASS, pCtx->pEnv->hInstance);
187 pCtx->wndClass = 0;
188 }
189
190 LogFlowFuncLeave();
191}
192
193/**
194 * Thread for handling the window's message pump.
195 *
196 * @return IPRT status code.
197 * @param hThread Handle to this thread.
198 * @param pvUser Pointer to VBoxDnDWnd instance which
199 * is using the thread.
200 */
201/* static */
202int VBoxDnDWnd::Thread(RTTHREAD hThread, void *pvUser)
203{
204 AssertPtrReturn(pvUser, VERR_INVALID_POINTER);
205
206 LogFlowFuncEnter();
207
208 VBoxDnDWnd *pThis = (VBoxDnDWnd*)pvUser;
209 AssertPtr(pThis);
210
211 PVBOXDNDCONTEXT pCtx = pThis->pCtx;
212 AssertPtr(pCtx);
213 AssertPtr(pCtx->pEnv);
214
215 int rc = VINF_SUCCESS;
216
217 AssertPtr(pCtx->pEnv);
218 HINSTANCE hInstance = pCtx->pEnv->hInstance;
219 Assert(hInstance != 0);
220
221 /* Create our proxy window. */
222 WNDCLASSEX wc = { 0 };
223 wc.cbSize = sizeof(WNDCLASSEX);
224
225 if (!GetClassInfoEx(hInstance, VBOX_DND_WND_CLASS, &wc))
226 {
227 wc.lpfnWndProc = vboxDnDWndProc;
228 wc.lpszClassName = VBOX_DND_WND_CLASS;
229 wc.hInstance = hInstance;
230 wc.style = CS_NOCLOSE;
231#ifdef VBOX_DND_DEBUG_WND
232 wc.style |= CS_HREDRAW | CS_VREDRAW;
233 wc.hbrBackground = (HBRUSH)(CreateSolidBrush(RGB(255, 0, 0)));
234#else
235 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
236#endif
237 if (!RegisterClassEx(&wc))
238 {
239 DWORD dwErr = GetLastError();
240 LogFlowFunc(("Unable to register proxy window class, error=%ld\n", dwErr));
241 rc = RTErrConvertFromWin32(dwErr);
242 }
243 }
244
245 if (RT_SUCCESS(rc))
246 {
247 DWORD dwExStyle = WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE;
248 DWORD dwStyle = WS_POPUP;
249#ifdef VBOX_DND_DEBUG_WND
250 dwExStyle &= ~WS_EX_TRANSPARENT; /* Remove transparency bit. */
251 dwStyle |= WS_VISIBLE; /* Make the window visible. */
252#endif
253 pThis->hWnd =
254 CreateWindowEx(dwExStyle,
255 VBOX_DND_WND_CLASS, VBOX_DND_WND_CLASS,
256 dwStyle,
257#ifdef VBOX_DND_DEBUG_WND
258 CW_USEDEFAULT, CW_USEDEFAULT, 200, 200, NULL, NULL,
259#else
260 -200, -200, 100, 100, NULL, NULL,
261#endif
262 hInstance, pThis /* lParm */);
263 if (!pThis->hWnd)
264 {
265 DWORD dwErr = GetLastError();
266 LogFlowFunc(("Unable to create proxy window, error=%ld\n", dwErr));
267 rc = RTErrConvertFromWin32(dwErr);
268 }
269 else
270 {
271#ifndef VBOX_DND_DEBUG_WND
272 SetWindowPos(pThis->hWnd, HWND_TOPMOST, -200, -200, 0, 0,
273 SWP_NOACTIVATE | SWP_HIDEWINDOW
274 | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
275 LogFlowFunc(("Proxy window created, hWnd=0x%x\n", pThis->hWnd));
276#else
277 LogFlowFunc(("Debug proxy window created, hWnd=0x%x\n", pThis->hWnd));
278
279 /*
280 * Install some mouse tracking.
281 */
282 TRACKMOUSEEVENT me;
283 RT_ZERO(me);
284 me.cbSize = sizeof(TRACKMOUSEEVENT);
285 me.dwFlags = TME_HOVER | TME_LEAVE | TME_NONCLIENT;
286 me.hwndTrack = pThis->hWnd;
287 BOOL fRc = TrackMouseEvent(&me);
288 Assert(fRc);
289#endif
290 }
291 }
292
293 HRESULT hr = OleInitialize(NULL);
294 if (SUCCEEDED(hr))
295 {
296#ifdef VBOX_WITH_DRAG_AND_DROP_GH
297 rc = pThis->RegisterAsDropTarget();
298#endif
299 }
300 else
301 {
302 LogRel(("DnD: Unable to initialize OLE, hr=%Rhrc\n", hr));
303 rc = VERR_COM_UNEXPECTED;
304 }
305
306 if (RT_SUCCESS(rc))
307 pCtx->fStarted = true; /* Set started indicator on success. */
308
309 int rc2 = RTThreadUserSignal(hThread);
310 bool fSignalled = RT_SUCCESS(rc2);
311
312 if (RT_SUCCESS(rc))
313 {
314 bool fShutdown = false;
315 for (;;)
316 {
317 MSG uMsg;
318 BOOL fRet;
319 while ((fRet = GetMessage(&uMsg, 0, 0, 0)) > 0)
320 {
321 TranslateMessage(&uMsg);
322 DispatchMessage(&uMsg);
323 }
324 Assert(fRet >= 0);
325
326 if (ASMAtomicReadBool(&pCtx->fShutdown))
327 fShutdown = true;
328
329 if (fShutdown)
330 {
331 LogFlowFunc(("Closing proxy window ...\n"));
332 break;
333 }
334
335 /** @todo Immediately drop on failure? */
336 }
337
338#ifdef VBOX_WITH_DRAG_AND_DROP_GH
339 rc2 = pThis->UnregisterAsDropTarget();
340 if (RT_SUCCESS(rc))
341 rc = rc2;
342#endif
343 OleUninitialize();
344 }
345
346 if (!fSignalled)
347 {
348 rc2 = RTThreadUserSignal(hThread);
349 AssertRC(rc2);
350 }
351
352 LogFlowFuncLeaveRC(rc);
353 return rc;
354}
355
356/**
357 * Monitor enumeration callback for building up a simple bounding
358 * box, capable of holding all enumerated monitors.
359 *
360 * @return BOOL TRUE if enumeration should continue,
361 * FALSE if not.
362 * @param hMonitor Handle to current monitor being enumerated.
363 * @param hdcMonitor The current monitor's DC (device context).
364 * @param lprcMonitor The current monitor's RECT.
365 * @param lParam Pointer to a RECT structure holding the
366 * bounding box to build.
367 */
368/* static */
369BOOL CALLBACK VBoxDnDWnd::MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM lParam)
370{
371 RT_NOREF(hMonitor, hdcMonitor);
372 LPRECT pRect = (LPRECT)lParam;
373 AssertPtrReturn(pRect, FALSE);
374
375 AssertPtr(lprcMonitor);
376 LogFlowFunc(("Monitor is %ld,%ld,%ld,%ld\n",
377 lprcMonitor->left, lprcMonitor->top,
378 lprcMonitor->right, lprcMonitor->bottom));
379
380 /* Build up a simple bounding box to hold the entire (virtual) screen. */
381 if (pRect->left > lprcMonitor->left)
382 pRect->left = lprcMonitor->left;
383 if (pRect->right < lprcMonitor->right)
384 pRect->right = lprcMonitor->right;
385 if (pRect->top > lprcMonitor->top)
386 pRect->top = lprcMonitor->top;
387 if (pRect->bottom < lprcMonitor->bottom)
388 pRect->bottom = lprcMonitor->bottom;
389
390 return TRUE;
391}
392
393/**
394 * The proxy window's WndProc.
395 */
396LRESULT CALLBACK VBoxDnDWnd::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
397{
398 switch (uMsg)
399 {
400 case WM_CREATE:
401 {
402 int rc = OnCreate();
403 if (RT_FAILURE(rc))
404 {
405 LogRel(("DnD: Failed to create proxy window, rc=%Rrc\n", rc));
406 return -1;
407 }
408 return 0;
409 }
410
411 case WM_QUIT:
412 {
413 LogFlowThisFunc(("WM_QUIT\n"));
414 PostQuitMessage(0);
415 return 0;
416 }
417
418 case WM_DESTROY:
419 {
420 LogFlowThisFunc(("WM_DESTROY\n"));
421
422 OnDestroy();
423 return 0;
424 }
425
426 case WM_LBUTTONDOWN:
427 {
428 LogFlowThisFunc(("WM_LBUTTONDOWN\n"));
429 mfMouseButtonDown = true;
430 return 0;
431 }
432
433 case WM_LBUTTONUP:
434 {
435 LogFlowThisFunc(("WM_LBUTTONUP\n"));
436 mfMouseButtonDown = false;
437
438 /* As the mouse button was released, Hide the proxy window again.
439 * This can happen if
440 * - the user bumped a guest window to the screen's edges
441 * - there was no drop data from the guest available and the user
442 * enters the guest screen again after this unsuccessful operation */
443 Reset();
444 return 0;
445 }
446
447 case WM_MOUSELEAVE:
448 {
449 LogFlowThisFunc(("WM_MOUSELEAVE\n"));
450 return 0;
451 }
452
453 /* Will only be called once; after the first mouse move, this
454 * window will be hidden! */
455 case WM_MOUSEMOVE:
456 {
457 LogFlowThisFunc(("WM_MOUSEMOVE: mfMouseButtonDown=%RTbool, mMode=%ld, mState=%ld\n",
458 mfMouseButtonDown, mMode, mState));
459#ifdef DEBUG_andy
460 POINT p;
461 GetCursorPos(&p);
462 LogFlowThisFunc(("WM_MOUSEMOVE: curX=%ld, curY=%ld\n", p.x, p.y));
463#endif
464 int rc = VINF_SUCCESS;
465 if (mMode == HG) /* Host to guest. */
466 {
467 /* Dragging not started yet? Kick it off ... */
468 if ( mfMouseButtonDown
469 && (mState != Dragging))
470 {
471 mState = Dragging;
472#if 0
473 /* Delay hiding the proxy window a bit when debugging, to see
474 * whether the desired range is covered correctly. */
475 RTThreadSleep(5000);
476#endif
477 Hide();
478
479 LogFlowThisFunc(("Starting drag and drop: dndLstActionsAllowed=0x%x, dwOKEffects=0x%x ...\n",
480 dndLstActionsAllowed, startupInfo.dwOKEffects));
481
482 AssertPtr(startupInfo.pDataObject);
483 AssertPtr(startupInfo.pDropSource);
484 DWORD dwEffect;
485 HRESULT hr = DoDragDrop(startupInfo.pDataObject, startupInfo.pDropSource,
486 startupInfo.dwOKEffects, &dwEffect);
487 LogFlowThisFunc(("hr=%Rhrc, dwEffect=%RI32\n", hr, dwEffect));
488 switch (hr)
489 {
490 case DRAGDROP_S_DROP:
491 mState = Dropped;
492 break;
493
494 case DRAGDROP_S_CANCEL:
495 mState = Canceled;
496 break;
497
498 default:
499 LogFlowThisFunc(("Drag and drop failed with %Rhrc\n", hr));
500 mState = Canceled;
501 rc = VERR_GENERAL_FAILURE; /** @todo Find a better status code. */
502 break;
503 }
504
505 int rc2 = RTCritSectEnter(&mCritSect);
506 if (RT_SUCCESS(rc2))
507 {
508 startupInfo.pDropSource->Release();
509 startupInfo.pDataObject->Release();
510
511 RT_ZERO(startupInfo);
512
513 rc2 = RTCritSectLeave(&mCritSect);
514 if (RT_SUCCESS(rc))
515 rc = rc2;
516 }
517
518 mMode = Unknown;
519 }
520 }
521 else if (mMode == GH) /* Guest to host. */
522 {
523 /* Starting here VBoxDnDDropTarget should
524 * take over; was instantiated when registering
525 * this proxy window as a (valid) drop target. */
526 }
527 else
528 rc = VERR_NOT_SUPPORTED;
529
530 LogFlowThisFunc(("WM_MOUSEMOVE: mMode=%ld, mState=%ld, rc=%Rrc\n",
531 mMode, mState, rc));
532 return 0;
533 }
534
535 case WM_NCMOUSEHOVER:
536 LogFlowThisFunc(("WM_NCMOUSEHOVER\n"));
537 return 0;
538
539 case WM_NCMOUSELEAVE:
540 LogFlowThisFunc(("WM_NCMOUSELEAVE\n"));
541 return 0;
542
543 case WM_VBOXTRAY_DND_MESSAGE:
544 {
545 PVBOXDNDEVENT pEvent = (PVBOXDNDEVENT)lParam;
546 if (!pEvent)
547 break; /* No event received, bail out. */
548
549 PVBGLR3DNDEVENT pVbglR3Event = pEvent->pVbglR3Event;
550 AssertPtrBreak(pVbglR3Event);
551
552 LogFlowThisFunc(("Received enmType=%RU32\n", pVbglR3Event->enmType));
553
554 int rc;
555 switch (pVbglR3Event->enmType)
556 {
557 case VBGLR3DNDEVENTTYPE_HG_ENTER:
558 {
559 if (pVbglR3Event->u.HG_Enter.cbFormats)
560 {
561 RTCList<RTCString> lstFormats =
562 RTCString(pVbglR3Event->u.HG_Enter.pszFormats, pVbglR3Event->u.HG_Enter.cbFormats - 1).split("\r\n");
563 rc = OnHgEnter(lstFormats, pVbglR3Event->u.HG_Enter.dndLstActionsAllowed);
564 if (RT_FAILURE(rc))
565 break;
566 }
567 else
568 {
569 AssertMsgFailed(("cbFormats is 0\n"));
570 rc = VERR_INVALID_PARAMETER;
571 break;
572 }
573
574 /* Note: After HOST_DND_HG_EVT_ENTER there immediately is a move
575 * event, so fall through is intentional here. */
576 RT_FALL_THROUGH();
577 }
578
579 case VBGLR3DNDEVENTTYPE_HG_MOVE:
580 {
581 rc = OnHgMove(pVbglR3Event->u.HG_Move.uXpos, pVbglR3Event->u.HG_Move.uYpos,
582 pVbglR3Event->u.HG_Move.dndActionDefault);
583 break;
584 }
585
586 case VBGLR3DNDEVENTTYPE_HG_LEAVE:
587 {
588 rc = OnHgLeave();
589 break;
590 }
591
592 case VBGLR3DNDEVENTTYPE_HG_DROP:
593 {
594 rc = OnHgDrop();
595 break;
596 }
597
598 /**
599 * The data header now will contain all the (meta) data the guest needs in
600 * order to complete the DnD operation.
601 */
602 case VBGLR3DNDEVENTTYPE_HG_RECEIVE:
603 {
604 rc = OnHgDataReceive(&pVbglR3Event->u.HG_Received.Meta);
605 break;
606 }
607
608 case VBGLR3DNDEVENTTYPE_HG_CANCEL:
609 {
610 rc = OnHgCancel();
611 break;
612 }
613
614#ifdef VBOX_WITH_DRAG_AND_DROP_GH
615 case VBGLR3DNDEVENTTYPE_GH_ERROR:
616 {
617 Reset();
618 rc = VINF_SUCCESS;
619 break;
620 }
621
622 case VBGLR3DNDEVENTTYPE_GH_REQ_PENDING:
623 {
624 rc = OnGhIsDnDPending();
625 break;
626 }
627
628 case VBGLR3DNDEVENTTYPE_GH_DROP:
629 {
630 rc = OnGhDrop(pVbglR3Event->u.GH_Drop.pszFormat, pVbglR3Event->u.GH_Drop.dndActionRequested);
631 break;
632 }
633#endif
634 default:
635 {
636 LogRel(("DnD: Received unsupported message '%RU32'\n", pVbglR3Event->enmType));
637 rc = VERR_NOT_SUPPORTED;
638 break;
639 }
640 }
641
642 LogFlowFunc(("Message %RU32 processed with %Rrc\n", pVbglR3Event->enmType, rc));
643 if (RT_FAILURE(rc))
644 {
645 /* Tell the user. */
646 LogRel(("DnD: Processing message %RU32 failed with %Rrc\n", pVbglR3Event->enmType, rc));
647
648 /* If anything went wrong, do a reset and start over. */
649 Reset();
650 }
651
652 if (pEvent)
653 {
654 VbglR3DnDEventFree(pEvent->pVbglR3Event);
655 pEvent->pVbglR3Event = NULL;
656
657 RTMemFree(pEvent);
658 }
659
660 return 0;
661 }
662
663 default:
664 break;
665 }
666
667 return DefWindowProc(hWnd, uMsg, wParam, lParam);
668}
669
670#ifdef VBOX_WITH_DRAG_AND_DROP_GH
671/**
672 * Registers this proxy window as a local drop target.
673 *
674 * @return IPRT status code.
675 */
676int VBoxDnDWnd::RegisterAsDropTarget(void)
677{
678 if (pDropTarget) /* Already registered as drop target? */
679 return VINF_SUCCESS;
680
681 int rc;
682 try
683 {
684 pDropTarget = new VBoxDnDDropTarget(this /* pParent */);
685 HRESULT hr = CoLockObjectExternal(pDropTarget, TRUE /* fLock */,
686 FALSE /* fLastUnlockReleases */);
687 if (SUCCEEDED(hr))
688 hr = RegisterDragDrop(hWnd, pDropTarget);
689
690 if (FAILED(hr))
691 {
692 LogRel(("DnD: Creating drop target failed with hr=%Rhrc\n", hr));
693 rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
694 }
695 else
696 {
697 rc = VINF_SUCCESS;
698 }
699 }
700 catch (std::bad_alloc)
701 {
702 rc = VERR_NO_MEMORY;
703 }
704
705 LogFlowFuncLeaveRC(rc);
706 return rc;
707}
708
709/**
710 * Unregisters this proxy as a drop target.
711 *
712 * @return IPRT status code.
713 */
714int VBoxDnDWnd::UnregisterAsDropTarget(void)
715{
716 LogFlowFuncEnter();
717
718 if (!pDropTarget) /* No drop target? Bail out. */
719 return VINF_SUCCESS;
720
721 HRESULT hr = RevokeDragDrop(hWnd);
722 if (SUCCEEDED(hr))
723 hr = CoLockObjectExternal(pDropTarget, FALSE /* fLock */,
724 TRUE /* fLastUnlockReleases */);
725 if (SUCCEEDED(hr))
726 {
727 ULONG cRefs = pDropTarget->Release();
728 Assert(cRefs == 0); NOREF(cRefs);
729 pDropTarget = NULL;
730 }
731
732 int rc = SUCCEEDED(hr)
733 ? VINF_SUCCESS : VERR_GENERAL_FAILURE; /** @todo Fix this. */
734
735 LogFlowFuncLeaveRC(rc);
736 return rc;
737}
738#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
739
740/**
741 * Handles the creation of a proxy window.
742 *
743 * @return IPRT status code.
744 */
745int VBoxDnDWnd::OnCreate(void)
746{
747 LogFlowFuncEnter();
748 int rc = VbglR3DnDConnect(&mDnDCtx);
749 if (RT_FAILURE(rc))
750 {
751 LogRel(("DnD: Connection to host service failed, rc=%Rrc\n", rc));
752 return rc;
753 }
754
755 LogFlowThisFunc(("Client ID=%RU32, rc=%Rrc\n", mDnDCtx.uClientID, rc));
756 return rc;
757}
758
759/**
760 * Handles the destruction of a proxy window.
761 */
762void VBoxDnDWnd::OnDestroy(void)
763{
764 DestroyWindow(hWnd);
765
766 VbglR3DnDDisconnect(&mDnDCtx);
767 LogFlowThisFuncLeave();
768}
769
770/**
771 * Handles actions required when the host cursor enters
772 * the guest's screen to initiate a host -> guest DnD operation.
773 *
774 * @return IPRT status code.
775 * @param lstFormats Supported formats offered by the host.
776 * @param dndLstActionsAllowed Supported actions offered by the host.
777 */
778int VBoxDnDWnd::OnHgEnter(const RTCList<RTCString> &lstFormats, VBOXDNDACTIONLIST dndLstActionsAllowed)
779{
780 if (mMode == GH) /* Wrong mode? Bail out. */
781 return VERR_WRONG_ORDER;
782
783#ifdef DEBUG
784 LogFlowThisFunc(("dndActionList=0x%x, lstFormats=%zu: ", dndLstActionsAllowed, lstFormats.size()));
785 for (size_t i = 0; i < lstFormats.size(); i++)
786 LogFlow(("'%s' ", lstFormats.at(i).c_str()));
787 LogFlow(("\n"));
788#endif
789
790 Reset();
791 setMode(HG);
792
793 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
794 int rc = checkForSessionChange();
795 if (RT_FAILURE(rc))
796 return rc;
797
798 try
799 {
800 /* Save all allowed actions. */
801 this->dndLstActionsAllowed = dndLstActionsAllowed;
802
803 /*
804 * Check if reported formats from host are compatible with this client.
805 */
806 size_t cFormatsSup = this->lstFmtSup.size();
807 ULONG cFormatsActive = 0;
808
809 LPFORMATETC pFormatEtc = new FORMATETC[cFormatsSup];
810 RT_BZERO(pFormatEtc, sizeof(FORMATETC) * cFormatsSup);
811
812 LPSTGMEDIUM pStgMeds = new STGMEDIUM[cFormatsSup];
813 RT_BZERO(pStgMeds, sizeof(STGMEDIUM) * cFormatsSup);
814
815 LogRel2(("DnD: Reported formats:\n"));
816 for (size_t i = 0; i < lstFormats.size(); i++)
817 {
818 bool fSupported = false;
819 for (size_t a = 0; a < this->lstFmtSup.size(); a++)
820 {
821 const char *pszFormat = lstFormats.at(i).c_str();
822 LogFlowThisFunc(("\t\"%s\" <=> \"%s\"\n", this->lstFmtSup.at(a).c_str(), pszFormat));
823
824 fSupported = RTStrICmp(this->lstFmtSup.at(a).c_str(), pszFormat) == 0;
825 if (fSupported)
826 {
827 this->lstFmtActive.append(lstFormats.at(i));
828
829 /** @todo Put this into a \#define / struct. */
830 if (!RTStrICmp(pszFormat, "text/uri-list"))
831 {
832 pFormatEtc[cFormatsActive].cfFormat = CF_HDROP;
833 pFormatEtc[cFormatsActive].dwAspect = DVASPECT_CONTENT;
834 pFormatEtc[cFormatsActive].lindex = -1;
835 pFormatEtc[cFormatsActive].tymed = TYMED_HGLOBAL;
836
837 pStgMeds [cFormatsActive].tymed = TYMED_HGLOBAL;
838 cFormatsActive++;
839 }
840 else if ( !RTStrICmp(pszFormat, "text/plain")
841 || !RTStrICmp(pszFormat, "text/html")
842 || !RTStrICmp(pszFormat, "text/plain;charset=utf-8")
843 || !RTStrICmp(pszFormat, "text/plain;charset=utf-16")
844 || !RTStrICmp(pszFormat, "text/plain")
845 || !RTStrICmp(pszFormat, "text/richtext")
846 || !RTStrICmp(pszFormat, "UTF8_STRING")
847 || !RTStrICmp(pszFormat, "TEXT")
848 || !RTStrICmp(pszFormat, "STRING"))
849 {
850 pFormatEtc[cFormatsActive].cfFormat = CF_TEXT;
851 pFormatEtc[cFormatsActive].dwAspect = DVASPECT_CONTENT;
852 pFormatEtc[cFormatsActive].lindex = -1;
853 pFormatEtc[cFormatsActive].tymed = TYMED_HGLOBAL;
854
855 pStgMeds [cFormatsActive].tymed = TYMED_HGLOBAL;
856 cFormatsActive++;
857 }
858 else /* Should never happen. */
859 AssertReleaseMsgFailedBreak(("Format specification for '%s' not implemented\n", pszFormat));
860 break;
861 }
862 }
863
864 LogRel2(("DnD: \t%s: %RTbool\n", lstFormats.at(i).c_str(), fSupported));
865 }
866
867 /*
868 * Warn in the log if this guest does not accept anything.
869 */
870 Assert(cFormatsActive <= cFormatsSup);
871 if (cFormatsActive)
872 {
873 LogRel2(("DnD: %RU32 supported formats found:\n", cFormatsActive));
874 for (size_t i = 0; i < cFormatsActive; i++)
875 LogRel2(("DnD: \t%s\n", this->lstFmtActive.at(i).c_str()));
876 }
877 else
878 LogRel(("DnD: Warning: No supported drag and drop formats on the guest found!\n"));
879
880 /*
881 * Prepare the startup info for DoDragDrop().
882 */
883
884 /* Translate our drop actions into allowed Windows drop effects. */
885 startupInfo.dwOKEffects = DROPEFFECT_NONE;
886 if (dndLstActionsAllowed)
887 {
888 if (dndLstActionsAllowed & VBOX_DND_ACTION_COPY)
889 startupInfo.dwOKEffects |= DROPEFFECT_COPY;
890 if (dndLstActionsAllowed & VBOX_DND_ACTION_MOVE)
891 startupInfo.dwOKEffects |= DROPEFFECT_MOVE;
892 if (dndLstActionsAllowed & VBOX_DND_ACTION_LINK)
893 startupInfo.dwOKEffects |= DROPEFFECT_LINK;
894 }
895
896 LogRel2(("DnD: Supported drop actions: 0x%x\n", startupInfo.dwOKEffects));
897
898 startupInfo.pDropSource = new VBoxDnDDropSource(this);
899 startupInfo.pDataObject = new VBoxDnDDataObject(pFormatEtc, pStgMeds, cFormatsActive);
900
901 if (pFormatEtc)
902 delete pFormatEtc;
903 if (pStgMeds)
904 delete pStgMeds;
905 }
906 catch (std::bad_alloc)
907 {
908 rc = VERR_NO_MEMORY;
909 }
910
911 if (RT_SUCCESS(rc))
912 rc = makeFullscreen();
913
914 LogFlowFuncLeaveRC(rc);
915 return rc;
916}
917
918/**
919 * Handles actions required when the host cursor moves inside
920 * the guest's screen.
921 *
922 * @return IPRT status code.
923 * @param u32xPos Absolute X position (in pixels) of the host cursor
924 * inside the guest.
925 * @param u32yPos Absolute Y position (in pixels) of the host cursor
926 * inside the guest.
927 * @param dndAction Action the host wants to perform while moving.
928 * Currently ignored.
929 */
930int VBoxDnDWnd::OnHgMove(uint32_t u32xPos, uint32_t u32yPos, VBOXDNDACTION dndAction)
931{
932 RT_NOREF(dndAction);
933 int rc;
934
935 uint32_t uActionNotify = VBOX_DND_ACTION_IGNORE;
936 if (mMode == HG)
937 {
938 LogFlowThisFunc(("u32xPos=%RU32, u32yPos=%RU32, dndAction=0x%x\n",
939 u32xPos, u32yPos, dndAction));
940
941 rc = mouseMove(u32xPos, u32yPos, MOUSEEVENTF_LEFTDOWN);
942
943 if (RT_SUCCESS(rc))
944 rc = RTCritSectEnter(&mCritSect);
945 if (RT_SUCCESS(rc))
946 {
947 if ( (Dragging == mState)
948 && startupInfo.pDropSource)
949 uActionNotify = startupInfo.pDropSource->GetCurrentAction();
950
951 RTCritSectLeave(&mCritSect);
952 }
953 }
954 else /* Just acknowledge the operation with an ignore action. */
955 rc = VINF_SUCCESS;
956
957 if (RT_SUCCESS(rc))
958 {
959 rc = VbglR3DnDHGSendAckOp(&mDnDCtx, uActionNotify);
960 if (RT_FAILURE(rc))
961 LogFlowThisFunc(("Acknowledging operation failed with rc=%Rrc\n", rc));
962 }
963
964 LogFlowThisFunc(("Returning uActionNotify=0x%x, rc=%Rrc\n", uActionNotify, rc));
965 return rc;
966}
967
968/**
969 * Handles actions required when the host cursor leaves
970 * the guest's screen again.
971 *
972 * @return IPRT status code.
973 */
974int VBoxDnDWnd::OnHgLeave(void)
975{
976 if (mMode == GH) /* Wrong mode? Bail out. */
977 return VERR_WRONG_ORDER;
978
979 LogFlowThisFunc(("mMode=%ld, mState=%RU32\n", mMode, mState));
980 LogRel(("DnD: Drag and drop operation aborted\n"));
981
982 Reset();
983
984 int rc = VINF_SUCCESS;
985
986 /* Post ESC to our window to officially abort the
987 * drag and drop operation. */
988 this->PostMessage(WM_KEYDOWN, VK_ESCAPE /* wParam */, 0 /* lParam */);
989
990 LogFlowFuncLeaveRC(rc);
991 return rc;
992}
993
994/**
995 * Handles actions required when the host cursor wants to drop
996 * and therefore start a "drop" action in the guest.
997 *
998 * @return IPRT status code.
999 */
1000int VBoxDnDWnd::OnHgDrop(void)
1001{
1002 if (mMode == GH)
1003 return VERR_WRONG_ORDER;
1004
1005 LogFlowThisFunc(("mMode=%ld, mState=%RU32\n", mMode, mState));
1006
1007 int rc = VINF_SUCCESS;
1008 if (mState == Dragging)
1009 {
1010 if (lstFmtActive.size() >= 1)
1011 {
1012 /** @todo What to do when multiple formats are available? */
1013 mFormatRequested = lstFmtActive.at(0);
1014
1015 rc = RTCritSectEnter(&mCritSect);
1016 if (RT_SUCCESS(rc))
1017 {
1018 if (startupInfo.pDataObject)
1019 startupInfo.pDataObject->SetStatus(VBoxDnDDataObject::Dropping);
1020 else
1021 rc = VERR_NOT_FOUND;
1022
1023 RTCritSectLeave(&mCritSect);
1024 }
1025
1026 if (RT_SUCCESS(rc))
1027 {
1028 LogRel(("DnD: Requesting data as '%s' ...\n", mFormatRequested.c_str()));
1029 rc = VbglR3DnDHGSendReqData(&mDnDCtx, mFormatRequested.c_str());
1030 if (RT_FAILURE(rc))
1031 LogFlowThisFunc(("Requesting data failed with rc=%Rrc\n", rc));
1032 }
1033
1034 }
1035 else /* Should never happen. */
1036 LogRel(("DnD: Error: Host did not specify a data format for drop data\n"));
1037 }
1038
1039 LogFlowFuncLeaveRC(rc);
1040 return rc;
1041}
1042
1043/**
1044 * Handles actions required when the host has sent over DnD data
1045 * to the guest after a "drop" event.
1046 *
1047 * @return IPRT status code.
1048 * @param pMeta Pointer to meta data received.
1049 */
1050int VBoxDnDWnd::OnHgDataReceive(PVBGLR3GUESTDNDMETADATA pMeta)
1051{
1052 LogFlowThisFunc(("mState=%ld, enmMetaType=%RU32, cbMeta=%RU32\n", mState, pMeta->enmType, pMeta->cbMeta));
1053
1054 mState = Dropped;
1055
1056 int rc = VINF_SUCCESS;
1057 if (pMeta->pvMeta)
1058 {
1059 Assert(pMeta->cbMeta);
1060 rc = RTCritSectEnter(&mCritSect);
1061 if (RT_SUCCESS(rc))
1062 {
1063 if (startupInfo.pDataObject)
1064 rc = startupInfo.pDataObject->Signal(mFormatRequested, pMeta->pvMeta, pMeta->cbMeta);
1065 else
1066 rc = VERR_NOT_FOUND;
1067
1068 RTCritSectLeave(&mCritSect);
1069 }
1070 }
1071
1072 int rc2 = mouseRelease();
1073 if (RT_SUCCESS(rc))
1074 rc = rc2;
1075
1076 LogFlowFuncLeaveRC(rc);
1077 return rc;
1078}
1079
1080/**
1081 * Handles actions required when the host wants to cancel the current
1082 * host -> guest operation.
1083 *
1084 * @return IPRT status code.
1085 */
1086int VBoxDnDWnd::OnHgCancel(void)
1087{
1088 int rc = RTCritSectEnter(&mCritSect);
1089 if (RT_SUCCESS(rc))
1090 {
1091 if (startupInfo.pDataObject)
1092 startupInfo.pDataObject->Abort();
1093
1094 RTCritSectLeave(&mCritSect);
1095 }
1096
1097 int rc2 = mouseRelease();
1098 if (RT_SUCCESS(rc))
1099 rc = rc2;
1100
1101 Reset();
1102
1103 return rc;
1104}
1105
1106#ifdef VBOX_WITH_DRAG_AND_DROP_GH
1107/**
1108 * Handles actions required to start a guest -> host DnD operation.
1109 * This works by letting the host ask whether a DnD operation is pending
1110 * on the guest. The guest must not know anything about the host's DnD state
1111 * and/or operations due to security reasons.
1112 *
1113 * To capture a pending DnD operation on the guest which then can be communicated
1114 * to the host the proxy window needs to be registered as a drop target. This drop
1115 * target then will act as a proxy target between the guest OS and the host. In other
1116 * words, the guest OS will use this proxy target as a regular (invisible) window
1117 * which can be used by the regular guest OS' DnD mechanisms, independently of the
1118 * host OS. To make sure this proxy target is able receive an in-progress DnD operation
1119 * on the guest, it will be shown invisibly across all active guest OS screens. Just
1120 * think of an opened umbrella across all screens here.
1121 *
1122 * As soon as the proxy target and its underlying data object receive appropriate
1123 * DnD messages they'll be hidden again, and the control will be transferred back
1124 * this class again.
1125 *
1126 * @return IPRT status code.
1127 */
1128int VBoxDnDWnd::OnGhIsDnDPending(void)
1129{
1130 LogFlowThisFunc(("mMode=%ld, mState=%ld\n", mMode, mState));
1131
1132 if (mMode == Unknown)
1133 setMode(GH);
1134
1135 if (mMode != GH)
1136 return VERR_WRONG_ORDER;
1137
1138 if (mState == Uninitialized)
1139 {
1140 /* Nothing to do here yet. */
1141 mState = Initialized;
1142 }
1143
1144 int rc;
1145 if (mState == Initialized)
1146 {
1147 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
1148 rc = checkForSessionChange();
1149 if (RT_SUCCESS(rc))
1150 {
1151 rc = makeFullscreen();
1152 if (RT_SUCCESS(rc))
1153 {
1154 /*
1155 * We have to release the left mouse button to
1156 * get into our (invisible) proxy window.
1157 */
1158 mouseRelease();
1159
1160 /*
1161 * Even if we just released the left mouse button
1162 * we're still in the dragging state to handle our
1163 * own drop target (for the host).
1164 */
1165 mState = Dragging;
1166 }
1167 }
1168 }
1169 else
1170 rc = VINF_SUCCESS;
1171
1172 /**
1173 * Some notes regarding guest cursor movement:
1174 * - The host only sends an HOST_DND_GH_REQ_PENDING message to the guest
1175 * if the mouse cursor is outside the VM's window.
1176 * - The guest does not know anything about the host's cursor
1177 * position / state due to security reasons.
1178 * - The guest *only* knows that the host currently is asking whether a
1179 * guest DnD operation is in progress.
1180 */
1181
1182 if ( RT_SUCCESS(rc)
1183 && mState == Dragging)
1184 {
1185 /** @todo Put this block into a function! */
1186 POINT p;
1187 GetCursorPos(&p);
1188 ClientToScreen(hWnd, &p);
1189#ifdef DEBUG_andy
1190 LogFlowThisFunc(("Client to screen curX=%ld, curY=%ld\n", p.x, p.y));
1191#endif
1192
1193 /** @todo Multi-monitor setups? */
1194#if 0 /* unused */
1195 int iScreenX = GetSystemMetrics(SM_CXSCREEN) - 1;
1196 int iScreenY = GetSystemMetrics(SM_CYSCREEN) - 1;
1197#endif
1198
1199 LONG px = p.x;
1200 if (px <= 0)
1201 px = 1;
1202 LONG py = p.y;
1203 if (py <= 0)
1204 py = 1;
1205
1206 rc = mouseMove(px, py, 0 /* dwMouseInputFlags */);
1207 }
1208
1209 if (RT_SUCCESS(rc))
1210 {
1211 VBOXDNDACTION dndActionDefault = VBOX_DND_ACTION_IGNORE;
1212
1213 AssertPtr(pDropTarget);
1214 RTCString strFormats = pDropTarget->Formats();
1215 if (!strFormats.isEmpty())
1216 {
1217 dndActionDefault = VBOX_DND_ACTION_COPY;
1218
1219 LogFlowFunc(("Acknowledging pDropTarget=0x%p, dndActionDefault=0x%x, dndLstActionsAllowed=0x%x, strFormats=%s\n",
1220 pDropTarget, dndActionDefault, dndLstActionsAllowed, strFormats.c_str()));
1221 }
1222 else
1223 {
1224 strFormats = "unknown"; /* Prevent VERR_IO_GEN_FAILURE for IOCTL. */
1225 LogFlowFunc(("No format data from proxy window available yet\n"));
1226 }
1227
1228 /** @todo Support more than one action at a time. */
1229 dndLstActionsAllowed = dndActionDefault;
1230
1231 int rc2 = VbglR3DnDGHSendAckPending(&mDnDCtx,
1232 dndActionDefault, dndLstActionsAllowed,
1233 strFormats.c_str(), (uint32_t)strFormats.length() + 1 /* Include termination */);
1234 if (RT_FAILURE(rc2))
1235 {
1236 char szMsg[256]; /* Sizes according to MSDN. */
1237 char szTitle[64];
1238
1239 /** @todo Add some i18l tr() macros here. */
1240 RTStrPrintf(szTitle, sizeof(szTitle), "VirtualBox Guest Additions Drag and Drop");
1241 RTStrPrintf(szMsg, sizeof(szMsg), "Drag and drop to the host either is not supported or disabled. "
1242 "Please enable Guest to Host or Bidirectional drag and drop mode "
1243 "or re-install the VirtualBox Guest Additions.");
1244 switch (rc2)
1245 {
1246 case VERR_ACCESS_DENIED:
1247 {
1248 rc = hlpShowBalloonTip(g_hInstance, g_hwndToolWindow, ID_TRAYICON,
1249 szMsg, szTitle,
1250 15 * 1000 /* Time to display in msec */, NIIF_INFO);
1251 AssertRC(rc);
1252 break;
1253 }
1254
1255 default:
1256 break;
1257 }
1258
1259 LogRel2(("DnD: Host refuses drag and drop operation from guest: %Rrc\n", rc2));
1260 Reset();
1261 }
1262 }
1263
1264 if (RT_FAILURE(rc))
1265 Reset(); /* Reset state on failure. */
1266
1267 LogFlowFuncLeaveRC(rc);
1268 return rc;
1269}
1270
1271/**
1272 * Handles actions required to let the guest know that the host
1273 * started a "drop" action on the host. This will tell the guest
1274 * to send data in a specific format the host requested.
1275 *
1276 * @return IPRT status code.
1277 * @param pszFormat Format the host requests the data in.
1278 * @param cbFormat Size (in bytes) of format string.
1279 * @param dndActionDefault Default action on the host.
1280 */
1281int VBoxDnDWnd::OnGhDrop(const RTCString &strFormat, uint32_t dndActionDefault)
1282{
1283 RT_NOREF(dndActionDefault);
1284
1285 LogFlowThisFunc(("mMode=%ld, mState=%ld, pDropTarget=0x%p, strFormat=%s, dndActionDefault=0x%x\n",
1286 mMode, mState, pDropTarget, strFormat.c_str(), dndActionDefault));
1287 int rc;
1288 if (mMode == GH)
1289 {
1290 if (mState == Dragging)
1291 {
1292 AssertPtr(pDropTarget);
1293 rc = pDropTarget->WaitForDrop(5 * 1000 /* 5s timeout */);
1294
1295 Reset();
1296 }
1297 else if (mState == Dropped)
1298 {
1299 rc = VINF_SUCCESS;
1300 }
1301 else
1302 rc = VERR_WRONG_ORDER;
1303
1304 if (RT_SUCCESS(rc))
1305 {
1306 /** @todo Respect uDefAction. */
1307 void *pvData = pDropTarget->DataMutableRaw();
1308 uint32_t cbData = (uint32_t)pDropTarget->DataSize();
1309 Assert(cbData == pDropTarget->DataSize());
1310
1311 if ( pvData
1312 && cbData)
1313 {
1314 rc = VbglR3DnDGHSendData(&mDnDCtx, strFormat.c_str(), pvData, cbData);
1315 LogFlowFunc(("Sent pvData=0x%p, cbData=%RU32, rc=%Rrc\n", pvData, cbData, rc));
1316 }
1317 else
1318 rc = VERR_NO_DATA;
1319 }
1320 }
1321 else
1322 rc = VERR_WRONG_ORDER;
1323
1324 if (RT_FAILURE(rc))
1325 {
1326 /*
1327 * If an error occurred or the guest is in a wrong DnD mode,
1328 * send an error to the host in any case so that the host does
1329 * not wait for the data it expects from the guest.
1330 */
1331 int rc2 = VbglR3DnDGHSendError(&mDnDCtx, rc);
1332 AssertRC(rc2);
1333 }
1334
1335 LogFlowFuncLeaveRC(rc);
1336 return rc;
1337}
1338#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
1339
1340void VBoxDnDWnd::PostMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
1341{
1342 LogFlowFunc(("Posting message %u\n"));
1343 BOOL fRc = ::PostMessage(hWnd, uMsg, wParam, lParam);
1344 Assert(fRc); NOREF(fRc);
1345}
1346
1347/**
1348 * Injects a DnD event in this proxy window's Windows
1349 * event queue. The (allocated) event will be deleted by
1350 * this class after processing.
1351 *
1352 * @return IPRT status code.
1353 * @param pEvent Event to inject.
1354 */
1355int VBoxDnDWnd::ProcessEvent(PVBOXDNDEVENT pEvent)
1356{
1357 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1358
1359 BOOL fRc = ::PostMessage(hWnd, WM_VBOXTRAY_DND_MESSAGE,
1360 0 /* wParm */, (LPARAM)pEvent /* lParm */);
1361 if (!fRc)
1362 {
1363 DWORD dwErr = GetLastError();
1364
1365 static int s_iBitchedAboutFailedDnDMessages = 0;
1366 if (s_iBitchedAboutFailedDnDMessages++ < 32)
1367 {
1368 LogRel(("DnD: Processing event %p failed with %ld (%Rrc), skipping\n",
1369 pEvent, dwErr, RTErrConvertFromWin32(dwErr)));
1370 }
1371
1372 VbglR3DnDEventFree(pEvent->pVbglR3Event);
1373
1374 RTMemFree(pEvent);
1375 pEvent = NULL;
1376
1377 return RTErrConvertFromWin32(dwErr);
1378 }
1379
1380 return VINF_SUCCESS;
1381}
1382
1383/**
1384 * Checks if the VM session has changed (can happen when restoring the VM from a saved state)
1385 * and do a reconnect to the DnD HGCM service.
1386 *
1387 * @returns IPRT status code.
1388 */
1389int VBoxDnDWnd::checkForSessionChange(void)
1390{
1391 uint64_t uSessionID;
1392 int rc = VbglR3GetSessionId(&uSessionID);
1393 if ( RT_SUCCESS(rc)
1394 && uSessionID != mDnDCtx.uSessionID)
1395 {
1396 LogFlowThisFunc(("VM session has changed to %RU64\n", uSessionID));
1397
1398 rc = VbglR3DnDDisconnect(&mDnDCtx);
1399 AssertRC(rc);
1400
1401 rc = VbglR3DnDConnect(&mDnDCtx);
1402 AssertRC(rc);
1403 }
1404
1405 LogFlowFuncLeaveRC(rc);
1406 return rc;
1407}
1408
1409/**
1410 * Hides the proxy window again.
1411 *
1412 * @return IPRT status code.
1413 */
1414int VBoxDnDWnd::Hide(void)
1415{
1416#ifdef DEBUG_andy
1417 LogFlowFunc(("\n"));
1418#endif
1419 ShowWindow(hWnd, SW_HIDE);
1420
1421 return VINF_SUCCESS;
1422}
1423
1424/**
1425 * Shows the (invisible) proxy window in fullscreen,
1426 * spawned across all active guest monitors.
1427 *
1428 * @return IPRT status code.
1429 */
1430int VBoxDnDWnd::makeFullscreen(void)
1431{
1432 int rc = VINF_SUCCESS;
1433
1434 RECT r;
1435 RT_ZERO(r);
1436
1437 BOOL fRc;
1438 HDC hDC = GetDC(NULL /* Entire screen */);
1439 if (hDC)
1440 {
1441 fRc = g_pfnEnumDisplayMonitors
1442 /* EnumDisplayMonitors is not available on NT4. */
1443 ? g_pfnEnumDisplayMonitors(hDC, NULL, VBoxDnDWnd::MonitorEnumProc, (LPARAM)&r):
1444 FALSE;
1445
1446 if (!fRc)
1447 rc = VERR_NOT_FOUND;
1448 ReleaseDC(NULL, hDC);
1449 }
1450 else
1451 rc = VERR_ACCESS_DENIED;
1452
1453 if (RT_FAILURE(rc))
1454 {
1455 /* If multi-monitor enumeration failed above, try getting at least the
1456 * primary monitor as a fallback. */
1457 r.left = 0;
1458 r.top = 0;
1459 r.right = GetSystemMetrics(SM_CXSCREEN);
1460 r.bottom = GetSystemMetrics(SM_CYSCREEN);
1461 rc = VINF_SUCCESS;
1462 }
1463
1464 if (RT_SUCCESS(rc))
1465 {
1466 LONG lStyle = GetWindowLong(hWnd, GWL_STYLE);
1467 SetWindowLong(hWnd, GWL_STYLE,
1468 lStyle & ~(WS_CAPTION | WS_THICKFRAME));
1469 LONG lExStyle = GetWindowLong(hWnd, GWL_EXSTYLE);
1470 SetWindowLong(hWnd, GWL_EXSTYLE,
1471 lExStyle & ~( WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE
1472 | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
1473
1474 fRc = SetWindowPos(hWnd, HWND_TOPMOST,
1475 r.left,
1476 r.top,
1477 r.right - r.left,
1478 r.bottom - r.top,
1479#ifdef VBOX_DND_DEBUG_WND
1480 SWP_SHOWWINDOW | SWP_FRAMECHANGED);
1481#else
1482 SWP_SHOWWINDOW | SWP_NOOWNERZORDER | SWP_NOREDRAW | SWP_NOACTIVATE);
1483#endif
1484 if (fRc)
1485 {
1486 LogFlowFunc(("Virtual screen is %ld,%ld,%ld,%ld (%ld x %ld)\n",
1487 r.left, r.top, r.right, r.bottom,
1488 r.right - r.left, r.bottom - r.top));
1489 }
1490 else
1491 {
1492 DWORD dwErr = GetLastError();
1493 LogRel(("DnD: Failed to set proxy window position, rc=%Rrc\n",
1494 RTErrConvertFromWin32(dwErr)));
1495 }
1496 }
1497 else
1498 LogRel(("DnD: Failed to determine virtual screen size, rc=%Rrc\n", rc));
1499
1500 LogFlowFuncLeaveRC(rc);
1501 return rc;
1502}
1503
1504/**
1505 * Moves the guest mouse cursor to a specific position.
1506 *
1507 * @return IPRT status code.
1508 * @param x X position (in pixels) to move cursor to.
1509 * @param y Y position (in pixels) to move cursor to.
1510 * @param dwMouseInputFlags Additional movement flags. @sa MOUSEEVENTF_ flags.
1511 */
1512int VBoxDnDWnd::mouseMove(int x, int y, DWORD dwMouseInputFlags)
1513{
1514 int iScreenX = GetSystemMetrics(SM_CXSCREEN) - 1;
1515 int iScreenY = GetSystemMetrics(SM_CYSCREEN) - 1;
1516
1517 INPUT Input[1] = { 0 };
1518 Input[0].type = INPUT_MOUSE;
1519 Input[0].mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE
1520 | dwMouseInputFlags;
1521 Input[0].mi.dx = x * (65535 / iScreenX);
1522 Input[0].mi.dy = y * (65535 / iScreenY);
1523
1524 int rc;
1525 if (g_pfnSendInput(1 /* Number of inputs */,
1526 Input, sizeof(INPUT)))
1527 {
1528#ifdef DEBUG_andy
1529 CURSORINFO ci;
1530 RT_ZERO(ci);
1531 ci.cbSize = sizeof(ci);
1532 BOOL fRc = GetCursorInfo(&ci);
1533 if (fRc)
1534 LogFlowThisFunc(("Cursor shown=%RTbool, cursor=0x%p, x=%d, y=%d\n",
1535 (ci.flags & CURSOR_SHOWING) ? true : false,
1536 ci.hCursor, ci.ptScreenPos.x, ci.ptScreenPos.y));
1537#endif
1538 rc = VINF_SUCCESS;
1539 }
1540 else
1541 {
1542 DWORD dwErr = GetLastError();
1543 rc = RTErrConvertFromWin32(dwErr);
1544 LogFlowFunc(("SendInput failed with rc=%Rrc\n", rc));
1545 }
1546
1547 return rc;
1548}
1549
1550/**
1551 * Releases a previously pressed left guest mouse button.
1552 *
1553 * @return IPRT status code.
1554 */
1555int VBoxDnDWnd::mouseRelease(void)
1556{
1557 LogFlowFuncEnter();
1558
1559 int rc;
1560
1561 /* Release mouse button in the guest to start the "drop"
1562 * action at the current mouse cursor position. */
1563 INPUT Input[1] = { 0 };
1564 Input[0].type = INPUT_MOUSE;
1565 Input[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;
1566 if (!g_pfnSendInput(1, Input, sizeof(INPUT)))
1567 {
1568 DWORD dwErr = GetLastError();
1569 rc = RTErrConvertFromWin32(dwErr);
1570 LogFlowFunc(("SendInput failed with rc=%Rrc\n", rc));
1571 }
1572 else
1573 rc = VINF_SUCCESS;
1574
1575 return rc;
1576}
1577
1578/**
1579 * Resets the proxy window.
1580 */
1581void VBoxDnDWnd::Reset(void)
1582{
1583 LogFlowThisFunc(("Resetting, old mMode=%ld, mState=%ld\n",
1584 mMode, mState));
1585
1586 /*
1587 * Note: Don't clear this->lstAllowedFormats at the moment, as this value is initialized
1588 * on class creation. We might later want to modify the allowed formats at runtime,
1589 * so keep this in mind when implementing this.
1590 */
1591
1592 this->lstFmtActive.clear();
1593 this->dndLstActionsAllowed = VBOX_DND_ACTION_IGNORE;
1594
1595 int rc2 = setMode(Unknown);
1596 AssertRC(rc2);
1597
1598 Hide();
1599}
1600
1601/**
1602 * Sets the current operation mode of this proxy window.
1603 *
1604 * @return IPRT status code.
1605 * @param enmMode New mode to set.
1606 */
1607int VBoxDnDWnd::setMode(Mode enmMode)
1608{
1609 LogFlowThisFunc(("Old mode=%ld, new mode=%ld\n",
1610 mMode, enmMode));
1611
1612 mMode = enmMode;
1613 mState = Initialized;
1614
1615 return VINF_SUCCESS;
1616}
1617
1618/**
1619 * Static helper function for having an own WndProc for proxy
1620 * window instances.
1621 */
1622static LRESULT CALLBACK vboxDnDWndProcInstance(HWND hWnd, UINT uMsg,
1623 WPARAM wParam, LPARAM lParam)
1624{
1625 LONG_PTR pUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);
1626 AssertPtrReturn(pUserData, 0);
1627
1628 VBoxDnDWnd *pWnd = reinterpret_cast<VBoxDnDWnd *>(pUserData);
1629 if (pWnd)
1630 return pWnd->WndProc(hWnd, uMsg, wParam, lParam);
1631
1632 return 0;
1633}
1634
1635/**
1636 * Static helper function for routing Windows messages to a specific
1637 * proxy window instance.
1638 */
1639static LRESULT CALLBACK vboxDnDWndProc(HWND hWnd, UINT uMsg,
1640 WPARAM wParam, LPARAM lParam)
1641{
1642 /* Note: WM_NCCREATE is not the first ever message which arrives, but
1643 * early enough for us. */
1644 if (uMsg == WM_NCCREATE)
1645 {
1646 LPCREATESTRUCT pCS = (LPCREATESTRUCT)lParam;
1647 AssertPtr(pCS);
1648 SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pCS->lpCreateParams);
1649 SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)vboxDnDWndProcInstance);
1650
1651 return vboxDnDWndProcInstance(hWnd, uMsg, wParam, lParam);
1652 }
1653
1654 /* No window associated yet. */
1655 return DefWindowProc(hWnd, uMsg, wParam, lParam);
1656}
1657
1658/**
1659 * Initializes drag and drop.
1660 *
1661 * @return IPRT status code.
1662 * @param pEnv The DnD service's environment.
1663 * @param ppInstance The instance pointer which refer to this object.
1664 */
1665DECLCALLBACK(int) VBoxDnDInit(const PVBOXSERVICEENV pEnv, void **ppInstance)
1666{
1667 AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
1668 AssertPtrReturn(ppInstance, VERR_INVALID_POINTER);
1669
1670 LogFlowFuncEnter();
1671
1672 PVBOXDNDCONTEXT pCtx = &g_Ctx; /* Only one instance at the moment. */
1673 AssertPtr(pCtx);
1674
1675 int rc;
1676 bool fSupportedOS = true;
1677
1678 if (VbglR3AutoLogonIsRemoteSession())
1679 {
1680 /* Do not do drag and drop for remote sessions. */
1681 LogRel(("DnD: Drag and drop has been disabled for a remote session\n"));
1682 rc = VERR_NOT_SUPPORTED;
1683 }
1684 else
1685 rc = VINF_SUCCESS;
1686
1687 if (RT_SUCCESS(rc))
1688 {
1689 g_pfnSendInput = (PFNSENDINPUT)
1690 RTLdrGetSystemSymbol("User32.dll", "SendInput");
1691 fSupportedOS = !RT_BOOL(g_pfnSendInput == NULL);
1692 g_pfnEnumDisplayMonitors = (PFNENUMDISPLAYMONITORS)
1693 RTLdrGetSystemSymbol("User32.dll", "EnumDisplayMonitors");
1694 /* g_pfnEnumDisplayMonitors is optional. */
1695
1696 if (!fSupportedOS)
1697 {
1698 LogRel(("DnD: Not supported Windows version, disabling drag and drop support\n"));
1699 rc = VERR_NOT_SUPPORTED;
1700 }
1701 }
1702
1703 if (RT_SUCCESS(rc))
1704 {
1705 /* Assign service environment to our context. */
1706 pCtx->pEnv = pEnv;
1707
1708 /* Create the proxy window. At the moment we
1709 * only support one window at a time. */
1710 VBoxDnDWnd *pWnd = NULL;
1711 try
1712 {
1713 pWnd = new VBoxDnDWnd();
1714 rc = pWnd->Initialize(pCtx);
1715
1716 /* Add proxy window to our proxy windows list. */
1717 if (RT_SUCCESS(rc))
1718 pCtx->lstWnd.append(pWnd);
1719 }
1720 catch (std::bad_alloc)
1721 {
1722 rc = VERR_NO_MEMORY;
1723 }
1724 }
1725
1726 if (RT_SUCCESS(rc))
1727 rc = RTSemEventCreate(&pCtx->hEvtQueueSem);
1728 if (RT_SUCCESS(rc))
1729 {
1730 *ppInstance = pCtx;
1731
1732 LogRel(("DnD: Drag and drop service successfully started\n"));
1733 }
1734 else
1735 LogRel(("DnD: Initializing drag and drop service failed with rc=%Rrc\n", rc));
1736
1737 LogFlowFuncLeaveRC(rc);
1738 return rc;
1739}
1740
1741DECLCALLBACK(int) VBoxDnDStop(void *pInstance)
1742{
1743 AssertPtrReturn(pInstance, VERR_INVALID_POINTER);
1744
1745 LogFunc(("Stopping pInstance=%p\n", pInstance));
1746
1747 PVBOXDNDCONTEXT pCtx = (PVBOXDNDCONTEXT)pInstance;
1748 AssertPtr(pCtx);
1749
1750 /* Set shutdown indicator. */
1751 ASMAtomicWriteBool(&pCtx->fShutdown, true);
1752
1753 /* Disconnect. */
1754 VbglR3DnDDisconnect(&pCtx->cmdCtx);
1755
1756 LogFlowFuncLeaveRC(VINF_SUCCESS);
1757 return VINF_SUCCESS;
1758}
1759
1760DECLCALLBACK(void) VBoxDnDDestroy(void *pInstance)
1761{
1762 AssertPtrReturnVoid(pInstance);
1763
1764 LogFunc(("Destroying pInstance=%p\n", pInstance));
1765
1766 PVBOXDNDCONTEXT pCtx = (PVBOXDNDCONTEXT)pInstance;
1767 AssertPtr(pCtx);
1768
1769 /** @todo At the moment we only have one DnD proxy window. */
1770 Assert(pCtx->lstWnd.size() == 1);
1771 VBoxDnDWnd *pWnd = pCtx->lstWnd.first();
1772 if (pWnd)
1773 {
1774 delete pWnd;
1775 pWnd = NULL;
1776 }
1777
1778 if (pCtx->hEvtQueueSem != NIL_RTSEMEVENT)
1779 {
1780 RTSemEventDestroy(pCtx->hEvtQueueSem);
1781 pCtx->hEvtQueueSem = NIL_RTSEMEVENT;
1782 }
1783
1784 LogFunc(("Destroyed pInstance=%p\n", pInstance));
1785}
1786
1787DECLCALLBACK(int) VBoxDnDWorker(void *pInstance, bool volatile *pfShutdown)
1788{
1789 AssertPtr(pInstance);
1790 AssertPtr(pfShutdown);
1791
1792 LogFlowFunc(("pInstance=%p\n", pInstance));
1793
1794 /*
1795 * Tell the control thread that it can continue
1796 * spawning services.
1797 */
1798 RTThreadUserSignal(RTThreadSelf());
1799
1800 PVBOXDNDCONTEXT pCtx = (PVBOXDNDCONTEXT)pInstance;
1801 AssertPtr(pCtx);
1802
1803 int rc = VbglR3DnDConnect(&pCtx->cmdCtx);
1804 if (RT_FAILURE(rc))
1805 return rc;
1806
1807 /** @todo At the moment we only have one DnD proxy window. */
1808 Assert(pCtx->lstWnd.size() == 1);
1809 VBoxDnDWnd *pWnd = pCtx->lstWnd.first();
1810 AssertPtr(pWnd);
1811
1812 /* Number of invalid messages skipped in a row. */
1813 int cMsgSkippedInvalid = 0;
1814 PVBOXDNDEVENT pEvent = NULL;
1815
1816 for (;;)
1817 {
1818 pEvent = (PVBOXDNDEVENT)RTMemAllocZ(sizeof(VBOXDNDEVENT));
1819 if (!pEvent)
1820 {
1821 rc = VERR_NO_MEMORY;
1822 break;
1823 }
1824 /* Note: pEvent will be free'd by the consumer later. */
1825
1826 PVBGLR3DNDEVENT pVbglR3Event = NULL;
1827 rc = VbglR3DnDEventGetNext(&pCtx->cmdCtx, &pVbglR3Event);
1828 if (RT_SUCCESS(rc))
1829 {
1830 LogFunc(("enmType=%RU32, rc=%Rrc\n", pVbglR3Event->enmType, rc));
1831
1832 cMsgSkippedInvalid = 0; /* Reset skipped messages count. */
1833
1834 LogRel2(("DnD: Received new event, type=%RU32, rc=%Rrc\n", pVbglR3Event->enmType, rc));
1835
1836 /* pEvent now owns pVbglR3Event. */
1837 pEvent->pVbglR3Event = pVbglR3Event;
1838 pVbglR3Event = NULL;
1839
1840 rc = pWnd->ProcessEvent(pEvent);
1841 if (RT_SUCCESS(rc))
1842 {
1843 /* Event was consumed and the proxy window till take care of the memory -- NULL it. */
1844 pEvent = NULL;
1845 }
1846 else
1847 LogRel(("DnD: Processing proxy window event %RU32 failed with %Rrc\n", pVbglR3Event->enmType, rc));
1848 }
1849 else if (rc == VERR_INTERRUPTED) /* Disconnected from service. */
1850 {
1851 LogRel(("DnD: Received quit message, shutting down ...\n"));
1852 pWnd->PostMessage(WM_QUIT, 0 /* wParm */, 0 /* lParm */);
1853 rc = VINF_SUCCESS;
1854 }
1855
1856 if (RT_FAILURE(rc))
1857 {
1858 if (pEvent)
1859 {
1860 VbglR3DnDEventFree(pEvent->pVbglR3Event);
1861
1862 RTMemFree(pEvent);
1863 pEvent = NULL;
1864 }
1865
1866 LogFlowFunc(("Processing next message failed with rc=%Rrc\n", rc));
1867
1868 /* Old(er) hosts either are broken regarding DnD support or otherwise
1869 * don't support the stuff we do on the guest side, so make sure we
1870 * don't process invalid messages forever. */
1871 if (cMsgSkippedInvalid++ > 32)
1872 {
1873 LogRel(("DnD: Too many invalid/skipped messages from host, exiting ...\n"));
1874 break;
1875 }
1876
1877 /* Make sure our proxy window is hidden when an error occured to
1878 * not block the guest's UI. */
1879 pWnd->Reset();
1880 }
1881
1882 if (*pfShutdown)
1883 break;
1884
1885 if (ASMAtomicReadBool(&pCtx->fShutdown))
1886 break;
1887
1888 if (RT_FAILURE(rc)) /* Don't hog the CPU on errors. */
1889 RTThreadSleep(1000 /* ms */);
1890 }
1891
1892 if (pEvent)
1893 {
1894 VbglR3DnDEventFree(pEvent->pVbglR3Event);
1895
1896 RTMemFree(pEvent);
1897 pEvent = NULL;
1898 }
1899
1900 VbglR3DnDDisconnect(&pCtx->cmdCtx);
1901
1902 LogRel(("DnD: Ended\n"));
1903
1904 LogFlowFuncLeaveRC(rc);
1905 return rc;
1906}
1907
1908/**
1909 * The service description.
1910 */
1911VBOXSERVICEDESC g_SvcDescDnD =
1912{
1913 /* pszName. */
1914 "draganddrop",
1915 /* pszDescription. */
1916 "Drag and Drop",
1917 /* methods */
1918 VBoxDnDInit,
1919 VBoxDnDWorker,
1920 VBoxDnDStop,
1921 VBoxDnDDestroy
1922};
1923
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