VirtualBox

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

Last change on this file since 106501 was 106501, checked in by vboxsync, 3 months ago

Add/NT/VBoxTray: Probably missing a break after PostQuitMessage. jiraref:VBP-1171

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