VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestDnDPrivate.cpp@ 97761

Last change on this file since 97761 was 97761, checked in by vboxsync, 2 years ago

DnD/Main: Don't set any (new) progress if the progress object already has been completed and/or cancelled [addendum to r154824].

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.4 KB
Line 
1/* $Id: GuestDnDPrivate.cpp 97761 2022-12-07 15:57:36Z vboxsync $ */
2/** @file
3 * Private guest drag and drop code, used by GuestDnDTarget + GuestDnDSource.
4 */
5
6/*
7 * Copyright (C) 2011-2022 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28#define LOG_GROUP LOG_GROUP_GUEST_DND
29#include "LoggingNew.h"
30
31#include "GuestImpl.h"
32#include "AutoCaller.h"
33
34#ifdef VBOX_WITH_DRAG_AND_DROP
35# include "ConsoleImpl.h"
36# include "ProgressImpl.h"
37# include "GuestDnDPrivate.h"
38
39# include <algorithm>
40
41# include <iprt/dir.h>
42# include <iprt/path.h>
43# include <iprt/stream.h>
44# include <iprt/semaphore.h>
45# include <iprt/cpp/utils.h>
46
47# include <VMMDev.h>
48
49# include <VBox/GuestHost/DragAndDrop.h>
50# include <VBox/HostServices/DragAndDropSvc.h>
51# include <VBox/version.h>
52
53/** @page pg_main_dnd Dungeons & Dragons - Overview
54 * Overview:
55 *
56 * Drag and Drop is handled over the internal HGCM service for the host <->
57 * guest communication. Beside that we need to map the Drag and Drop protocols
58 * of the various OS's we support to our internal channels, this is also highly
59 * communicative in both directions. Unfortunately HGCM isn't really designed
60 * for that. Next we have to foul some of the components. This includes to
61 * trick X11 on the guest side, but also Qt needs to be tricked on the host
62 * side a little bit.
63 *
64 * The following components are involved:
65 *
66 * 1. GUI: Uses the Qt classes for Drag and Drop and mainly forward the content
67 * of it to the Main IGuest / IGuestDnDSource / IGuestDnDTarget interfaces.
68 * 2. Main: Public interface for doing Drag and Drop. Also manage the IProgress
69 * interfaces for blocking the caller by showing a progress dialog (see
70 * this file).
71 * 3. HGCM service: Handle all messages from the host to the guest at once and
72 * encapsulate the internal communication details (see dndmanager.cpp and
73 * friends).
74 * 4. Guest Additions: Split into the platform neutral part (see
75 * VBoxGuestR3LibDragAndDrop.cpp) and the guest OS specific parts.
76 * Receive/send message from/to the HGCM service and does all guest specific
77 * operations. For Windows guests VBoxTray is in charge, whereas on UNIX-y guests
78 * VBoxClient will be used.
79 *
80 * Terminology:
81 *
82 * All transfers contain a MIME format and according meta data. This meta data then can
83 * be interpreted either as raw meta data or something else. When raw meta data is
84 * being handled, this gets passed through to the destination (guest / host) without
85 * modification. Other meta data (like URI lists) can and will be modified by the
86 * receiving side before passing to OS. How and when modifications will be applied
87 * depends on the MIME format.
88 *
89 * Host -> Guest:
90 * 1. There are DnD Enter, Move, Leave events which are send exactly like this
91 * to the guest. The info includes the position, MIME types and allowed actions.
92 * The guest has to respond with an action it would accept, so the GUI could
93 * change the cursor accordingly.
94 * 2. On drop, first a drop event is sent. If this is accepted a drop data
95 * event follows. This blocks the GUI and shows some progress indicator.
96 *
97 * Guest -> Host:
98 * 1. The GUI is asking the guest if a DnD event is pending when the user moves
99 * the cursor out of the view window. If so, this returns the mimetypes and
100 * allowed actions.
101 * (2. On every mouse move this is asked again, to make sure the DnD event is
102 * still valid.)
103 * 3. On drop the host request the data from the guest. This blocks the GUI and
104 * shows some progress indicator.
105 *
106 * Implementation hints:
107 * m_strSupportedFormats here in this file defines the allowed mime-types.
108 * This is necessary because we need special handling for some of the
109 * mime-types. E.g. for URI lists we need to transfer the actual dirs and
110 * files. Text EOL may to be changed. Also unknown mime-types may need special
111 * handling as well, which may lead to undefined behavior in the host/guest, if
112 * not done.
113 *
114 * Dropping of a directory, means recursively transferring _all_ the content.
115 *
116 * Directories and files are placed into the user's temporary directory on the
117 * guest (e.g. /tmp/VirtualBox Dropped Files). We can't delete them after the
118 * DnD operation, because we didn't know what the DnD target does with it. E.g.
119 * it could just be opened in place. This could lead ofc to filling up the disk
120 * within the guest. To inform the user about this, a small app could be
121 * developed which scans this directory regularly and inform the user with a
122 * tray icon hint (and maybe the possibility to clean this up instantly). The
123 * same has to be done in the G->H direction when it is implemented.
124 *
125 * Only regular files are supported; symlinks are not allowed.
126 *
127 * Transfers currently are an all-succeed or all-fail operation (see todos).
128 *
129 * On MacOS hosts we had to implement own DnD "promises" support for file transfers,
130 * as Qt does not support this out-of-the-box.
131 *
132 * The code tries to preserve the file modes of the transfered directories / files.
133 * This is useful (and maybe necessary) for two things:
134 * 1. If a file is executable, it should be also after the transfer, so the
135 * user can just execute it, without manually tweaking the modes first.
136 * 2. If a dir/file is not accessible by group/others in the host, it shouldn't
137 * be in the guest.
138 * In any case, the user mode is always set to rwx (so that we can access it
139 * ourself, in e.g. for a cleanup case after cancel).
140 *
141 * ACEs / ACLs currently are not supported.
142 *
143 * Cancelling ongoing transfers is supported in both directions by the guest
144 * and/or host side and cleans up all previous steps. This also involves
145 * removing partially transferred directories / files in the temporary directory.
146 *
147 ** @todo
148 * - ESC doesn't really work (on Windows guests it's already implemented)
149 * ... in any case it seems a little bit difficult to handle from the Qt side.
150 * - Transfers currently do not have any interactive (UI) callbacks / hooks which
151 * e.g. would allow to skip / replace / rename and entry, or abort the operation on failure.
152 * - Add support for more MIME types (especially images, csv)
153 * - Test unusual behavior:
154 * - DnD service crash in the guest during a DnD op (e.g. crash of VBoxClient or X11)
155 * - Not expected order of the events between HGCM and the guest
156 * - Security considerations: We transfer a lot of memory between the guest and
157 * the host and even allow the creation of dirs/files. Maybe there should be
158 * limits introduced to preventing DoS attacks or filling up all the memory
159 * (both in the host and the guest).
160 */
161
162
163/*********************************************************************************************************************************
164 * Internal macros. *
165 ********************************************************************************************************************************/
166
167/** Tries locking the GuestDnD object and returns on failure. */
168#define GUESTDND_LOCK() \
169 { \
170 int rcLock = RTCritSectEnter(&m_CritSect); \
171 if (RT_FAILURE(rcLock)) \
172 return rcLock; \
173 }
174
175/** Tries locking the GuestDnD object and returns a_Ret failure. */
176#define GUESTDND_LOCK_RET(a_Ret) \
177 { \
178 int rcLock = RTCritSectEnter(&m_CritSect); \
179 if (RT_FAILURE(rcLock)) \
180 return a_Ret; \
181 }
182
183/** Unlocks a formerly locked GuestDnD object. */
184#define GUESTDND_UNLOCK() \
185 { \
186 int rcUnlock = RTCritSectLeave(&m_CritSect); RT_NOREF(rcUnlock); \
187 AssertRC(rcUnlock); \
188 }
189
190/*********************************************************************************************************************************
191 * GuestDnDSendCtx implementation. *
192 ********************************************************************************************************************************/
193
194GuestDnDSendCtx::GuestDnDSendCtx(void)
195 : pTarget(NULL)
196 , pState(NULL)
197{
198 reset();
199}
200
201/**
202 * Resets a GuestDnDSendCtx object.
203 */
204void GuestDnDSendCtx::reset(void)
205{
206 if (pState)
207 pState->reset();
208
209 uScreenID = 0;
210
211 Transfer.reset();
212
213 int rc2 = EventCallback.Reset();
214 AssertRC(rc2);
215
216 GuestDnDData::reset();
217}
218
219/*********************************************************************************************************************************
220 * GuestDnDRecvCtx implementation. *
221 ********************************************************************************************************************************/
222
223GuestDnDRecvCtx::GuestDnDRecvCtx(void)
224 : pSource(NULL)
225 , pState(NULL)
226{
227 reset();
228}
229
230/**
231 * Resets a GuestDnDRecvCtx object.
232 */
233void GuestDnDRecvCtx::reset(void)
234{
235 if (pState)
236 pState->reset();
237
238 lstFmtOffered.clear();
239 strFmtReq = "";
240 strFmtRecv = "";
241 enmAction = 0;
242
243 Transfer.reset();
244
245 int rc2 = EventCallback.Reset();
246 AssertRC(rc2);
247
248 GuestDnDData::reset();
249}
250
251/*********************************************************************************************************************************
252 * GuestDnDCallbackEvent implementation. *
253 ********************************************************************************************************************************/
254
255GuestDnDCallbackEvent::~GuestDnDCallbackEvent(void)
256{
257 if (NIL_RTSEMEVENT != m_SemEvent)
258 RTSemEventDestroy(m_SemEvent);
259}
260
261/**
262 * Resets a GuestDnDCallbackEvent object.
263 */
264int GuestDnDCallbackEvent::Reset(void)
265{
266 int rc = VINF_SUCCESS;
267
268 if (NIL_RTSEMEVENT == m_SemEvent)
269 rc = RTSemEventCreate(&m_SemEvent);
270
271 m_Rc = VINF_SUCCESS;
272 return rc;
273}
274
275/**
276 * Completes a callback event by notifying the waiting side.
277 *
278 * @returns VBox status code.
279 * @param rc Result code to use for the event completion.
280 */
281int GuestDnDCallbackEvent::Notify(int rc /* = VINF_SUCCESS */)
282{
283 m_Rc = rc;
284 return RTSemEventSignal(m_SemEvent);
285}
286
287/**
288 * Waits on a callback event for being notified.
289 *
290 * @returns VBox status code.
291 * @param msTimeout Timeout (in ms) to wait for callback event.
292 */
293int GuestDnDCallbackEvent::Wait(RTMSINTERVAL msTimeout)
294{
295 return RTSemEventWait(m_SemEvent, msTimeout);
296}
297
298/********************************************************************************************************************************
299 *
300 ********************************************************************************************************************************/
301
302GuestDnDState::GuestDnDState(const ComObjPtr<Guest>& pGuest)
303 : m_uProtocolVersion(0)
304 , m_fGuestFeatures0(VBOX_DND_GF_NONE)
305 , m_EventSem(NIL_RTSEMEVENT)
306 , m_dndActionDefault(0)
307 , m_dndLstActionsAllowed(0)
308 , m_pParent(pGuest)
309{
310 int rc = RTSemEventCreate(&m_EventSem);
311 if (RT_FAILURE(rc))
312 throw rc;
313}
314
315GuestDnDState::~GuestDnDState(void)
316{
317 reset();
318
319 int rc = RTSemEventDestroy(m_EventSem);
320 AssertRC(rc);
321}
322
323/**
324 * Notifies the waiting side about a guest notification response.
325 */
326int GuestDnDState::notifyAboutGuestResponse(void) const
327{
328 return RTSemEventSignal(m_EventSem);
329}
330
331/**
332 * Resets a GuestDnDResponse object.
333 */
334void GuestDnDState::reset(void)
335{
336 LogFlowThisFuncEnter();
337
338 m_dndActionDefault = 0;
339 m_dndLstActionsAllowed = 0;
340
341 m_lstFormats.clear();
342}
343
344/**
345 * Resets the progress object.
346 *
347 * @returns HRESULT
348 * @param pParent Parent to set for the progress object.
349 */
350HRESULT GuestDnDState::resetProgress(const ComObjPtr<Guest>& pParent)
351{
352 m_pProgress.setNull();
353
354 HRESULT hr = m_pProgress.createObject();
355 if (SUCCEEDED(hr))
356 {
357 hr = m_pProgress->init(static_cast<IGuest *>(pParent),
358 Bstr(tr("Dropping data")).raw(),
359 TRUE /* aCancelable */);
360 }
361
362 return hr;
363}
364
365/**
366 * Returns whether the progress object has been canceled or not.
367 *
368 * @returns \c true if canceled, \c false if not.
369 */
370bool GuestDnDState::isProgressCanceled(void) const
371{
372 BOOL fCanceled;
373 if (!m_pProgress.isNull())
374 {
375 HRESULT hr = m_pProgress->COMGETTER(Canceled)(&fCanceled);
376 AssertComRC(hr);
377 }
378 else
379 fCanceled = TRUE;
380
381 return RT_BOOL(fCanceled);
382}
383
384/**
385 * Sets a callback for a specific HGCM message.
386 *
387 * @returns VBox status code.
388 * @param uMsg HGCM message ID to set callback for.
389 * @param pfnCallback Callback function pointer to use.
390 * @param pvUser User-provided arguments for the callback function. Optional and can be NULL.
391 */
392int GuestDnDState::setCallback(uint32_t uMsg, PFNGUESTDNDCALLBACK pfnCallback, void *pvUser /* = NULL */)
393{
394 GuestDnDCallbackMap::iterator it = m_mapCallbacks.find(uMsg);
395
396 /* Add. */
397 if (pfnCallback)
398 {
399 if (it == m_mapCallbacks.end())
400 {
401 m_mapCallbacks[uMsg] = GuestDnDCallback(pfnCallback, uMsg, pvUser);
402 return VINF_SUCCESS;
403 }
404
405 AssertMsgFailed(("Callback for message %RU32 already registered\n", uMsg));
406 return VERR_ALREADY_EXISTS;
407 }
408
409 /* Remove. */
410 if (it != m_mapCallbacks.end())
411 m_mapCallbacks.erase(it);
412
413 return VINF_SUCCESS;
414}
415
416/**
417 * Sets the progress object to a new state.
418 *
419 * @returns VBox status code.
420 * @param uPercentage Percentage (0-100) to set.
421 * @param uStatus Status (of type DND_PROGRESS_XXX) to set.
422 * @param rcOp IPRT-style result code to set. Optional.
423 * @param strMsg Message to set. Optional.
424 */
425int GuestDnDState::setProgress(unsigned uPercentage, uint32_t uStatus,
426 int rcOp /* = VINF_SUCCESS */, const Utf8Str &strMsg /* = "" */)
427{
428 LogFlowFunc(("uPercentage=%u, uStatus=%RU32, , rcOp=%Rrc, strMsg=%s\n",
429 uPercentage, uStatus, rcOp, strMsg.c_str()));
430
431 HRESULT hr = S_OK;
432
433 if (m_pProgress.isNull())
434 return VINF_SUCCESS;
435
436 BOOL fCompleted = FALSE;
437 hr = m_pProgress->COMGETTER(Completed)(&fCompleted);
438 AssertComRCReturn(hr, VERR_COM_UNEXPECTED);
439
440 BOOL fCanceled = FALSE;
441 hr = m_pProgress->COMGETTER(Canceled)(&fCanceled);
442 AssertComRCReturn(hr, VERR_COM_UNEXPECTED);
443
444 LogFlowFunc(("Progress fCompleted=%RTbool, fCanceled=%RTbool\n", fCompleted, fCanceled));
445
446 int rc = VINF_SUCCESS;
447
448 switch (uStatus)
449 {
450 case DragAndDropSvc::DND_PROGRESS_ERROR:
451 {
452 LogRel(("DnD: Guest reported error %Rrc\n", rcOp));
453
454 if (!fCompleted)
455 hr = m_pProgress->i_notifyComplete(VBOX_E_DND_ERROR,
456 COM_IIDOF(IGuest),
457 m_pParent->getComponentName(), strMsg.c_str());
458 reset();
459 break;
460 }
461
462 case DragAndDropSvc::DND_PROGRESS_CANCELLED:
463 {
464 LogRel2(("DnD: Guest cancelled operation\n"));
465
466 if (!fCanceled)
467 {
468 hr = m_pProgress->Cancel();
469 AssertComRC(hr);
470 }
471
472 if (!fCompleted)
473 {
474 hr = m_pProgress->i_notifyComplete(S_OK);
475 AssertComRC(hr);
476 }
477
478 reset();
479 break;
480 }
481
482 case DragAndDropSvc::DND_PROGRESS_RUNNING:
483 RT_FALL_THROUGH();
484 case DragAndDropSvc::DND_PROGRESS_COMPLETE:
485 {
486 LogRel2(("DnD: Guest reporting running/completion status with %u%%\n", uPercentage));
487
488 if ( !fCompleted
489 && !fCanceled)
490 {
491 hr = m_pProgress->SetCurrentOperationProgress(uPercentage);
492 AssertComRCReturn(hr, VERR_COM_UNEXPECTED);
493 if ( uStatus == DragAndDropSvc::DND_PROGRESS_COMPLETE
494 || uPercentage >= 100)
495 {
496 hr = m_pProgress->i_notifyComplete(S_OK);
497 AssertComRCReturn(hr, VERR_COM_UNEXPECTED);
498 }
499 }
500 break;
501 }
502
503 default:
504 break;
505 }
506
507 LogFlowFuncLeaveRC(rc);
508 return rc;
509}
510
511/**
512 * Dispatching function for handling the host service service callback.
513 *
514 * @returns VBox status code.
515 * @param u32Function HGCM message ID to handle.
516 * @param pvParms Pointer to optional data provided for a particular message. Optional.
517 * @param cbParms Size (in bytes) of \a pvParms.
518 */
519int GuestDnDState::onDispatch(uint32_t u32Function, void *pvParms, uint32_t cbParms)
520{
521 LogFlowFunc(("u32Function=%RU32, pvParms=%p, cbParms=%RU32\n", u32Function, pvParms, cbParms));
522
523 int rc = VERR_WRONG_ORDER; /* Play safe. */
524
525 /* Whether or not to try calling host-installed callbacks after successfully processing the message. */
526 bool fTryCallbacks = false;
527
528 switch (u32Function)
529 {
530 case DragAndDropSvc::GUEST_DND_FN_CONNECT:
531 {
532 DragAndDropSvc::PVBOXDNDCBCONNECTDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBCONNECTDATA>(pvParms);
533 AssertPtr(pCBData);
534 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBCONNECTDATA) == cbParms, VERR_INVALID_PARAMETER);
535 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_CONNECT == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
536
537 m_uProtocolVersion = pCBData->uProtocolVersion;
538 /** @todo Handle flags. */
539
540 LogThisFunc(("Client connected, using protocol v%RU32\n", m_uProtocolVersion));
541
542 rc = VINF_SUCCESS;
543 break;
544 }
545
546 case DragAndDropSvc::GUEST_DND_FN_REPORT_FEATURES:
547 {
548 DragAndDropSvc::PVBOXDNDCBREPORTFEATURESDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBREPORTFEATURESDATA>(pvParms);
549 AssertPtr(pCBData);
550 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBREPORTFEATURESDATA) == cbParms, VERR_INVALID_PARAMETER);
551 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_REPORT_FEATURES == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
552
553 m_fGuestFeatures0 = pCBData->fGuestFeatures0;
554
555 LogThisFunc(("Client reported features: %#RX64\n", m_fGuestFeatures0));
556
557 rc = VINF_SUCCESS;
558 break;
559 }
560
561 case DragAndDropSvc::GUEST_DND_FN_DISCONNECT:
562 {
563 LogThisFunc(("Client disconnected\n"));
564 rc = setProgress(100, DND_PROGRESS_CANCELLED, VINF_SUCCESS);
565 break;
566 }
567
568 case DragAndDropSvc::GUEST_DND_FN_HG_ACK_OP:
569 {
570 DragAndDropSvc::PVBOXDNDCBHGACKOPDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGACKOPDATA>(pvParms);
571 AssertPtr(pCBData);
572 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGACKOPDATA) == cbParms, VERR_INVALID_PARAMETER);
573 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_ACK_OP == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
574
575 LogRel2(("DnD: Guest responded with action '%s' for host->guest drag event\n", DnDActionToStr(pCBData->uAction)));
576
577 setActionDefault(pCBData->uAction);
578 rc = notifyAboutGuestResponse();
579 break;
580 }
581
582 case DragAndDropSvc::GUEST_DND_FN_HG_REQ_DATA:
583 {
584 DragAndDropSvc::PVBOXDNDCBHGREQDATADATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGREQDATADATA>(pvParms);
585 AssertPtr(pCBData);
586 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGREQDATADATA) == cbParms, VERR_INVALID_PARAMETER);
587 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_REQ_DATA == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
588
589 if ( pCBData->cbFormat == 0
590 || pCBData->cbFormat > _64K /** @todo Make this configurable? */
591 || pCBData->pszFormat == NULL)
592 {
593 rc = VERR_INVALID_PARAMETER;
594 }
595 else if (!RTStrIsValidEncoding(pCBData->pszFormat))
596 {
597 rc = VERR_INVALID_PARAMETER;
598 }
599 else
600 {
601 setFormats(GuestDnD::toFormatList(pCBData->pszFormat));
602 rc = VINF_SUCCESS;
603 }
604
605 int rc2 = notifyAboutGuestResponse();
606 if (RT_SUCCESS(rc))
607 rc = rc2;
608 break;
609 }
610
611 case DragAndDropSvc::GUEST_DND_FN_HG_EVT_PROGRESS:
612 {
613 DragAndDropSvc::PVBOXDNDCBHGEVTPROGRESSDATA pCBData =
614 reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGEVTPROGRESSDATA>(pvParms);
615 AssertPtr(pCBData);
616 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGEVTPROGRESSDATA) == cbParms, VERR_INVALID_PARAMETER);
617 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_EVT_PROGRESS == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
618
619 rc = setProgress(pCBData->uPercentage, pCBData->uStatus, pCBData->rc);
620 if (RT_SUCCESS(rc))
621 rc = notifyAboutGuestResponse();
622 break;
623 }
624#ifdef VBOX_WITH_DRAG_AND_DROP_GH
625 case DragAndDropSvc::GUEST_DND_FN_GH_ACK_PENDING:
626 {
627 DragAndDropSvc::PVBOXDNDCBGHACKPENDINGDATA pCBData =
628 reinterpret_cast<DragAndDropSvc::PVBOXDNDCBGHACKPENDINGDATA>(pvParms);
629 AssertPtr(pCBData);
630 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBGHACKPENDINGDATA) == cbParms, VERR_INVALID_PARAMETER);
631 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_GH_ACK_PENDING == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
632
633 LogRel2(("DnD: Guest responded with pending action '%s' (%RU32 bytes format data) to guest->host drag event\n",
634 DnDActionToStr(pCBData->uDefAction), pCBData->cbFormat));
635
636 if ( pCBData->cbFormat == 0
637 || pCBData->cbFormat > _64K /** @todo Make the maximum size configurable? */
638 || pCBData->pszFormat == NULL)
639 {
640 rc = VERR_INVALID_PARAMETER;
641 }
642 else if (!RTStrIsValidEncoding(pCBData->pszFormat))
643 {
644 rc = VERR_INVALID_PARAMETER;
645 }
646 else
647 {
648 setFormats (GuestDnD::toFormatList(pCBData->pszFormat));
649 setActionDefault (pCBData->uDefAction);
650 setActionsAllowed(pCBData->uAllActions);
651
652 rc = VINF_SUCCESS;
653 }
654
655 int rc2 = notifyAboutGuestResponse();
656 if (RT_SUCCESS(rc))
657 rc = rc2;
658 break;
659 }
660#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
661 default:
662 /* * Try if the event is covered by a registered callback. */
663 fTryCallbacks = true;
664 break;
665 }
666
667 /*
668 * Try the host's installed callbacks (if any).
669 */
670 if (fTryCallbacks)
671 {
672 GuestDnDCallbackMap::const_iterator it = m_mapCallbacks.find(u32Function);
673 if (it != m_mapCallbacks.end())
674 {
675 AssertPtr(it->second.pfnCallback);
676 rc = it->second.pfnCallback(u32Function, pvParms, cbParms, it->second.pvUser);
677 }
678 else
679 {
680 LogFlowFunc(("No callback for function %RU32 defined\n", u32Function));
681 rc = VERR_NOT_SUPPORTED; /* Tell the guest. */
682 }
683 }
684
685 LogFlowFunc(("Returning rc=%Rrc\n", rc));
686 return rc;
687}
688
689/**
690 * Helper function to query the internal progress object to an IProgress interface.
691 *
692 * @returns HRESULT
693 * @param ppProgress Where to query the progress object to.
694 */
695HRESULT GuestDnDState::queryProgressTo(IProgress **ppProgress)
696{
697 return m_pProgress.queryInterfaceTo(ppProgress);
698}
699
700/**
701 * Waits for a guest response to happen.
702 *
703 * @returns VBox status code.
704 * @param msTimeout Timeout (in ms) for waiting. Optional, waits 3000 ms if not specified.
705 */
706int GuestDnDState::waitForGuestResponse(RTMSINTERVAL msTimeout /*= 3000 */) const
707{
708 int rc = RTSemEventWait(m_EventSem, msTimeout);
709#ifdef DEBUG_andy
710 LogFlowFunc(("msTimeout=%RU32, rc=%Rrc\n", msTimeout, rc));
711#endif
712 return rc;
713}
714
715/*********************************************************************************************************************************
716 * GuestDnD implementation. *
717 ********************************************************************************************************************************/
718
719/** Static (Singleton) instance of the GuestDnD object. */
720GuestDnD* GuestDnD::s_pInstance = NULL;
721
722GuestDnD::GuestDnD(const ComObjPtr<Guest> &pGuest)
723 : m_pGuest(pGuest)
724 , m_cTransfersPending(0)
725{
726 LogFlowFuncEnter();
727
728 try
729 {
730 m_pState = new GuestDnDState(pGuest);
731 }
732 catch (std::bad_alloc &)
733 {
734 throw VERR_NO_MEMORY;
735 }
736
737 int rc = RTCritSectInit(&m_CritSect);
738 if (RT_FAILURE(rc))
739 throw rc;
740
741 /* List of supported default MIME types. */
742 LogRel2(("DnD: Supported default host formats:\n"));
743 const com::Utf8Str arrEntries[] = { VBOX_DND_FORMATS_DEFAULT };
744 for (size_t i = 0; i < RT_ELEMENTS(arrEntries); i++)
745 {
746 m_strDefaultFormats.push_back(arrEntries[i]);
747 LogRel2(("DnD: \t%s\n", arrEntries[i].c_str()));
748 }
749}
750
751GuestDnD::~GuestDnD(void)
752{
753 LogFlowFuncEnter();
754
755 Assert(m_cTransfersPending == 0); /* Sanity. */
756
757 RTCritSectDelete(&m_CritSect);
758
759 if (m_pState)
760 delete m_pState;
761}
762
763/**
764 * Adjusts coordinations to a given screen.
765 *
766 * @returns HRESULT
767 * @param uScreenId ID of screen to adjust coordinates to.
768 * @param puX Pointer to X coordinate to adjust. Will return the adjusted value on success.
769 * @param puY Pointer to Y coordinate to adjust. Will return the adjusted value on success.
770 */
771HRESULT GuestDnD::adjustScreenCoordinates(ULONG uScreenId, ULONG *puX, ULONG *puY) const
772{
773 /** @todo r=andy Save the current screen's shifting coordinates to speed things up.
774 * Only query for new offsets when the screen ID or the screen's resolution has changed. */
775
776 /* For multi-monitor support we need to add shift values to the coordinates
777 * (depending on the screen number). */
778 ComObjPtr<Console> pConsole = m_pGuest->i_getConsole();
779 ComPtr<IDisplay> pDisplay;
780 HRESULT hr = pConsole->COMGETTER(Display)(pDisplay.asOutParam());
781 if (FAILED(hr))
782 return hr;
783
784 ULONG dummy;
785 LONG xShift, yShift;
786 GuestMonitorStatus_T monitorStatus;
787 hr = pDisplay->GetScreenResolution(uScreenId, &dummy, &dummy, &dummy,
788 &xShift, &yShift, &monitorStatus);
789 if (FAILED(hr))
790 return hr;
791
792 if (puX)
793 *puX += xShift;
794 if (puY)
795 *puY += yShift;
796
797 LogFlowFunc(("uScreenId=%RU32, x=%RU32, y=%RU32\n", uScreenId, puX ? *puX : 0, puY ? *puY : 0));
798 return S_OK;
799}
800
801/**
802 * Returns a DnD guest state.
803 *
804 * @returns Pointer to DnD guest state, or NULL if not found / invalid.
805 * @param uID ID of DnD guest state to return.
806 */
807GuestDnDState *GuestDnD::getState(uint32_t uID /* = 0 */) const
808{
809 AssertMsgReturn(uID == 0, ("Only one state (0) is supported at the moment\n"), NULL);
810
811 return m_pState;
812}
813
814/**
815 * Sends a (blocking) message to the host side of the host service.
816 *
817 * @returns VBox status code.
818 * @param u32Function HGCM message ID to send.
819 * @param cParms Number of parameters to send.
820 * @param paParms Array of parameters to send. Must match \c cParms.
821 */
822int GuestDnD::hostCall(uint32_t u32Function, uint32_t cParms, PVBOXHGCMSVCPARM paParms) const
823{
824 Assert(!m_pGuest.isNull());
825 ComObjPtr<Console> pConsole = m_pGuest->i_getConsole();
826
827 /* Forward the information to the VMM device. */
828 Assert(!pConsole.isNull());
829 VMMDev *pVMMDev = pConsole->i_getVMMDev();
830 if (!pVMMDev)
831 return VERR_COM_OBJECT_NOT_FOUND;
832
833 return pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", u32Function, cParms, paParms);
834}
835
836/**
837 * Registers a GuestDnDSource object with the GuestDnD manager.
838 *
839 * Currently only one source is supported at a time.
840 *
841 * @returns VBox status code.
842 * @param Source Source to register.
843 */
844int GuestDnD::registerSource(const ComObjPtr<GuestDnDSource> &Source)
845{
846 GUESTDND_LOCK();
847
848 Assert(m_lstSrc.size() == 0); /* We only support one source at a time at the moment. */
849 m_lstSrc.push_back(Source);
850
851 GUESTDND_UNLOCK();
852 return VINF_SUCCESS;
853}
854
855/**
856 * Unregisters a GuestDnDSource object from the GuestDnD manager.
857 *
858 * @returns VBox status code.
859 * @param Source Source to unregister.
860 */
861int GuestDnD::unregisterSource(const ComObjPtr<GuestDnDSource> &Source)
862{
863 GUESTDND_LOCK();
864
865 GuestDnDSrcList::iterator itSrc = std::find(m_lstSrc.begin(), m_lstSrc.end(), Source);
866 if (itSrc != m_lstSrc.end())
867 m_lstSrc.erase(itSrc);
868
869 GUESTDND_UNLOCK();
870 return VINF_SUCCESS;
871}
872
873/**
874 * Returns the current number of registered sources.
875 *
876 * @returns Current number of registered sources.
877 */
878size_t GuestDnD::getSourceCount(void)
879{
880 GUESTDND_LOCK_RET(0);
881
882 size_t cSources = m_lstSrc.size();
883
884 GUESTDND_UNLOCK();
885 return cSources;
886}
887
888/**
889 * Registers a GuestDnDTarget object with the GuestDnD manager.
890 *
891 * Currently only one target is supported at a time.
892 *
893 * @returns VBox status code.
894 * @param Target Target to register.
895 */
896int GuestDnD::registerTarget(const ComObjPtr<GuestDnDTarget> &Target)
897{
898 GUESTDND_LOCK();
899
900 Assert(m_lstTgt.size() == 0); /* We only support one target at a time at the moment. */
901 m_lstTgt.push_back(Target);
902
903 GUESTDND_UNLOCK();
904 return VINF_SUCCESS;
905}
906
907/**
908 * Unregisters a GuestDnDTarget object from the GuestDnD manager.
909 *
910 * @returns VBox status code.
911 * @param Target Target to unregister.
912 */
913int GuestDnD::unregisterTarget(const ComObjPtr<GuestDnDTarget> &Target)
914{
915 GUESTDND_LOCK();
916
917 GuestDnDTgtList::iterator itTgt = std::find(m_lstTgt.begin(), m_lstTgt.end(), Target);
918 if (itTgt != m_lstTgt.end())
919 m_lstTgt.erase(itTgt);
920
921 GUESTDND_UNLOCK();
922 return VINF_SUCCESS;
923}
924
925/**
926 * Returns the current number of registered targets.
927 *
928 * @returns Current number of registered targets.
929 */
930size_t GuestDnD::getTargetCount(void)
931{
932 GUESTDND_LOCK_RET(0);
933
934 size_t cTargets = m_lstTgt.size();
935
936 GUESTDND_UNLOCK();
937 return cTargets;
938}
939
940/**
941 * Static main dispatcher function to handle callbacks from the DnD host service.
942 *
943 * @returns VBox status code.
944 * @param pvExtension Pointer to service extension.
945 * @param u32Function Callback HGCM message ID.
946 * @param pvParms Pointer to optional data provided for a particular message. Optional.
947 * @param cbParms Size (in bytes) of \a pvParms.
948 */
949/* static */
950DECLCALLBACK(int) GuestDnD::notifyDnDDispatcher(void *pvExtension, uint32_t u32Function,
951 void *pvParms, uint32_t cbParms)
952{
953 LogFlowFunc(("pvExtension=%p, u32Function=%RU32, pvParms=%p, cbParms=%RU32\n",
954 pvExtension, u32Function, pvParms, cbParms));
955
956 GuestDnD *pGuestDnD = reinterpret_cast<GuestDnD*>(pvExtension);
957 AssertPtrReturn(pGuestDnD, VERR_INVALID_POINTER);
958
959 /** @todo In case we need to handle multiple guest DnD responses at a time this
960 * would be the place to lookup and dispatch to those. For the moment we
961 * only have one response -- simple. */
962 if (pGuestDnD->m_pState)
963 return pGuestDnD->m_pState->onDispatch(u32Function, pvParms, cbParms);
964
965 return VERR_NOT_SUPPORTED;
966}
967
968/**
969 * Static helper function to determine whether a format is part of a given MIME list.
970 *
971 * @returns \c true if found, \c false if not.
972 * @param strFormat Format to search for.
973 * @param lstFormats MIME list to search in.
974 */
975/* static */
976bool GuestDnD::isFormatInFormatList(const com::Utf8Str &strFormat, const GuestDnDMIMEList &lstFormats)
977{
978 return std::find(lstFormats.begin(), lstFormats.end(), strFormat) != lstFormats.end();
979}
980
981/**
982 * Static helper function to create a GuestDnDMIMEList out of a format list string.
983 *
984 * @returns MIME list object.
985 * @param strFormats List of formats to convert.
986 * @param strSep Separator to use. If not specified, DND_FORMATS_SEPARATOR_STR will be used.
987 */
988/* static */
989GuestDnDMIMEList GuestDnD::toFormatList(const com::Utf8Str &strFormats, const com::Utf8Str &strSep /* = DND_FORMATS_SEPARATOR_STR */)
990{
991 GuestDnDMIMEList lstFormats;
992 RTCList<RTCString> lstFormatsTmp = strFormats.split(strSep);
993
994 for (size_t i = 0; i < lstFormatsTmp.size(); i++)
995 lstFormats.push_back(com::Utf8Str(lstFormatsTmp.at(i)));
996
997 return lstFormats;
998}
999
1000/**
1001 * Static helper function to create a format list string from a given GuestDnDMIMEList object.
1002 *
1003 * @returns Format list string.
1004 * @param lstFormats GuestDnDMIMEList to convert.
1005 */
1006/* static */
1007com::Utf8Str GuestDnD::toFormatString(const GuestDnDMIMEList &lstFormats)
1008{
1009 com::Utf8Str strFormat;
1010 for (size_t i = 0; i < lstFormats.size(); i++)
1011 {
1012 const com::Utf8Str &f = lstFormats.at(i);
1013 strFormat += f + DND_FORMATS_SEPARATOR_STR;
1014 }
1015
1016 return strFormat;
1017}
1018
1019/**
1020 * Static helper function to create a filtered GuestDnDMIMEList object from supported and wanted formats.
1021 *
1022 * @returns Filtered MIME list object.
1023 * @param lstFormatsSupported MIME list of supported formats.
1024 * @param lstFormatsWanted MIME list of wanted formats in returned object.
1025 */
1026/* static */
1027GuestDnDMIMEList GuestDnD::toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const GuestDnDMIMEList &lstFormatsWanted)
1028{
1029 GuestDnDMIMEList lstFormats;
1030
1031 for (size_t i = 0; i < lstFormatsWanted.size(); i++)
1032 {
1033 /* Only keep supported format types. */
1034 if (std::find(lstFormatsSupported.begin(),
1035 lstFormatsSupported.end(), lstFormatsWanted.at(i)) != lstFormatsSupported.end())
1036 {
1037 lstFormats.push_back(lstFormatsWanted[i]);
1038 }
1039 }
1040
1041 return lstFormats;
1042}
1043
1044/**
1045 * Static helper function to create a filtered GuestDnDMIMEList object from supported and wanted formats.
1046 *
1047 * @returns Filtered MIME list object.
1048 * @param lstFormatsSupported MIME list of supported formats.
1049 * @param strFormatsWanted Format list string of wanted formats in returned object.
1050 */
1051/* static */
1052GuestDnDMIMEList GuestDnD::toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const com::Utf8Str &strFormatsWanted)
1053{
1054 GuestDnDMIMEList lstFmt;
1055
1056 RTCList<RTCString> lstFormats = strFormatsWanted.split(DND_FORMATS_SEPARATOR_STR);
1057 size_t i = 0;
1058 while (i < lstFormats.size())
1059 {
1060 /* Only keep allowed format types. */
1061 if (std::find(lstFormatsSupported.begin(),
1062 lstFormatsSupported.end(), lstFormats.at(i)) != lstFormatsSupported.end())
1063 {
1064 lstFmt.push_back(lstFormats[i]);
1065 }
1066 i++;
1067 }
1068
1069 return lstFmt;
1070}
1071
1072/**
1073 * Static helper function to convert a Main DnD action an internal DnD action.
1074 *
1075 * @returns Internal DnD action, or VBOX_DND_ACTION_IGNORE if not found / supported.
1076 * @param enmAction Main DnD action to convert.
1077 */
1078/* static */
1079VBOXDNDACTION GuestDnD::toHGCMAction(DnDAction_T enmAction)
1080{
1081 VBOXDNDACTION dndAction = VBOX_DND_ACTION_IGNORE;
1082 switch (enmAction)
1083 {
1084 case DnDAction_Copy:
1085 dndAction = VBOX_DND_ACTION_COPY;
1086 break;
1087 case DnDAction_Move:
1088 dndAction = VBOX_DND_ACTION_MOVE;
1089 break;
1090 case DnDAction_Link:
1091 /* For now it doesn't seems useful to allow a link
1092 action between host & guest. Later? */
1093 case DnDAction_Ignore:
1094 /* Ignored. */
1095 break;
1096 default:
1097 AssertMsgFailed(("Action %RU32 not recognized!\n", enmAction));
1098 break;
1099 }
1100
1101 return dndAction;
1102}
1103
1104/**
1105 * Static helper function to convert a Main DnD default action and allowed Main actions to their
1106 * corresponding internal representations.
1107 *
1108 * @param enmDnDActionDefault Default Main action to convert.
1109 * @param pDnDActionDefault Where to store the converted default action.
1110 * @param vecDnDActionsAllowed Allowed Main actions to convert.
1111 * @param pDnDLstActionsAllowed Where to store the converted allowed actions.
1112 */
1113/* static */
1114void GuestDnD::toHGCMActions(DnDAction_T enmDnDActionDefault,
1115 VBOXDNDACTION *pDnDActionDefault,
1116 const std::vector<DnDAction_T> vecDnDActionsAllowed,
1117 VBOXDNDACTIONLIST *pDnDLstActionsAllowed)
1118{
1119 VBOXDNDACTIONLIST dndLstActionsAllowed = VBOX_DND_ACTION_IGNORE;
1120 VBOXDNDACTION dndActionDefault = toHGCMAction(enmDnDActionDefault);
1121
1122 if (!vecDnDActionsAllowed.empty())
1123 {
1124 /* First convert the allowed actions to a bit array. */
1125 for (size_t i = 0; i < vecDnDActionsAllowed.size(); i++)
1126 dndLstActionsAllowed |= toHGCMAction(vecDnDActionsAllowed[i]);
1127
1128 /*
1129 * If no default action is set (ignoring), try one of the
1130 * set allowed actions, preferring copy, move (in that order).
1131 */
1132 if (isDnDIgnoreAction(dndActionDefault))
1133 {
1134 if (hasDnDCopyAction(dndLstActionsAllowed))
1135 dndActionDefault = VBOX_DND_ACTION_COPY;
1136 else if (hasDnDMoveAction(dndLstActionsAllowed))
1137 dndActionDefault = VBOX_DND_ACTION_MOVE;
1138 }
1139 }
1140
1141 if (pDnDActionDefault)
1142 *pDnDActionDefault = dndActionDefault;
1143 if (pDnDLstActionsAllowed)
1144 *pDnDLstActionsAllowed = dndLstActionsAllowed;
1145}
1146
1147/**
1148 * Static helper function to convert an internal DnD action to its Main representation.
1149 *
1150 * @returns Converted Main DnD action.
1151 * @param dndAction DnD action to convert.
1152 */
1153/* static */
1154DnDAction_T GuestDnD::toMainAction(VBOXDNDACTION dndAction)
1155{
1156 /* For now it doesn't seems useful to allow a
1157 * link action between host & guest. Maybe later! */
1158 return isDnDCopyAction(dndAction) ? DnDAction_Copy
1159 : isDnDMoveAction(dndAction) ? DnDAction_Move
1160 : DnDAction_Ignore;
1161}
1162
1163/**
1164 * Static helper function to convert an internal DnD action list to its Main representation.
1165 *
1166 * @returns Converted Main DnD action list.
1167 * @param dndActionList DnD action list to convert.
1168 */
1169/* static */
1170std::vector<DnDAction_T> GuestDnD::toMainActions(VBOXDNDACTIONLIST dndActionList)
1171{
1172 std::vector<DnDAction_T> vecActions;
1173
1174 /* For now it doesn't seems useful to allow a
1175 * link action between host & guest. Maybe later! */
1176 RTCList<DnDAction_T> lstActions;
1177 if (hasDnDCopyAction(dndActionList))
1178 lstActions.append(DnDAction_Copy);
1179 if (hasDnDMoveAction(dndActionList))
1180 lstActions.append(DnDAction_Move);
1181
1182 for (size_t i = 0; i < lstActions.size(); ++i)
1183 vecActions.push_back(lstActions.at(i));
1184
1185 return vecActions;
1186}
1187
1188/*********************************************************************************************************************************
1189 * GuestDnDBase implementation. *
1190 ********************************************************************************************************************************/
1191
1192GuestDnDBase::GuestDnDBase(void)
1193 : m_fIsPending(false)
1194{
1195 /* Initialize public attributes. */
1196 m_lstFmtSupported = GuestDnDInst()->defaultFormats();
1197}
1198
1199/**
1200 * Checks whether a given DnD format is supported or not.
1201 *
1202 * @returns \c true if supported, \c false if not.
1203 * @param aFormat DnD format to check.
1204 */
1205bool GuestDnDBase::i_isFormatSupported(const com::Utf8Str &aFormat) const
1206{
1207 return std::find(m_lstFmtSupported.begin(), m_lstFmtSupported.end(), aFormat) != m_lstFmtSupported.end();
1208}
1209
1210/**
1211 * Returns the currently supported DnD formats.
1212 *
1213 * @returns List of the supported DnD formats.
1214 */
1215const GuestDnDMIMEList &GuestDnDBase::i_getFormats(void) const
1216{
1217 return m_lstFmtSupported;
1218}
1219
1220/**
1221 * Adds DnD formats to the supported formats list.
1222 *
1223 * @returns HRESULT
1224 * @param aFormats List of DnD formats to add.
1225 */
1226HRESULT GuestDnDBase::i_addFormats(const GuestDnDMIMEList &aFormats)
1227{
1228 for (size_t i = 0; i < aFormats.size(); ++i)
1229 {
1230 Utf8Str strFormat = aFormats.at(i);
1231 if (std::find(m_lstFmtSupported.begin(),
1232 m_lstFmtSupported.end(), strFormat) == m_lstFmtSupported.end())
1233 {
1234 m_lstFmtSupported.push_back(strFormat);
1235 }
1236 }
1237
1238 return S_OK;
1239}
1240
1241/**
1242 * Removes DnD formats from tehh supported formats list.
1243 *
1244 * @returns HRESULT
1245 * @param aFormats List of DnD formats to remove.
1246 */
1247HRESULT GuestDnDBase::i_removeFormats(const GuestDnDMIMEList &aFormats)
1248{
1249 for (size_t i = 0; i < aFormats.size(); ++i)
1250 {
1251 Utf8Str strFormat = aFormats.at(i);
1252 GuestDnDMIMEList::iterator itFormat = std::find(m_lstFmtSupported.begin(),
1253 m_lstFmtSupported.end(), strFormat);
1254 if (itFormat != m_lstFmtSupported.end())
1255 m_lstFmtSupported.erase(itFormat);
1256 }
1257
1258 return S_OK;
1259}
1260
1261/**
1262 * Adds a new guest DnD message to the internal message queue.
1263 *
1264 * @returns VBox status code.
1265 * @param pMsg Pointer to message to add.
1266 */
1267int GuestDnDBase::msgQueueAdd(GuestDnDMsg *pMsg)
1268{
1269 m_DataBase.lstMsgOut.push_back(pMsg);
1270 return VINF_SUCCESS;
1271}
1272
1273/**
1274 * Returns the next guest DnD message in the internal message queue (FIFO).
1275 *
1276 * @returns Pointer to guest DnD message, or NULL if none found.
1277 */
1278GuestDnDMsg *GuestDnDBase::msgQueueGetNext(void)
1279{
1280 if (m_DataBase.lstMsgOut.empty())
1281 return NULL;
1282 return m_DataBase.lstMsgOut.front();
1283}
1284
1285/**
1286 * Removes the next guest DnD message from the internal message queue.
1287 */
1288void GuestDnDBase::msgQueueRemoveNext(void)
1289{
1290 if (!m_DataBase.lstMsgOut.empty())
1291 {
1292 GuestDnDMsg *pMsg = m_DataBase.lstMsgOut.front();
1293 if (pMsg)
1294 delete pMsg;
1295 m_DataBase.lstMsgOut.pop_front();
1296 }
1297}
1298
1299/**
1300 * Clears the internal message queue.
1301 */
1302void GuestDnDBase::msgQueueClear(void)
1303{
1304 LogFlowFunc(("cMsg=%zu\n", m_DataBase.lstMsgOut.size()));
1305
1306 GuestDnDMsgList::iterator itMsg = m_DataBase.lstMsgOut.begin();
1307 while (itMsg != m_DataBase.lstMsgOut.end())
1308 {
1309 GuestDnDMsg *pMsg = *itMsg;
1310 if (pMsg)
1311 delete pMsg;
1312
1313 itMsg++;
1314 }
1315
1316 m_DataBase.lstMsgOut.clear();
1317}
1318
1319/**
1320 * Sends a request to the guest side to cancel the current DnD operation.
1321 *
1322 * @returns VBox status code.
1323 */
1324int GuestDnDBase::sendCancel(void)
1325{
1326 GuestDnDMsg Msg;
1327 Msg.setType(HOST_DND_FN_CANCEL);
1328 if (m_pState->m_uProtocolVersion >= 3)
1329 Msg.appendUInt32(0); /** @todo ContextID not used yet. */
1330
1331 LogRel2(("DnD: Cancelling operation on guest ...\n"));
1332
1333 int rc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
1334 if (RT_FAILURE(rc))
1335 LogRel(("DnD: Cancelling operation on guest failed with %Rrc\n", rc));
1336
1337 return rc;
1338}
1339
1340/**
1341 * Helper function to update the progress based on given a GuestDnDData object.
1342 *
1343 * @returns VBox status code.
1344 * @param pData GuestDnDData object to use for accounting.
1345 * @param pState Guest state to update its progress object for.
1346 * @param cbDataAdd By how much data (in bytes) to update the progress.
1347 */
1348int GuestDnDBase::updateProgress(GuestDnDData *pData, GuestDnDState *pState,
1349 size_t cbDataAdd /* = 0 */)
1350{
1351 AssertPtrReturn(pData, VERR_INVALID_POINTER);
1352 AssertPtrReturn(pState, VERR_INVALID_POINTER);
1353 /* cbDataAdd is optional. */
1354
1355 LogFlowFunc(("cbExtra=%zu, cbProcessed=%zu, cbRemaining=%zu, cbDataAdd=%zu\n",
1356 pData->cbExtra, pData->cbProcessed, pData->getRemaining(), cbDataAdd));
1357
1358 if ( !pState
1359 || !cbDataAdd) /* Only update if something really changes. */
1360 return VINF_SUCCESS;
1361
1362 if (cbDataAdd)
1363 pData->addProcessed(cbDataAdd);
1364
1365 const uint8_t uPercent = pData->getPercentComplete();
1366
1367 LogRel2(("DnD: Transfer %RU8%% complete\n", uPercent));
1368
1369 int rc = pState->setProgress(uPercent,
1370 pData->isComplete()
1371 ? DND_PROGRESS_COMPLETE
1372 : DND_PROGRESS_RUNNING);
1373 LogFlowFuncLeaveRC(rc);
1374 return rc;
1375}
1376
1377/**
1378 * Waits for a specific guest callback event to get signalled.
1379 *
1380 * @returns VBox status code. Will return VERR_CANCELLED if the user has cancelled the progress object.
1381 * @param pEvent Callback event to wait for.
1382 * @param pState Guest state to update.
1383 * @param msTimeout Timeout (in ms) to wait.
1384 */
1385int GuestDnDBase::waitForEvent(GuestDnDCallbackEvent *pEvent, GuestDnDState *pState, RTMSINTERVAL msTimeout)
1386{
1387 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1388 AssertPtrReturn(pState, VERR_INVALID_POINTER);
1389
1390 int rc;
1391
1392 LogFlowFunc(("msTimeout=%RU32\n", msTimeout));
1393
1394 uint64_t tsStart = RTTimeMilliTS();
1395 do
1396 {
1397 /*
1398 * Wait until our desired callback triggered the
1399 * wait event. As we don't want to block if the guest does not
1400 * respond, do busy waiting here.
1401 */
1402 rc = pEvent->Wait(500 /* ms */);
1403 if (RT_SUCCESS(rc))
1404 {
1405 rc = pEvent->Result();
1406 LogFlowFunc(("Callback done, result is %Rrc\n", rc));
1407 break;
1408 }
1409 else if (rc == VERR_TIMEOUT) /* Continue waiting. */
1410 rc = VINF_SUCCESS;
1411
1412 if ( msTimeout != RT_INDEFINITE_WAIT
1413 && RTTimeMilliTS() - tsStart > msTimeout)
1414 {
1415 rc = VERR_TIMEOUT;
1416 LogRel2(("DnD: Error: Guest did not respond within time\n"));
1417 }
1418 else if (pState->isProgressCanceled())
1419 {
1420 LogRel2(("DnD: Operation was canceled by user\n"));
1421 rc = VERR_CANCELLED;
1422 }
1423
1424 } while (RT_SUCCESS(rc));
1425
1426 LogFlowFuncLeaveRC(rc);
1427 return rc;
1428}
1429#endif /* VBOX_WITH_DRAG_AND_DROP */
1430
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