VirtualBox

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

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

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 58.1 KB
Line 
1/* $Id: VBoxDnD.cpp 76553 2019-01-01 01:45:53Z vboxsync $ */
2/** @file
3 * VBoxDnD.cpp - Windows-specific bits of the drag and drop service.
4 */
5
6/*
7 * Copyright (C) 2013-2019 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/ldr.h>
36#include <iprt/list.h>
37#include <iprt/mem.h>
38
39#include <iprt/cpp/mtlist.h>
40#include <iprt/cpp/ministring.h>
41
42#include <iprt/cpp/mtlist.h>
43
44#include <VBox/err.h>
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 * Aborts an in-flight DnD operation on the guest.
772 *
773 * @return VBox status code.
774 */
775int VBoxDnDWnd::Abort(void)
776{
777 LogFlowThisFunc(("mMode=%ld, mState=%RU32\n", mMode, mState));
778 LogRel(("DnD: Drag and drop operation aborted\n"));
779
780 int rc = RTCritSectEnter(&mCritSect);
781 if (RT_SUCCESS(rc))
782 {
783 if (startupInfo.pDataObject)
784 startupInfo.pDataObject->Abort();
785
786 RTCritSectLeave(&mCritSect);
787 }
788
789 /* Post ESC to our window to officially abort the
790 * drag and drop operation. */
791 this->PostMessage(WM_KEYDOWN, VK_ESCAPE /* wParam */, 0 /* lParam */);
792
793 Reset();
794
795 return rc;
796}
797
798/**
799 * Handles actions required when the host cursor enters
800 * the guest's screen to initiate a host -> guest DnD operation.
801 *
802 * @return IPRT status code.
803 * @param lstFormats Supported formats offered by the host.
804 * @param dndLstActionsAllowed Supported actions offered by the host.
805 */
806int VBoxDnDWnd::OnHgEnter(const RTCList<RTCString> &lstFormats, VBOXDNDACTIONLIST dndLstActionsAllowed)
807{
808 if (mMode == GH) /* Wrong mode? Bail out. */
809 return VERR_WRONG_ORDER;
810
811#ifdef DEBUG
812 LogFlowThisFunc(("dndActionList=0x%x, lstFormats=%zu: ", dndLstActionsAllowed, lstFormats.size()));
813 for (size_t i = 0; i < lstFormats.size(); i++)
814 LogFlow(("'%s' ", lstFormats.at(i).c_str()));
815 LogFlow(("\n"));
816#endif
817
818 Reset();
819 setMode(HG);
820
821 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
822 int rc = checkForSessionChange();
823 if (RT_FAILURE(rc))
824 return rc;
825
826 try
827 {
828 /* Save all allowed actions. */
829 this->dndLstActionsAllowed = dndLstActionsAllowed;
830
831 /*
832 * Check if reported formats from host are compatible with this client.
833 */
834 size_t cFormatsSup = this->lstFmtSup.size();
835 ULONG cFormatsActive = 0;
836
837 LPFORMATETC pFormatEtc = new FORMATETC[cFormatsSup];
838 RT_BZERO(pFormatEtc, sizeof(FORMATETC) * cFormatsSup);
839
840 LPSTGMEDIUM pStgMeds = new STGMEDIUM[cFormatsSup];
841 RT_BZERO(pStgMeds, sizeof(STGMEDIUM) * cFormatsSup);
842
843 LogRel2(("DnD: Reported formats:\n"));
844 for (size_t i = 0; i < lstFormats.size(); i++)
845 {
846 bool fSupported = false;
847 for (size_t a = 0; a < this->lstFmtSup.size(); a++)
848 {
849 const char *pszFormat = lstFormats.at(i).c_str();
850 LogFlowThisFunc(("\t\"%s\" <=> \"%s\"\n", this->lstFmtSup.at(a).c_str(), pszFormat));
851
852 fSupported = RTStrICmp(this->lstFmtSup.at(a).c_str(), pszFormat) == 0;
853 if (fSupported)
854 {
855 this->lstFmtActive.append(lstFormats.at(i));
856
857 /** @todo Put this into a \#define / struct. */
858 if (!RTStrICmp(pszFormat, "text/uri-list"))
859 {
860 pFormatEtc[cFormatsActive].cfFormat = CF_HDROP;
861 pFormatEtc[cFormatsActive].dwAspect = DVASPECT_CONTENT;
862 pFormatEtc[cFormatsActive].lindex = -1;
863 pFormatEtc[cFormatsActive].tymed = TYMED_HGLOBAL;
864
865 pStgMeds [cFormatsActive].tymed = TYMED_HGLOBAL;
866 cFormatsActive++;
867 }
868 else if ( !RTStrICmp(pszFormat, "text/plain")
869 || !RTStrICmp(pszFormat, "text/html")
870 || !RTStrICmp(pszFormat, "text/plain;charset=utf-8")
871 || !RTStrICmp(pszFormat, "text/plain;charset=utf-16")
872 || !RTStrICmp(pszFormat, "text/plain")
873 || !RTStrICmp(pszFormat, "text/richtext")
874 || !RTStrICmp(pszFormat, "UTF8_STRING")
875 || !RTStrICmp(pszFormat, "TEXT")
876 || !RTStrICmp(pszFormat, "STRING"))
877 {
878 pFormatEtc[cFormatsActive].cfFormat = CF_TEXT;
879 pFormatEtc[cFormatsActive].dwAspect = DVASPECT_CONTENT;
880 pFormatEtc[cFormatsActive].lindex = -1;
881 pFormatEtc[cFormatsActive].tymed = TYMED_HGLOBAL;
882
883 pStgMeds [cFormatsActive].tymed = TYMED_HGLOBAL;
884 cFormatsActive++;
885 }
886 else /* Should never happen. */
887 AssertReleaseMsgFailedBreak(("Format specification for '%s' not implemented\n", pszFormat));
888 break;
889 }
890 }
891
892 LogRel2(("DnD: \t%s: %RTbool\n", lstFormats.at(i).c_str(), fSupported));
893 }
894
895 /*
896 * Warn in the log if this guest does not accept anything.
897 */
898 Assert(cFormatsActive <= cFormatsSup);
899 if (cFormatsActive)
900 {
901 LogRel2(("DnD: %RU32 supported formats found:\n", cFormatsActive));
902 for (size_t i = 0; i < cFormatsActive; i++)
903 LogRel2(("DnD: \t%s\n", this->lstFmtActive.at(i).c_str()));
904 }
905 else
906 LogRel(("DnD: Warning: No supported drag and drop formats on the guest found!\n"));
907
908 /*
909 * Prepare the startup info for DoDragDrop().
910 */
911
912 /* Translate our drop actions into allowed Windows drop effects. */
913 startupInfo.dwOKEffects = DROPEFFECT_NONE;
914 if (dndLstActionsAllowed)
915 {
916 if (dndLstActionsAllowed & VBOX_DND_ACTION_COPY)
917 startupInfo.dwOKEffects |= DROPEFFECT_COPY;
918 if (dndLstActionsAllowed & VBOX_DND_ACTION_MOVE)
919 startupInfo.dwOKEffects |= DROPEFFECT_MOVE;
920 if (dndLstActionsAllowed & VBOX_DND_ACTION_LINK)
921 startupInfo.dwOKEffects |= DROPEFFECT_LINK;
922 }
923
924 LogRel2(("DnD: Supported drop actions: 0x%x\n", startupInfo.dwOKEffects));
925
926 startupInfo.pDropSource = new VBoxDnDDropSource(this);
927 startupInfo.pDataObject = new VBoxDnDDataObject(pFormatEtc, pStgMeds, cFormatsActive);
928
929 if (pFormatEtc)
930 delete pFormatEtc;
931 if (pStgMeds)
932 delete pStgMeds;
933 }
934 catch (std::bad_alloc)
935 {
936 rc = VERR_NO_MEMORY;
937 }
938
939 if (RT_SUCCESS(rc))
940 rc = makeFullscreen();
941
942 LogFlowFuncLeaveRC(rc);
943 return rc;
944}
945
946/**
947 * Handles actions required when the host cursor moves inside
948 * the guest's screen.
949 *
950 * @return IPRT status code.
951 * @param u32xPos Absolute X position (in pixels) of the host cursor
952 * inside the guest.
953 * @param u32yPos Absolute Y position (in pixels) of the host cursor
954 * inside the guest.
955 * @param dndAction Action the host wants to perform while moving.
956 * Currently ignored.
957 */
958int VBoxDnDWnd::OnHgMove(uint32_t u32xPos, uint32_t u32yPos, VBOXDNDACTION dndAction)
959{
960 RT_NOREF(dndAction);
961 int rc;
962
963 uint32_t uActionNotify = VBOX_DND_ACTION_IGNORE;
964 if (mMode == HG)
965 {
966 LogFlowThisFunc(("u32xPos=%RU32, u32yPos=%RU32, dndAction=0x%x\n",
967 u32xPos, u32yPos, dndAction));
968
969 rc = mouseMove(u32xPos, u32yPos, MOUSEEVENTF_LEFTDOWN);
970
971 if (RT_SUCCESS(rc))
972 rc = RTCritSectEnter(&mCritSect);
973 if (RT_SUCCESS(rc))
974 {
975 if ( (Dragging == mState)
976 && startupInfo.pDropSource)
977 uActionNotify = startupInfo.pDropSource->GetCurrentAction();
978
979 RTCritSectLeave(&mCritSect);
980 }
981 }
982 else /* Just acknowledge the operation with an ignore action. */
983 rc = VINF_SUCCESS;
984
985 if (RT_SUCCESS(rc))
986 {
987 rc = VbglR3DnDHGSendAckOp(&mDnDCtx, uActionNotify);
988 if (RT_FAILURE(rc))
989 LogFlowThisFunc(("Acknowledging operation failed with rc=%Rrc\n", rc));
990 }
991
992 LogFlowThisFunc(("Returning uActionNotify=0x%x, rc=%Rrc\n", uActionNotify, rc));
993 return rc;
994}
995
996/**
997 * Handles actions required when the host cursor leaves
998 * the guest's screen again.
999 *
1000 * @return IPRT status code.
1001 */
1002int VBoxDnDWnd::OnHgLeave(void)
1003{
1004 if (mMode == GH) /* Wrong mode? Bail out. */
1005 return VERR_WRONG_ORDER;
1006
1007 int rc = Abort();
1008
1009 LogFlowFuncLeaveRC(rc);
1010 return rc;
1011}
1012
1013/**
1014 * Handles actions required when the host cursor wants to drop
1015 * and therefore start a "drop" action in the guest.
1016 *
1017 * @return IPRT status code.
1018 */
1019int VBoxDnDWnd::OnHgDrop(void)
1020{
1021 if (mMode == GH)
1022 return VERR_WRONG_ORDER;
1023
1024 LogFlowThisFunc(("mMode=%ld, mState=%RU32\n", mMode, mState));
1025
1026 int rc = VINF_SUCCESS;
1027 if (mState == Dragging)
1028 {
1029 if (lstFmtActive.size() >= 1)
1030 {
1031 /** @todo What to do when multiple formats are available? */
1032 mFormatRequested = lstFmtActive.at(0);
1033
1034 rc = RTCritSectEnter(&mCritSect);
1035 if (RT_SUCCESS(rc))
1036 {
1037 if (startupInfo.pDataObject)
1038 startupInfo.pDataObject->SetStatus(VBoxDnDDataObject::Dropping);
1039 else
1040 rc = VERR_NOT_FOUND;
1041
1042 RTCritSectLeave(&mCritSect);
1043 }
1044
1045 if (RT_SUCCESS(rc))
1046 {
1047 LogRel(("DnD: Requesting data as '%s' ...\n", mFormatRequested.c_str()));
1048 rc = VbglR3DnDHGSendReqData(&mDnDCtx, mFormatRequested.c_str());
1049 if (RT_FAILURE(rc))
1050 LogFlowThisFunc(("Requesting data failed with rc=%Rrc\n", rc));
1051 }
1052
1053 }
1054 else /* Should never happen. */
1055 LogRel(("DnD: Error: Host did not specify a data format for drop data\n"));
1056 }
1057
1058 LogFlowFuncLeaveRC(rc);
1059 return rc;
1060}
1061
1062/**
1063 * Handles actions required when the host has sent over DnD data
1064 * to the guest after a "drop" event.
1065 *
1066 * @return IPRT status code.
1067 * @param pMeta Pointer to meta data received.
1068 */
1069int VBoxDnDWnd::OnHgDataReceive(PVBGLR3GUESTDNDMETADATA pMeta)
1070{
1071 LogFlowThisFunc(("mState=%ld, enmMetaType=%RU32, cbMeta=%RU32\n", mState, pMeta->enmType, pMeta->cbMeta));
1072
1073 mState = Dropped;
1074
1075 int rc = VINF_SUCCESS;
1076 if (pMeta->pvMeta)
1077 {
1078 Assert(pMeta->cbMeta);
1079 rc = RTCritSectEnter(&mCritSect);
1080 if (RT_SUCCESS(rc))
1081 {
1082 if (startupInfo.pDataObject)
1083 rc = startupInfo.pDataObject->Signal(mFormatRequested, pMeta->pvMeta, pMeta->cbMeta);
1084 else
1085 rc = VERR_NOT_FOUND;
1086
1087 RTCritSectLeave(&mCritSect);
1088 }
1089 }
1090
1091 int rc2 = mouseRelease();
1092 if (RT_SUCCESS(rc))
1093 rc = rc2;
1094
1095 LogFlowFuncLeaveRC(rc);
1096 return rc;
1097}
1098
1099/**
1100 * Handles actions required when the host wants to cancel the current
1101 * host -> guest operation.
1102 *
1103 * @return IPRT status code.
1104 */
1105int VBoxDnDWnd::OnHgCancel(void)
1106{
1107 return Abort();
1108}
1109
1110#ifdef VBOX_WITH_DRAG_AND_DROP_GH
1111/**
1112 * Handles actions required to start a guest -> host DnD operation.
1113 * This works by letting the host ask whether a DnD operation is pending
1114 * on the guest. The guest must not know anything about the host's DnD state
1115 * and/or operations due to security reasons.
1116 *
1117 * To capture a pending DnD operation on the guest which then can be communicated
1118 * to the host the proxy window needs to be registered as a drop target. This drop
1119 * target then will act as a proxy target between the guest OS and the host. In other
1120 * words, the guest OS will use this proxy target as a regular (invisible) window
1121 * which can be used by the regular guest OS' DnD mechanisms, independently of the
1122 * host OS. To make sure this proxy target is able receive an in-progress DnD operation
1123 * on the guest, it will be shown invisibly across all active guest OS screens. Just
1124 * think of an opened umbrella across all screens here.
1125 *
1126 * As soon as the proxy target and its underlying data object receive appropriate
1127 * DnD messages they'll be hidden again, and the control will be transferred back
1128 * this class again.
1129 *
1130 * @return IPRT status code.
1131 */
1132int VBoxDnDWnd::OnGhIsDnDPending(void)
1133{
1134 LogFlowThisFunc(("mMode=%ld, mState=%ld\n", mMode, mState));
1135
1136 if (mMode == Unknown)
1137 setMode(GH);
1138
1139 if (mMode != GH)
1140 return VERR_WRONG_ORDER;
1141
1142 if (mState == Uninitialized)
1143 {
1144 /* Nothing to do here yet. */
1145 mState = Initialized;
1146 }
1147
1148 int rc;
1149 if (mState == Initialized)
1150 {
1151 /* Check if the VM session has changed and reconnect to the HGCM service if necessary. */
1152 rc = checkForSessionChange();
1153 if (RT_SUCCESS(rc))
1154 {
1155 rc = makeFullscreen();
1156 if (RT_SUCCESS(rc))
1157 {
1158 /*
1159 * We have to release the left mouse button to
1160 * get into our (invisible) proxy window.
1161 */
1162 mouseRelease();
1163
1164 /*
1165 * Even if we just released the left mouse button
1166 * we're still in the dragging state to handle our
1167 * own drop target (for the host).
1168 */
1169 mState = Dragging;
1170 }
1171 }
1172 }
1173 else
1174 rc = VINF_SUCCESS;
1175
1176 /**
1177 * Some notes regarding guest cursor movement:
1178 * - The host only sends an HOST_DND_GH_REQ_PENDING message to the guest
1179 * if the mouse cursor is outside the VM's window.
1180 * - The guest does not know anything about the host's cursor
1181 * position / state due to security reasons.
1182 * - The guest *only* knows that the host currently is asking whether a
1183 * guest DnD operation is in progress.
1184 */
1185
1186 if ( RT_SUCCESS(rc)
1187 && mState == Dragging)
1188 {
1189 /** @todo Put this block into a function! */
1190 POINT p;
1191 GetCursorPos(&p);
1192 ClientToScreen(hWnd, &p);
1193#ifdef DEBUG_andy
1194 LogFlowThisFunc(("Client to screen curX=%ld, curY=%ld\n", p.x, p.y));
1195#endif
1196
1197 /** @todo Multi-monitor setups? */
1198#if 0 /* unused */
1199 int iScreenX = GetSystemMetrics(SM_CXSCREEN) - 1;
1200 int iScreenY = GetSystemMetrics(SM_CYSCREEN) - 1;
1201#endif
1202
1203 LONG px = p.x;
1204 if (px <= 0)
1205 px = 1;
1206 LONG py = p.y;
1207 if (py <= 0)
1208 py = 1;
1209
1210 rc = mouseMove(px, py, 0 /* dwMouseInputFlags */);
1211 }
1212
1213 if (RT_SUCCESS(rc))
1214 {
1215 VBOXDNDACTION dndActionDefault = VBOX_DND_ACTION_IGNORE;
1216
1217 AssertPtr(pDropTarget);
1218 RTCString strFormats = pDropTarget->Formats();
1219 if (!strFormats.isEmpty())
1220 {
1221 dndActionDefault = VBOX_DND_ACTION_COPY;
1222
1223 LogFlowFunc(("Acknowledging pDropTarget=0x%p, dndActionDefault=0x%x, dndLstActionsAllowed=0x%x, strFormats=%s\n",
1224 pDropTarget, dndActionDefault, dndLstActionsAllowed, strFormats.c_str()));
1225 }
1226 else
1227 {
1228 strFormats = "unknown"; /* Prevent VERR_IO_GEN_FAILURE for IOCTL. */
1229 LogFlowFunc(("No format data from proxy window available yet\n"));
1230 }
1231
1232 /** @todo Support more than one action at a time. */
1233 dndLstActionsAllowed = dndActionDefault;
1234
1235 int rc2 = VbglR3DnDGHSendAckPending(&mDnDCtx,
1236 dndActionDefault, dndLstActionsAllowed,
1237 strFormats.c_str(), (uint32_t)strFormats.length() + 1 /* Include termination */);
1238 if (RT_FAILURE(rc2))
1239 {
1240 char szMsg[256]; /* Sizes according to MSDN. */
1241 char szTitle[64];
1242
1243 /** @todo Add some i18l tr() macros here. */
1244 RTStrPrintf(szTitle, sizeof(szTitle), "VirtualBox Guest Additions Drag and Drop");
1245 RTStrPrintf(szMsg, sizeof(szMsg), "Drag and drop to the host either is not supported or disabled. "
1246 "Please enable Guest to Host or Bidirectional drag and drop mode "
1247 "or re-install the VirtualBox Guest Additions.");
1248 switch (rc2)
1249 {
1250 case VERR_ACCESS_DENIED:
1251 {
1252 rc = hlpShowBalloonTip(g_hInstance, g_hwndToolWindow, ID_TRAYICON,
1253 szMsg, szTitle,
1254 15 * 1000 /* Time to display in msec */, NIIF_INFO);
1255 AssertRC(rc);
1256 break;
1257 }
1258
1259 default:
1260 break;
1261 }
1262
1263 LogRel2(("DnD: Host refuses drag and drop operation from guest: %Rrc\n", rc2));
1264 Reset();
1265 }
1266 }
1267
1268 if (RT_FAILURE(rc))
1269 Reset(); /* Reset state on failure. */
1270
1271 LogFlowFuncLeaveRC(rc);
1272 return rc;
1273}
1274
1275/**
1276 * Handles actions required to let the guest know that the host
1277 * started a "drop" action on the host. This will tell the guest
1278 * to send data in a specific format the host requested.
1279 *
1280 * @return IPRT status code.
1281 * @param pszFormat Format the host requests the data in.
1282 * @param cbFormat Size (in bytes) of format string.
1283 * @param dndActionDefault Default action on the host.
1284 */
1285int VBoxDnDWnd::OnGhDrop(const RTCString &strFormat, uint32_t dndActionDefault)
1286{
1287 RT_NOREF(dndActionDefault);
1288
1289 LogFlowThisFunc(("mMode=%ld, mState=%ld, pDropTarget=0x%p, strFormat=%s, dndActionDefault=0x%x\n",
1290 mMode, mState, pDropTarget, strFormat.c_str(), dndActionDefault));
1291 int rc;
1292 if (mMode == GH)
1293 {
1294 if (mState == Dragging)
1295 {
1296 AssertPtr(pDropTarget);
1297 rc = pDropTarget->WaitForDrop(5 * 1000 /* 5s timeout */);
1298
1299 Reset();
1300 }
1301 else if (mState == Dropped)
1302 {
1303 rc = VINF_SUCCESS;
1304 }
1305 else
1306 rc = VERR_WRONG_ORDER;
1307
1308 if (RT_SUCCESS(rc))
1309 {
1310 /** @todo Respect uDefAction. */
1311 void *pvData = pDropTarget->DataMutableRaw();
1312 uint32_t cbData = (uint32_t)pDropTarget->DataSize();
1313 Assert(cbData == pDropTarget->DataSize());
1314
1315 if ( pvData
1316 && cbData)
1317 {
1318 rc = VbglR3DnDGHSendData(&mDnDCtx, strFormat.c_str(), pvData, cbData);
1319 LogFlowFunc(("Sent pvData=0x%p, cbData=%RU32, rc=%Rrc\n", pvData, cbData, rc));
1320 }
1321 else
1322 rc = VERR_NO_DATA;
1323 }
1324 }
1325 else
1326 rc = VERR_WRONG_ORDER;
1327
1328 if (RT_FAILURE(rc))
1329 {
1330 /*
1331 * If an error occurred or the guest is in a wrong DnD mode,
1332 * send an error to the host in any case so that the host does
1333 * not wait for the data it expects from the guest.
1334 */
1335 int rc2 = VbglR3DnDGHSendError(&mDnDCtx, rc);
1336 AssertRC(rc2);
1337 }
1338
1339 LogFlowFuncLeaveRC(rc);
1340 return rc;
1341}
1342#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
1343
1344void VBoxDnDWnd::PostMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
1345{
1346 LogFlowFunc(("Posting message %u\n"));
1347 BOOL fRc = ::PostMessage(hWnd, uMsg, wParam, lParam);
1348 Assert(fRc); NOREF(fRc);
1349}
1350
1351/**
1352 * Injects a DnD event in this proxy window's Windows
1353 * event queue. The (allocated) event will be deleted by
1354 * this class after processing.
1355 *
1356 * @return IPRT status code.
1357 * @param pEvent Event to inject.
1358 */
1359int VBoxDnDWnd::ProcessEvent(PVBOXDNDEVENT pEvent)
1360{
1361 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1362
1363 BOOL fRc = ::PostMessage(hWnd, WM_VBOXTRAY_DND_MESSAGE,
1364 0 /* wParm */, (LPARAM)pEvent /* lParm */);
1365 if (!fRc)
1366 {
1367 DWORD dwErr = GetLastError();
1368
1369 static int s_iBitchedAboutFailedDnDMessages = 0;
1370 if (s_iBitchedAboutFailedDnDMessages++ < 32)
1371 {
1372 LogRel(("DnD: Processing event %p failed with %ld (%Rrc), skipping\n",
1373 pEvent, dwErr, RTErrConvertFromWin32(dwErr)));
1374 }
1375
1376 VbglR3DnDEventFree(pEvent->pVbglR3Event);
1377
1378 RTMemFree(pEvent);
1379 pEvent = NULL;
1380
1381 return RTErrConvertFromWin32(dwErr);
1382 }
1383
1384 return VINF_SUCCESS;
1385}
1386
1387/**
1388 * Checks if the VM session has changed (can happen when restoring the VM from a saved state)
1389 * and do a reconnect to the DnD HGCM service.
1390 *
1391 * @returns IPRT status code.
1392 */
1393int VBoxDnDWnd::checkForSessionChange(void)
1394{
1395 uint64_t uSessionID;
1396 int rc = VbglR3GetSessionId(&uSessionID);
1397 if ( RT_SUCCESS(rc)
1398 && uSessionID != mDnDCtx.uSessionID)
1399 {
1400 LogFlowThisFunc(("VM session has changed to %RU64\n", uSessionID));
1401
1402 rc = VbglR3DnDDisconnect(&mDnDCtx);
1403 AssertRC(rc);
1404
1405 rc = VbglR3DnDConnect(&mDnDCtx);
1406 AssertRC(rc);
1407 }
1408
1409 LogFlowFuncLeaveRC(rc);
1410 return rc;
1411}
1412
1413/**
1414 * Hides the proxy window again.
1415 *
1416 * @return IPRT status code.
1417 */
1418int VBoxDnDWnd::Hide(void)
1419{
1420#ifdef DEBUG_andy
1421 LogFlowFunc(("\n"));
1422#endif
1423 ShowWindow(hWnd, SW_HIDE);
1424
1425 return VINF_SUCCESS;
1426}
1427
1428/**
1429 * Shows the (invisible) proxy window in fullscreen,
1430 * spawned across all active guest monitors.
1431 *
1432 * @return IPRT status code.
1433 */
1434int VBoxDnDWnd::makeFullscreen(void)
1435{
1436 int rc = VINF_SUCCESS;
1437
1438 RECT r;
1439 RT_ZERO(r);
1440
1441 BOOL fRc;
1442 HDC hDC = GetDC(NULL /* Entire screen */);
1443 if (hDC)
1444 {
1445 fRc = g_pfnEnumDisplayMonitors
1446 /* EnumDisplayMonitors is not available on NT4. */
1447 ? g_pfnEnumDisplayMonitors(hDC, NULL, VBoxDnDWnd::MonitorEnumProc, (LPARAM)&r):
1448 FALSE;
1449
1450 if (!fRc)
1451 rc = VERR_NOT_FOUND;
1452 ReleaseDC(NULL, hDC);
1453 }
1454 else
1455 rc = VERR_ACCESS_DENIED;
1456
1457 if (RT_FAILURE(rc))
1458 {
1459 /* If multi-monitor enumeration failed above, try getting at least the
1460 * primary monitor as a fallback. */
1461 r.left = 0;
1462 r.top = 0;
1463 r.right = GetSystemMetrics(SM_CXSCREEN);
1464 r.bottom = GetSystemMetrics(SM_CYSCREEN);
1465 rc = VINF_SUCCESS;
1466 }
1467
1468 if (RT_SUCCESS(rc))
1469 {
1470 LONG lStyle = GetWindowLong(hWnd, GWL_STYLE);
1471 SetWindowLong(hWnd, GWL_STYLE,
1472 lStyle & ~(WS_CAPTION | WS_THICKFRAME));
1473 LONG lExStyle = GetWindowLong(hWnd, GWL_EXSTYLE);
1474 SetWindowLong(hWnd, GWL_EXSTYLE,
1475 lExStyle & ~( WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE
1476 | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
1477
1478 fRc = SetWindowPos(hWnd, HWND_TOPMOST,
1479 r.left,
1480 r.top,
1481 r.right - r.left,
1482 r.bottom - r.top,
1483#ifdef VBOX_DND_DEBUG_WND
1484 SWP_SHOWWINDOW | SWP_FRAMECHANGED);
1485#else
1486 SWP_SHOWWINDOW | SWP_NOOWNERZORDER | SWP_NOREDRAW | SWP_NOACTIVATE);
1487#endif
1488 if (fRc)
1489 {
1490 LogFlowFunc(("Virtual screen is %ld,%ld,%ld,%ld (%ld x %ld)\n",
1491 r.left, r.top, r.right, r.bottom,
1492 r.right - r.left, r.bottom - r.top));
1493 }
1494 else
1495 {
1496 DWORD dwErr = GetLastError();
1497 LogRel(("DnD: Failed to set proxy window position, rc=%Rrc\n",
1498 RTErrConvertFromWin32(dwErr)));
1499 }
1500 }
1501 else
1502 LogRel(("DnD: Failed to determine virtual screen size, rc=%Rrc\n", rc));
1503
1504 LogFlowFuncLeaveRC(rc);
1505 return rc;
1506}
1507
1508/**
1509 * Moves the guest mouse cursor to a specific position.
1510 *
1511 * @return IPRT status code.
1512 * @param x X position (in pixels) to move cursor to.
1513 * @param y Y position (in pixels) to move cursor to.
1514 * @param dwMouseInputFlags Additional movement flags. @sa MOUSEEVENTF_ flags.
1515 */
1516int VBoxDnDWnd::mouseMove(int x, int y, DWORD dwMouseInputFlags)
1517{
1518 int iScreenX = GetSystemMetrics(SM_CXSCREEN) - 1;
1519 int iScreenY = GetSystemMetrics(SM_CYSCREEN) - 1;
1520
1521 INPUT Input[1] = { 0 };
1522 Input[0].type = INPUT_MOUSE;
1523 Input[0].mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE
1524 | dwMouseInputFlags;
1525 Input[0].mi.dx = x * (65535 / iScreenX);
1526 Input[0].mi.dy = y * (65535 / iScreenY);
1527
1528 int rc;
1529 if (g_pfnSendInput(1 /* Number of inputs */,
1530 Input, sizeof(INPUT)))
1531 {
1532#ifdef DEBUG_andy
1533 CURSORINFO ci;
1534 RT_ZERO(ci);
1535 ci.cbSize = sizeof(ci);
1536 BOOL fRc = GetCursorInfo(&ci);
1537 if (fRc)
1538 LogFlowThisFunc(("Cursor shown=%RTbool, cursor=0x%p, x=%d, y=%d\n",
1539 (ci.flags & CURSOR_SHOWING) ? true : false,
1540 ci.hCursor, ci.ptScreenPos.x, ci.ptScreenPos.y));
1541#endif
1542 rc = VINF_SUCCESS;
1543 }
1544 else
1545 {
1546 DWORD dwErr = GetLastError();
1547 rc = RTErrConvertFromWin32(dwErr);
1548 LogFlowFunc(("SendInput failed with rc=%Rrc\n", rc));
1549 }
1550
1551 return rc;
1552}
1553
1554/**
1555 * Releases a previously pressed left guest mouse button.
1556 *
1557 * @return IPRT status code.
1558 */
1559int VBoxDnDWnd::mouseRelease(void)
1560{
1561 LogFlowFuncEnter();
1562
1563 int rc;
1564
1565 /* Release mouse button in the guest to start the "drop"
1566 * action at the current mouse cursor position. */
1567 INPUT Input[1] = { 0 };
1568 Input[0].type = INPUT_MOUSE;
1569 Input[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;
1570 if (!g_pfnSendInput(1, Input, sizeof(INPUT)))
1571 {
1572 DWORD dwErr = GetLastError();
1573 rc = RTErrConvertFromWin32(dwErr);
1574 LogFlowFunc(("SendInput failed with rc=%Rrc\n", rc));
1575 }
1576 else
1577 rc = VINF_SUCCESS;
1578
1579 return rc;
1580}
1581
1582/**
1583 * Resets the proxy window.
1584 */
1585void VBoxDnDWnd::Reset(void)
1586{
1587 LogFlowThisFunc(("Resetting, old mMode=%ld, mState=%ld\n",
1588 mMode, mState));
1589
1590 /*
1591 * Note: Don't clear this->lstAllowedFormats at the moment, as this value is initialized
1592 * on class creation. We might later want to modify the allowed formats at runtime,
1593 * so keep this in mind when implementing this.
1594 */
1595
1596 this->lstFmtActive.clear();
1597 this->dndLstActionsAllowed = VBOX_DND_ACTION_IGNORE;
1598
1599 int rc2 = setMode(Unknown);
1600 AssertRC(rc2);
1601
1602 Hide();
1603}
1604
1605/**
1606 * Sets the current operation mode of this proxy window.
1607 *
1608 * @return IPRT status code.
1609 * @param enmMode New mode to set.
1610 */
1611int VBoxDnDWnd::setMode(Mode enmMode)
1612{
1613 LogFlowThisFunc(("Old mode=%ld, new mode=%ld\n",
1614 mMode, enmMode));
1615
1616 mMode = enmMode;
1617 mState = Initialized;
1618
1619 return VINF_SUCCESS;
1620}
1621
1622/**
1623 * Static helper function for having an own WndProc for proxy
1624 * window instances.
1625 */
1626static LRESULT CALLBACK vboxDnDWndProcInstance(HWND hWnd, UINT uMsg,
1627 WPARAM wParam, LPARAM lParam)
1628{
1629 LONG_PTR pUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);
1630 AssertPtrReturn(pUserData, 0);
1631
1632 VBoxDnDWnd *pWnd = reinterpret_cast<VBoxDnDWnd *>(pUserData);
1633 if (pWnd)
1634 return pWnd->WndProc(hWnd, uMsg, wParam, lParam);
1635
1636 return 0;
1637}
1638
1639/**
1640 * Static helper function for routing Windows messages to a specific
1641 * proxy window instance.
1642 */
1643static LRESULT CALLBACK vboxDnDWndProc(HWND hWnd, UINT uMsg,
1644 WPARAM wParam, LPARAM lParam)
1645{
1646 /* Note: WM_NCCREATE is not the first ever message which arrives, but
1647 * early enough for us. */
1648 if (uMsg == WM_NCCREATE)
1649 {
1650 LPCREATESTRUCT pCS = (LPCREATESTRUCT)lParam;
1651 AssertPtr(pCS);
1652 SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pCS->lpCreateParams);
1653 SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)vboxDnDWndProcInstance);
1654
1655 return vboxDnDWndProcInstance(hWnd, uMsg, wParam, lParam);
1656 }
1657
1658 /* No window associated yet. */
1659 return DefWindowProc(hWnd, uMsg, wParam, lParam);
1660}
1661
1662/**
1663 * Initializes drag and drop.
1664 *
1665 * @return IPRT status code.
1666 * @param pEnv The DnD service's environment.
1667 * @param ppInstance The instance pointer which refer to this object.
1668 */
1669DECLCALLBACK(int) VBoxDnDInit(const PVBOXSERVICEENV pEnv, void **ppInstance)
1670{
1671 AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
1672 AssertPtrReturn(ppInstance, VERR_INVALID_POINTER);
1673
1674 LogFlowFuncEnter();
1675
1676 PVBOXDNDCONTEXT pCtx = &g_Ctx; /* Only one instance at the moment. */
1677 AssertPtr(pCtx);
1678
1679 int rc;
1680 bool fSupportedOS = true;
1681
1682 if (VbglR3AutoLogonIsRemoteSession())
1683 {
1684 /* Do not do drag and drop for remote sessions. */
1685 LogRel(("DnD: Drag and drop has been disabled for a remote session\n"));
1686 rc = VERR_NOT_SUPPORTED;
1687 }
1688 else
1689 rc = VINF_SUCCESS;
1690
1691 if (RT_SUCCESS(rc))
1692 {
1693 g_pfnSendInput = (PFNSENDINPUT)
1694 RTLdrGetSystemSymbol("User32.dll", "SendInput");
1695 fSupportedOS = !RT_BOOL(g_pfnSendInput == NULL);
1696 g_pfnEnumDisplayMonitors = (PFNENUMDISPLAYMONITORS)
1697 RTLdrGetSystemSymbol("User32.dll", "EnumDisplayMonitors");
1698 /* g_pfnEnumDisplayMonitors is optional. */
1699
1700 if (!fSupportedOS)
1701 {
1702 LogRel(("DnD: Not supported Windows version, disabling drag and drop support\n"));
1703 rc = VERR_NOT_SUPPORTED;
1704 }
1705 }
1706
1707 if (RT_SUCCESS(rc))
1708 {
1709 /* Assign service environment to our context. */
1710 pCtx->pEnv = pEnv;
1711
1712 /* Create the proxy window. At the moment we
1713 * only support one window at a time. */
1714 VBoxDnDWnd *pWnd = NULL;
1715 try
1716 {
1717 pWnd = new VBoxDnDWnd();
1718 rc = pWnd->Initialize(pCtx);
1719
1720 /* Add proxy window to our proxy windows list. */
1721 if (RT_SUCCESS(rc))
1722 pCtx->lstWnd.append(pWnd);
1723 }
1724 catch (std::bad_alloc)
1725 {
1726 rc = VERR_NO_MEMORY;
1727 }
1728 }
1729
1730 if (RT_SUCCESS(rc))
1731 rc = RTSemEventCreate(&pCtx->hEvtQueueSem);
1732 if (RT_SUCCESS(rc))
1733 {
1734 *ppInstance = pCtx;
1735
1736 LogRel(("DnD: Drag and drop service successfully started\n"));
1737 }
1738 else
1739 LogRel(("DnD: Initializing drag and drop service failed with rc=%Rrc\n", rc));
1740
1741 LogFlowFuncLeaveRC(rc);
1742 return rc;
1743}
1744
1745DECLCALLBACK(int) VBoxDnDStop(void *pInstance)
1746{
1747 AssertPtrReturn(pInstance, VERR_INVALID_POINTER);
1748
1749 LogFunc(("Stopping pInstance=%p\n", pInstance));
1750
1751 PVBOXDNDCONTEXT pCtx = (PVBOXDNDCONTEXT)pInstance;
1752 AssertPtr(pCtx);
1753
1754 /* Set shutdown indicator. */
1755 ASMAtomicWriteBool(&pCtx->fShutdown, true);
1756
1757 /* Disconnect. */
1758 VbglR3DnDDisconnect(&pCtx->cmdCtx);
1759
1760 LogFlowFuncLeaveRC(VINF_SUCCESS);
1761 return VINF_SUCCESS;
1762}
1763
1764DECLCALLBACK(void) VBoxDnDDestroy(void *pInstance)
1765{
1766 AssertPtrReturnVoid(pInstance);
1767
1768 LogFunc(("Destroying pInstance=%p\n", pInstance));
1769
1770 PVBOXDNDCONTEXT pCtx = (PVBOXDNDCONTEXT)pInstance;
1771 AssertPtr(pCtx);
1772
1773 /** @todo At the moment we only have one DnD proxy window. */
1774 Assert(pCtx->lstWnd.size() == 1);
1775 VBoxDnDWnd *pWnd = pCtx->lstWnd.first();
1776 if (pWnd)
1777 {
1778 delete pWnd;
1779 pWnd = NULL;
1780 }
1781
1782 if (pCtx->hEvtQueueSem != NIL_RTSEMEVENT)
1783 {
1784 RTSemEventDestroy(pCtx->hEvtQueueSem);
1785 pCtx->hEvtQueueSem = NIL_RTSEMEVENT;
1786 }
1787
1788 LogFunc(("Destroyed pInstance=%p\n", pInstance));
1789}
1790
1791DECLCALLBACK(int) VBoxDnDWorker(void *pInstance, bool volatile *pfShutdown)
1792{
1793 AssertPtr(pInstance);
1794 AssertPtr(pfShutdown);
1795
1796 LogFlowFunc(("pInstance=%p\n", pInstance));
1797
1798 /*
1799 * Tell the control thread that it can continue
1800 * spawning services.
1801 */
1802 RTThreadUserSignal(RTThreadSelf());
1803
1804 PVBOXDNDCONTEXT pCtx = (PVBOXDNDCONTEXT)pInstance;
1805 AssertPtr(pCtx);
1806
1807 int rc = VbglR3DnDConnect(&pCtx->cmdCtx);
1808 if (RT_FAILURE(rc))
1809 return rc;
1810
1811 /** @todo At the moment we only have one DnD proxy window. */
1812 Assert(pCtx->lstWnd.size() == 1);
1813 VBoxDnDWnd *pWnd = pCtx->lstWnd.first();
1814 AssertPtr(pWnd);
1815
1816 /* Number of invalid messages skipped in a row. */
1817 int cMsgSkippedInvalid = 0;
1818 PVBOXDNDEVENT pEvent = NULL;
1819
1820 for (;;)
1821 {
1822 pEvent = (PVBOXDNDEVENT)RTMemAllocZ(sizeof(VBOXDNDEVENT));
1823 if (!pEvent)
1824 {
1825 rc = VERR_NO_MEMORY;
1826 break;
1827 }
1828 /* Note: pEvent will be free'd by the consumer later. */
1829
1830 PVBGLR3DNDEVENT pVbglR3Event = NULL;
1831 rc = VbglR3DnDEventGetNext(&pCtx->cmdCtx, &pVbglR3Event);
1832 if (RT_SUCCESS(rc))
1833 {
1834 LogFunc(("enmType=%RU32, rc=%Rrc\n", pVbglR3Event->enmType, rc));
1835
1836 cMsgSkippedInvalid = 0; /* Reset skipped messages count. */
1837
1838 LogRel2(("DnD: Received new event, type=%RU32, rc=%Rrc\n", pVbglR3Event->enmType, rc));
1839
1840 /* pEvent now owns pVbglR3Event. */
1841 pEvent->pVbglR3Event = pVbglR3Event;
1842 pVbglR3Event = NULL;
1843
1844 rc = pWnd->ProcessEvent(pEvent);
1845 if (RT_SUCCESS(rc))
1846 {
1847 /* Event was consumed and the proxy window till take care of the memory -- NULL it. */
1848 pEvent = NULL;
1849 }
1850 else
1851 LogRel(("DnD: Processing proxy window event %RU32 failed with %Rrc\n", pVbglR3Event->enmType, rc));
1852 }
1853 else if (rc == VERR_INTERRUPTED) /* Disconnected from service. */
1854 {
1855 LogRel(("DnD: Received quit message, shutting down ...\n"));
1856 pWnd->PostMessage(WM_QUIT, 0 /* wParm */, 0 /* lParm */);
1857 rc = VINF_SUCCESS;
1858 }
1859
1860 if (RT_FAILURE(rc))
1861 {
1862 if (pEvent)
1863 {
1864 RTMemFree(pEvent);
1865 pEvent = NULL;
1866 }
1867
1868 LogFlowFunc(("Processing next message failed with rc=%Rrc\n", rc));
1869
1870 /* Old(er) hosts either are broken regarding DnD support or otherwise
1871 * don't support the stuff we do on the guest side, so make sure we
1872 * don't process invalid messages forever. */
1873 if (cMsgSkippedInvalid++ > 32)
1874 {
1875 LogRel(("DnD: Too many invalid/skipped messages from host, exiting ...\n"));
1876 break;
1877 }
1878
1879 /* Make sure our proxy window is hidden when an error occured to
1880 * not block the guest's UI. */
1881 int rc2 = pWnd->Abort();
1882 AssertRC(rc2);
1883 }
1884
1885 if (*pfShutdown)
1886 break;
1887
1888 if (ASMAtomicReadBool(&pCtx->fShutdown))
1889 break;
1890
1891 if (RT_FAILURE(rc)) /* Don't hog the CPU on errors. */
1892 RTThreadSleep(1000 /* ms */);
1893 }
1894
1895 if (pEvent)
1896 {
1897 VbglR3DnDEventFree(pEvent->pVbglR3Event);
1898
1899 RTMemFree(pEvent);
1900 pEvent = NULL;
1901 }
1902
1903 VbglR3DnDDisconnect(&pCtx->cmdCtx);
1904
1905 LogRel(("DnD: Ended\n"));
1906
1907 LogFlowFuncLeaveRC(rc);
1908 return rc;
1909}
1910
1911/**
1912 * The service description.
1913 */
1914VBOXSERVICEDESC g_SvcDescDnD =
1915{
1916 /* pszName. */
1917 "draganddrop",
1918 /* pszDescription. */
1919 "Drag and Drop",
1920 /* methods */
1921 VBoxDnDInit,
1922 VBoxDnDWorker,
1923 VBoxDnDStop,
1924 VBoxDnDDestroy
1925};
1926
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