VirtualBox

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

Last change on this file since 106028 was 104635, checked in by vboxsync, 6 months ago

Main: Fixed warnings. ​bugref:3409

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 54.0 KB
Line 
1/* $Id: GuestDnDPrivate.cpp 104635 2024-05-15 09:29:32Z vboxsync $ */
2/** @file
3 * Private guest drag and drop code, used by GuestDnDTarget + GuestDnDSource.
4 */
5
6/*
7 * Copyright (C) 2011-2023 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* Defined Constants And Macros *
165*********************************************************************************************************************************/
166
167/** Tries locking the GuestDnD object and returns on failure. */
168#define GUESTDND_LOCK() do { \
169 int const vrcLock = RTCritSectEnter(&m_CritSect); \
170 if (RT_SUCCESS(vrcLock)) { /* likely */ } else return vrcLock; \
171 } while (0)
172
173/** Tries locking the GuestDnD object and returns a_Ret failure. */
174#define GUESTDND_LOCK_RET(a_Ret) do { \
175 int const vrcLock = RTCritSectEnter(&m_CritSect); \
176 if (RT_SUCCESS(vrcLock)) { /* likely */ } else return vrcLock; \
177 } while (0)
178
179/** Unlocks a formerly locked GuestDnD object. */
180#define GUESTDND_UNLOCK() do { \
181 int const vrcUnlock = RTCritSectLeave(&m_CritSect); \
182 AssertRC(vrcUnlock); \
183 } while (0)
184
185
186/*********************************************************************************************************************************
187* GuestDnDSendCtx implementation. *
188*********************************************************************************************************************************/
189
190GuestDnDSendCtx::GuestDnDSendCtx(void)
191 : pTarget(NULL)
192 , pState(NULL)
193{
194 reset();
195}
196
197/**
198 * Resets a GuestDnDSendCtx object.
199 */
200void GuestDnDSendCtx::reset(void)
201{
202 uScreenID = 0;
203
204 Transfer.reset();
205
206 int vrc2 = EventCallback.Reset();
207 AssertRC(vrc2);
208
209 GuestDnDData::reset();
210}
211
212
213/*********************************************************************************************************************************
214* GuestDnDRecvCtx implementation. *
215*********************************************************************************************************************************/
216
217GuestDnDRecvCtx::GuestDnDRecvCtx(void)
218 : pSource(NULL)
219 , pState(NULL)
220{
221 reset();
222}
223
224/**
225 * Resets a GuestDnDRecvCtx object.
226 */
227void GuestDnDRecvCtx::reset(void)
228{
229 lstFmtOffered.clear();
230 strFmtReq = "";
231 strFmtRecv = "";
232 enmAction = 0;
233
234 Transfer.reset();
235
236 int vrc2 = EventCallback.Reset();
237 AssertRC(vrc2);
238
239 GuestDnDData::reset();
240}
241
242
243/*********************************************************************************************************************************
244* GuestDnDCallbackEvent implementation. *
245*********************************************************************************************************************************/
246
247GuestDnDCallbackEvent::~GuestDnDCallbackEvent(void)
248{
249 if (NIL_RTSEMEVENT != m_SemEvent)
250 RTSemEventDestroy(m_SemEvent);
251}
252
253/**
254 * Resets a GuestDnDCallbackEvent object.
255 */
256int GuestDnDCallbackEvent::Reset(void)
257{
258 int vrc = VINF_SUCCESS;
259
260 if (m_SemEvent == NIL_RTSEMEVENT)
261 vrc = RTSemEventCreate(&m_SemEvent);
262
263 m_vrc = VINF_SUCCESS;
264 return vrc;
265}
266
267/**
268 * Completes a callback event by notifying the waiting side.
269 *
270 * @returns VBox status code.
271 * @param vrc Result code to use for the event completion.
272 */
273int GuestDnDCallbackEvent::Notify(int vrc /* = VINF_SUCCESS */)
274{
275 m_vrc = vrc;
276 return RTSemEventSignal(m_SemEvent);
277}
278
279/**
280 * Waits on a callback event for being notified.
281 *
282 * @returns VBox status code.
283 * @param msTimeout Timeout (in ms) to wait for callback event.
284 */
285int GuestDnDCallbackEvent::Wait(RTMSINTERVAL msTimeout)
286{
287 return RTSemEventWait(m_SemEvent, msTimeout);
288}
289
290
291/*********************************************************************************************************************************
292* GuestDnDState implementation *
293*********************************************************************************************************************************/
294
295GuestDnDState::GuestDnDState(const ComObjPtr<Guest>& pGuest)
296 : m_uProtocolVersion(0)
297 , m_fGuestFeatures0(VBOX_DND_GF_NONE)
298 , m_EventSem(NIL_RTSEMEVENT)
299 , m_pParent(pGuest)
300{
301 reset();
302
303 int vrc = RTCritSectInit(&m_CritSect);
304 if (RT_FAILURE(vrc))
305 throw vrc;
306 vrc = RTSemEventCreate(&m_EventSem);
307 if (RT_FAILURE(vrc))
308 throw vrc;
309}
310
311GuestDnDState::~GuestDnDState(void)
312{
313 int vrc = RTSemEventDestroy(m_EventSem);
314 AssertRC(vrc);
315 vrc = RTCritSectDelete(&m_CritSect);
316 AssertRC(vrc);
317}
318
319/**
320 * Notifies the waiting side about a guest notification response.
321 *
322 * @returns VBox status code.
323 * @param vrcGuest Guest VBox status code to set for the response.
324 * Defaults to VINF_SUCCESS (for success).
325 */
326int GuestDnDState::notifyAboutGuestResponse(int vrcGuest /* = VINF_SUCCESS */)
327{
328 m_vrcGuest = vrcGuest;
329 return RTSemEventSignal(m_EventSem);
330}
331
332/**
333 * Resets a guest drag'n drop state.
334 */
335void GuestDnDState::reset(void)
336{
337 LogRel2(("DnD: Reset\n"));
338
339 m_enmState = VBOXDNDSTATE_UNKNOWN;
340
341 m_dndActionDefault = VBOX_DND_ACTION_IGNORE;
342 m_dndLstActionsAllowed = VBOX_DND_ACTION_IGNORE;
343
344 m_lstFormats.clear();
345 m_mapCallbacks.clear();
346
347 m_vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
348}
349
350/**
351 * Default callback handler for guest callbacks.
352 *
353 * This handler acts as a fallback in case important callback messages are not being handled
354 * by the specific callers.
355 *
356 * @returns VBox status code. Will get sent back to the host service.
357 * @retval VERR_NO_DATA if no new messages from the host side are available at the moment.
358 * @retval VERR_CANCELLED for indicating that the current operation was cancelled.
359 * @param uMsg HGCM message ID (function number).
360 * @param pvParms Pointer to additional message data. Optional and can be NULL.
361 * @param cbParms Size (in bytes) additional message data. Optional and can be 0.
362 * @param pvUser User-supplied pointer on callback registration.
363 */
364/* static */
365DECLCALLBACK(int) GuestDnDState::i_defaultCallback(uint32_t uMsg, void *pvParms, size_t cbParms, void *pvUser)
366{
367 GuestDnDState *pThis = (GuestDnDState *)pvUser;
368 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
369
370 LogFlowFunc(("uMsg=%RU32 (%#x)\n", uMsg, uMsg));
371
372 int vrc = VERR_IPE_UNINITIALIZED_STATUS;
373
374 switch (uMsg)
375 {
376 case GUEST_DND_FN_EVT_ERROR:
377 {
378 PVBOXDNDCBEVTERRORDATA pCBData = reinterpret_cast<PVBOXDNDCBEVTERRORDATA>(pvParms);
379 AssertPtr(pCBData);
380 AssertReturn(sizeof(VBOXDNDCBEVTERRORDATA) == cbParms, VERR_INVALID_PARAMETER);
381 AssertReturn(CB_MAGIC_DND_EVT_ERROR == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
382
383 if (RT_SUCCESS(pCBData->rc))
384 {
385 AssertMsgFailed(("Guest has sent an error event but did not specify an actual error code\n"));
386 pCBData->rc = VERR_GENERAL_FAILURE; /* Make sure some error is set. */
387 }
388
389 vrc = pThis->setProgress(100, DND_PROGRESS_ERROR, pCBData->rc,
390 Utf8StrFmt("Received error from guest: %Rrc", pCBData->rc));
391 AssertRCBreak(vrc);
392 vrc = pThis->notifyAboutGuestResponse(pCBData->rc);
393 AssertRCBreak(vrc);
394 break;
395 }
396
397 case GUEST_DND_FN_GET_NEXT_HOST_MSG:
398 vrc = VERR_NO_DATA; /* Indicate back to the host service that there are no new messages. */
399 break;
400
401 default:
402 AssertMsgBreakStmt(pThis->isProgressRunning() == false,
403 ("Progress object not completed / canceld yet! State is '%s' (%#x)\n",
404 DnDStateToStr(pThis->m_enmState), pThis->m_enmState),
405 vrc = VERR_INVALID_STATE); /* Please report this! */
406 vrc = VERR_CANCELLED;
407 break;
408 }
409
410 LogFlowFunc(("Returning vrc=%Rrc\n", vrc));
411 return vrc;
412}
413
414/**
415 * Resets the progress object.
416 *
417 * @returns HRESULT
418 * @param pParent Parent to set for the progress object.
419 * @param strDesc Description of the progress.
420 */
421HRESULT GuestDnDState::resetProgress(const ComObjPtr<Guest>& pParent, const Utf8Str &strDesc)
422{
423 AssertReturn(strDesc.isNotEmpty(), E_INVALIDARG);
424
425 m_pProgress.setNull();
426
427 HRESULT hrc = m_pProgress.createObject();
428 if (SUCCEEDED(hrc))
429 hrc = m_pProgress->init(static_cast<IGuest *>(pParent), Bstr(strDesc).raw(), TRUE /* aCancelable */);
430
431 return hrc;
432}
433
434/**
435 * Returns whether the progress object has been canceled or not.
436 *
437 * @returns \c true if canceled or progress does not exist, \c false if not.
438 */
439bool GuestDnDState::isProgressCanceled(void) const
440{
441 if (m_pProgress.isNull())
442 return true;
443
444 BOOL fCanceled;
445 HRESULT hrc = m_pProgress->COMGETTER(Canceled)(&fCanceled);
446 AssertComRCReturn(hrc, false);
447 return RT_BOOL(fCanceled);
448}
449
450/**
451 * Returns whether the progress object still is in a running state or not.
452 *
453 * @returns \c true if running, \c false if not.
454 */
455bool GuestDnDState::isProgressRunning(void) const
456{
457 if (m_pProgress.isNull())
458 return false;
459
460 BOOL fCompleted;
461 HRESULT const hrc = m_pProgress->COMGETTER(Completed)(&fCompleted);
462 AssertComRCReturn(hrc, false);
463 return !RT_BOOL(fCompleted);
464}
465
466/**
467 * Sets (registers or unregisters) a callback for a specific HGCM message.
468 *
469 * @returns VBox status code.
470 * @param uMsg HGCM message ID to set callback for.
471 * @param pfnCallback Callback function pointer to use. Pass NULL to unregister.
472 * @param pvUser User-provided arguments for the callback function. Optional and can be NULL.
473 */
474int GuestDnDState::setCallback(uint32_t uMsg, PFNGUESTDNDCALLBACK pfnCallback, void *pvUser /* = NULL */)
475{
476 GuestDnDCallbackMap::iterator it = m_mapCallbacks.find(uMsg);
477
478 /* Register. */
479 if (pfnCallback)
480 {
481 try
482 {
483 m_mapCallbacks[uMsg] = GuestDnDCallback(pfnCallback, uMsg, pvUser);
484 }
485 catch (std::bad_alloc &)
486 {
487 return VERR_NO_MEMORY;
488 }
489 return VINF_SUCCESS;
490 }
491
492 /* Unregister. */
493 if (it != m_mapCallbacks.end())
494 m_mapCallbacks.erase(it);
495
496 return VINF_SUCCESS;
497}
498
499/**
500 * Sets the progress object to a new state.
501 *
502 * @returns VBox status code.
503 * @param uPercentage Percentage (0-100) to set.
504 * @param uStatus Status (of type DND_PROGRESS_XXX) to set.
505 * @param vrcOp VBox status code to set. Optional.
506 * @param strMsg Message to set. Optional.
507 */
508int GuestDnDState::setProgress(unsigned uPercentage, uint32_t uStatus,
509 int vrcOp /* = VINF_SUCCESS */, const Utf8Str &strMsg /* = Utf8Str::Empty */)
510{
511 LogFlowFunc(("uPercentage=%u, uStatus=%RU32, , vrcOp=%Rrc, strMsg=%s\n",
512 uPercentage, uStatus, vrcOp, strMsg.c_str()));
513
514 if (m_pProgress.isNull())
515 return VINF_SUCCESS;
516
517 BOOL fCompleted = FALSE;
518 HRESULT hrc = m_pProgress->COMGETTER(Completed)(&fCompleted);
519 AssertComRCReturn(hrc, VERR_COM_UNEXPECTED);
520
521 BOOL fCanceled = FALSE;
522 hrc = m_pProgress->COMGETTER(Canceled)(&fCanceled);
523 AssertComRCReturn(hrc, VERR_COM_UNEXPECTED);
524
525 LogFlowFunc(("Progress fCompleted=%RTbool, fCanceled=%RTbool\n", fCompleted, fCanceled));
526
527 int vrc = VINF_SUCCESS;
528
529 switch (uStatus)
530 {
531 case DragAndDropSvc::DND_PROGRESS_ERROR:
532 {
533 LogRel(("DnD: Guest reported error %Rrc\n", vrcOp));
534
535 if (!fCompleted)
536 {
537 hrc = m_pProgress->i_notifyComplete(VBOX_E_DND_ERROR, COM_IIDOF(IGuest),
538 m_pParent->getComponentName(), strMsg.c_str());
539 AssertComRC(hrc);
540 }
541 break;
542 }
543
544 case DragAndDropSvc::DND_PROGRESS_CANCELLED:
545 {
546 LogRel2(("DnD: Guest cancelled operation\n"));
547
548 if (!fCanceled)
549 {
550 hrc = m_pProgress->Cancel();
551 AssertComRC(hrc);
552 }
553
554 if (!fCompleted)
555 {
556 hrc = m_pProgress->i_notifyComplete(S_OK);
557 AssertComRC(hrc);
558 }
559 break;
560 }
561
562 case DragAndDropSvc::DND_PROGRESS_RUNNING:
563 RT_FALL_THROUGH();
564 case DragAndDropSvc::DND_PROGRESS_COMPLETE:
565 {
566 LogRel2(("DnD: Guest reporting running/completion status with %u%%\n", uPercentage));
567
568 if ( !fCompleted
569 && !fCanceled)
570 {
571 hrc = m_pProgress->SetCurrentOperationProgress(uPercentage);
572 AssertComRCReturn(hrc, VERR_COM_UNEXPECTED);
573 if ( uStatus == DragAndDropSvc::DND_PROGRESS_COMPLETE
574 || uPercentage >= 100)
575 {
576 hrc = m_pProgress->i_notifyComplete(S_OK);
577 AssertComRCReturn(hrc, VERR_COM_UNEXPECTED);
578 }
579 }
580 break;
581 }
582
583 default:
584 break;
585 }
586
587 LogFlowFuncLeaveRC(vrc);
588 return vrc;
589}
590
591/**
592 * Dispatching function for handling the host service service callback.
593 *
594 * @returns VBox status code.
595 * @param u32Function HGCM message ID to handle.
596 * @param pvParms Pointer to optional data provided for a particular message. Optional.
597 * @param cbParms Size (in bytes) of \a pvParms.
598 */
599int GuestDnDState::onDispatch(uint32_t u32Function, void *pvParms, uint32_t cbParms)
600{
601 LogFlowFunc(("u32Function=%RU32, pvParms=%p, cbParms=%RU32\n", u32Function, pvParms, cbParms));
602
603 int vrc = VERR_WRONG_ORDER; /* Play safe. */
604
605 /* Whether or not to try calling host-installed callbacks after successfully processing the message. */
606 bool fTryCallbacks = false;
607
608 switch (u32Function)
609 {
610 case DragAndDropSvc::GUEST_DND_FN_CONNECT:
611 {
612 DragAndDropSvc::PVBOXDNDCBCONNECTDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBCONNECTDATA>(pvParms);
613 AssertPtr(pCBData);
614 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBCONNECTDATA) == cbParms, VERR_INVALID_PARAMETER);
615 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_CONNECT == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
616
617 m_uProtocolVersion = pCBData->uProtocolVersion;
618 /** @todo Handle flags. */
619
620 LogThisFunc(("Client connected, using protocol v%RU32\n", m_uProtocolVersion));
621
622 vrc = VINF_SUCCESS;
623 break;
624 }
625
626 case DragAndDropSvc::GUEST_DND_FN_REPORT_FEATURES:
627 {
628 DragAndDropSvc::PVBOXDNDCBREPORTFEATURESDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBREPORTFEATURESDATA>(pvParms);
629 AssertPtr(pCBData);
630 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBREPORTFEATURESDATA) == cbParms, VERR_INVALID_PARAMETER);
631 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_REPORT_FEATURES == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
632
633 m_fGuestFeatures0 = pCBData->fGuestFeatures0;
634
635 LogThisFunc(("Client reported features: %#RX64\n", m_fGuestFeatures0));
636
637 vrc = VINF_SUCCESS;
638 break;
639 }
640
641 /* Note: GUEST_DND_FN_EVT_ERROR is handled in either the state's default callback or in specific
642 * (overriden) callbacks (e.g. GuestDnDSendCtx / GuestDnDRecvCtx). */
643
644 case DragAndDropSvc::GUEST_DND_FN_DISCONNECT:
645 {
646 LogThisFunc(("Client disconnected\n"));
647 vrc = setProgress(100, DND_PROGRESS_CANCELLED, VINF_SUCCESS);
648 break;
649 }
650
651 case DragAndDropSvc::GUEST_DND_FN_HG_ACK_OP:
652 {
653 DragAndDropSvc::PVBOXDNDCBHGACKOPDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGACKOPDATA>(pvParms);
654 AssertPtr(pCBData);
655 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGACKOPDATA) == cbParms, VERR_INVALID_PARAMETER);
656 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_ACK_OP == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
657
658 LogRel2(("DnD: Guest responded with action '%s' for host->guest drag event\n", DnDActionToStr(pCBData->uAction)));
659
660 setActionDefault(pCBData->uAction);
661 vrc = notifyAboutGuestResponse();
662 break;
663 }
664
665 case DragAndDropSvc::GUEST_DND_FN_HG_REQ_DATA:
666 {
667 DragAndDropSvc::PVBOXDNDCBHGREQDATADATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGREQDATADATA>(pvParms);
668 AssertPtr(pCBData);
669 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGREQDATADATA) == cbParms, VERR_INVALID_PARAMETER);
670 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_REQ_DATA == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
671
672 if ( pCBData->cbFormat == 0
673 || pCBData->cbFormat > _64K /** @todo Make this configurable? */
674 || pCBData->pszFormat == NULL)
675 vrc = VERR_INVALID_PARAMETER;
676 else if (!RTStrIsValidEncoding(pCBData->pszFormat))
677 vrc = VERR_INVALID_PARAMETER;
678 else
679 {
680 setFormats(GuestDnD::toFormatList(pCBData->pszFormat));
681 vrc = VINF_SUCCESS;
682 }
683
684 int vrc2 = notifyAboutGuestResponse();
685 if (RT_SUCCESS(vrc))
686 vrc = vrc2;
687 break;
688 }
689
690 case DragAndDropSvc::GUEST_DND_FN_HG_EVT_PROGRESS:
691 {
692 DragAndDropSvc::PVBOXDNDCBHGEVTPROGRESSDATA pCBData =
693 reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGEVTPROGRESSDATA>(pvParms);
694 AssertPtr(pCBData);
695 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGEVTPROGRESSDATA) == cbParms, VERR_INVALID_PARAMETER);
696 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_EVT_PROGRESS == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
697
698 vrc = setProgress(pCBData->uPercentage, pCBData->uStatus, pCBData->rc);
699 if (RT_SUCCESS(vrc))
700 vrc = notifyAboutGuestResponse(pCBData->rc);
701 break;
702 }
703#ifdef VBOX_WITH_DRAG_AND_DROP_GH
704 case DragAndDropSvc::GUEST_DND_FN_GH_ACK_PENDING:
705 {
706 DragAndDropSvc::PVBOXDNDCBGHACKPENDINGDATA pCBData =
707 reinterpret_cast<DragAndDropSvc::PVBOXDNDCBGHACKPENDINGDATA>(pvParms);
708 AssertPtr(pCBData);
709 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBGHACKPENDINGDATA) == cbParms, VERR_INVALID_PARAMETER);
710 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_GH_ACK_PENDING == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
711
712 LogRel2(("DnD: Guest responded with pending action '%s' (%RU32 bytes format data) to guest->host drag event\n",
713 DnDActionToStr(pCBData->uDefAction), pCBData->cbFormat));
714
715 if ( pCBData->cbFormat == 0
716 || pCBData->cbFormat > _64K /** @todo Make the maximum size configurable? */
717 || pCBData->pszFormat == NULL)
718 vrc = VERR_INVALID_PARAMETER;
719 else if (!RTStrIsValidEncoding(pCBData->pszFormat))
720 vrc = VERR_INVALID_PARAMETER;
721 else
722 {
723 setFormats (GuestDnD::toFormatList(pCBData->pszFormat));
724 setActionDefault (pCBData->uDefAction);
725 setActionsAllowed(pCBData->uAllActions);
726
727 vrc = VINF_SUCCESS;
728 }
729
730 int vrc2 = notifyAboutGuestResponse();
731 if (RT_SUCCESS(vrc))
732 vrc = vrc2;
733 break;
734 }
735#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
736 default:
737 /* * Try if the event is covered by a registered callback. */
738 fTryCallbacks = true;
739 break;
740 }
741
742 /*
743 * Try the host's installed callbacks (if any).
744 */
745 if (fTryCallbacks)
746 {
747 GuestDnDCallbackMap::const_iterator it = m_mapCallbacks.find(u32Function);
748 if (it != m_mapCallbacks.end())
749 {
750 AssertPtr(it->second.pfnCallback);
751 vrc = it->second.pfnCallback(u32Function, pvParms, cbParms, it->second.pvUser);
752 }
753 else
754 {
755 /* Invoke the default callback handler in case we don't have any registered callback above. */
756 vrc = i_defaultCallback(u32Function, pvParms, cbParms, this /* pvUser */);
757 }
758 }
759
760 LogFlowFunc(("Returning vrc=%Rrc\n", vrc));
761 return vrc;
762}
763
764/**
765 * Helper function to query the internal progress object to an IProgress interface.
766 *
767 * @returns HRESULT
768 * @param ppProgress Where to query the progress object to.
769 */
770HRESULT GuestDnDState::queryProgressTo(IProgress **ppProgress)
771{
772 return m_pProgress.queryInterfaceTo(ppProgress);
773}
774
775/**
776 * Waits for a guest response to happen, extended version.
777 *
778 * @returns VBox status code.
779 * @retval VERR_TIMEOUT when waiting has timed out.
780 * @retval VERR_DND_GUEST_ERROR on an error reported back from the guest.
781 * @param msTimeout Timeout (in ms) for waiting. Optional, waits 3000 ms if not specified.
782 * @param pvrcGuest Where to return the guest error when
783 * VERR_DND_GUEST_ERROR is returned. Optional.
784 */
785int GuestDnDState::waitForGuestResponseEx(RTMSINTERVAL msTimeout /* = 3000 */, int *pvrcGuest /* = NULL */)
786{
787 int vrc = RTSemEventWait(m_EventSem, msTimeout);
788 if (RT_SUCCESS(vrc))
789 {
790 if (RT_FAILURE(m_vrcGuest))
791 vrc = VERR_DND_GUEST_ERROR;
792 if (pvrcGuest)
793 *pvrcGuest = m_vrcGuest;
794 }
795 return vrc;
796}
797
798/**
799 * Waits for a guest response to happen.
800 *
801 * @returns VBox status code.
802 * @retval VERR_TIMEOUT when waiting has timed out.
803 * @retval VERR_DND_GUEST_ERROR on an error reported back from the guest.
804 * @param pvrcGuest Where to return the guest error when
805 * VERR_DND_GUEST_ERROR is returned. Optional.
806 *
807 * @note Uses the default timeout of 3000 ms.
808 */
809int GuestDnDState::waitForGuestResponse(int *pvrcGuest /* = NULL */)
810{
811 return waitForGuestResponseEx(3000 /* ms */, pvrcGuest);
812}
813
814/*********************************************************************************************************************************
815 * GuestDnD implementation. *
816 ********************************************************************************************************************************/
817
818/** Static (Singleton) instance of the GuestDnD object. */
819GuestDnD* GuestDnD::s_pInstance = NULL;
820
821GuestDnD::GuestDnD(const ComObjPtr<Guest> &pGuest)
822 : m_pGuest(pGuest)
823 , m_cTransfersPending(0)
824{
825 LogFlowFuncEnter();
826
827 try
828 {
829 m_pState = new GuestDnDState(pGuest);
830 }
831 catch (std::bad_alloc &)
832 {
833 throw VERR_NO_MEMORY;
834 }
835
836 int vrc = RTCritSectInit(&m_CritSect);
837 if (RT_FAILURE(vrc))
838 throw vrc;
839
840 /* List of supported default MIME types. */
841 LogRel2(("DnD: Supported default host formats:\n"));
842 const com::Utf8Str arrEntries[] = { VBOX_DND_FORMATS_DEFAULT };
843 for (size_t i = 0; i < RT_ELEMENTS(arrEntries); i++)
844 {
845 m_strDefaultFormats.push_back(arrEntries[i]);
846 LogRel2(("DnD: \t%s\n", arrEntries[i].c_str()));
847 }
848}
849
850GuestDnD::~GuestDnD(void)
851{
852 LogFlowFuncEnter();
853
854 Assert(m_cTransfersPending == 0); /* Sanity. */
855
856 RTCritSectDelete(&m_CritSect);
857
858 if (m_pState)
859 delete m_pState;
860}
861
862/**
863 * Adjusts coordinations to a given screen.
864 *
865 * @returns HRESULT
866 * @param uScreenId ID of screen to adjust coordinates to.
867 * @param puX Pointer to X coordinate to adjust. Will return the adjusted value on success.
868 * @param puY Pointer to Y coordinate to adjust. Will return the adjusted value on success.
869 */
870HRESULT GuestDnD::adjustScreenCoordinates(ULONG uScreenId, ULONG *puX, ULONG *puY) const
871{
872 /** @todo r=andy Save the current screen's shifting coordinates to speed things up.
873 * Only query for new offsets when the screen ID or the screen's resolution has changed. */
874
875 /* For multi-monitor support we need to add shift values to the coordinates
876 * (depending on the screen number). */
877 ComObjPtr<Console> pConsole = m_pGuest->i_getConsole();
878 ComPtr<IDisplay> pDisplay;
879 HRESULT hrc = pConsole->COMGETTER(Display)(pDisplay.asOutParam());
880 if (FAILED(hrc))
881 return hrc;
882
883 ULONG dummy;
884 LONG xShift, yShift;
885 GuestMonitorStatus_T monitorStatus;
886 hrc = pDisplay->GetScreenResolution(uScreenId, &dummy, &dummy, &dummy, &xShift, &yShift, &monitorStatus);
887 if (FAILED(hrc))
888 return hrc;
889
890 if (puX)
891 *puX += xShift;
892 if (puY)
893 *puY += yShift;
894
895 LogFlowFunc(("uScreenId=%RU32, x=%RU32, y=%RU32\n", uScreenId, puX ? *puX : 0, puY ? *puY : 0));
896 return S_OK;
897}
898
899/**
900 * Returns a DnD guest state.
901 *
902 * @returns Pointer to DnD guest state, or NULL if not found / invalid.
903 * @param uID ID of DnD guest state to return.
904 */
905GuestDnDState *GuestDnD::getState(uint32_t uID /* = 0 */) const
906{
907 AssertMsgReturn(uID == 0, ("Only one state (0) is supported at the moment\n"), NULL);
908
909 return m_pState;
910}
911
912/**
913 * Sends a (blocking) message to the host side of the host service.
914 *
915 * @returns VBox status code.
916 * @param u32Function HGCM message ID to send.
917 * @param cParms Number of parameters to send.
918 * @param paParms Array of parameters to send. Must match \c cParms.
919 */
920int GuestDnD::hostCall(uint32_t u32Function, uint32_t cParms, PVBOXHGCMSVCPARM paParms) const
921{
922 Assert(!m_pGuest.isNull());
923 ComObjPtr<Console> pConsole = m_pGuest->i_getConsole();
924
925 /* Forward the information to the VMM device. */
926 Assert(!pConsole.isNull());
927 VMMDev *pVMMDev = pConsole->i_getVMMDev();
928 if (!pVMMDev)
929 return VERR_COM_OBJECT_NOT_FOUND;
930
931 return pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", u32Function, cParms, paParms);
932}
933
934/**
935 * Registers a GuestDnDSource object with the GuestDnD manager.
936 *
937 * Currently only one source is supported at a time.
938 *
939 * @returns VBox status code.
940 * @param Source Source to register.
941 */
942int GuestDnD::registerSource(const ComObjPtr<GuestDnDSource> &Source)
943{
944 GUESTDND_LOCK();
945
946 Assert(m_lstSrc.size() == 0); /* We only support one source at a time at the moment. */
947 m_lstSrc.push_back(Source);
948
949 GUESTDND_UNLOCK();
950 return VINF_SUCCESS;
951}
952
953/**
954 * Unregisters a GuestDnDSource object from the GuestDnD manager.
955 *
956 * @returns VBox status code.
957 * @param Source Source to unregister.
958 */
959int GuestDnD::unregisterSource(const ComObjPtr<GuestDnDSource> &Source)
960{
961 GUESTDND_LOCK();
962
963 GuestDnDSrcList::iterator itSrc = std::find(m_lstSrc.begin(), m_lstSrc.end(), Source);
964 if (itSrc != m_lstSrc.end())
965 m_lstSrc.erase(itSrc);
966
967 GUESTDND_UNLOCK();
968 return VINF_SUCCESS;
969}
970
971/**
972 * Returns the current number of registered sources.
973 *
974 * @returns Current number of registered sources.
975 */
976size_t GuestDnD::getSourceCount(void)
977{
978 GUESTDND_LOCK_RET(0);
979
980 size_t cSources = m_lstSrc.size();
981
982 GUESTDND_UNLOCK();
983 return cSources;
984}
985
986/**
987 * Registers a GuestDnDTarget object with the GuestDnD manager.
988 *
989 * Currently only one target is supported at a time.
990 *
991 * @returns VBox status code.
992 * @param Target Target to register.
993 */
994int GuestDnD::registerTarget(const ComObjPtr<GuestDnDTarget> &Target)
995{
996 GUESTDND_LOCK();
997
998 Assert(m_lstTgt.size() == 0); /* We only support one target at a time at the moment. */
999 m_lstTgt.push_back(Target);
1000
1001 GUESTDND_UNLOCK();
1002 return VINF_SUCCESS;
1003}
1004
1005/**
1006 * Unregisters a GuestDnDTarget object from the GuestDnD manager.
1007 *
1008 * @returns VBox status code.
1009 * @param Target Target to unregister.
1010 */
1011int GuestDnD::unregisterTarget(const ComObjPtr<GuestDnDTarget> &Target)
1012{
1013 GUESTDND_LOCK();
1014
1015 GuestDnDTgtList::iterator itTgt = std::find(m_lstTgt.begin(), m_lstTgt.end(), Target);
1016 if (itTgt != m_lstTgt.end())
1017 m_lstTgt.erase(itTgt);
1018
1019 GUESTDND_UNLOCK();
1020 return VINF_SUCCESS;
1021}
1022
1023/**
1024 * Returns the current number of registered targets.
1025 *
1026 * @returns Current number of registered targets.
1027 */
1028size_t GuestDnD::getTargetCount(void)
1029{
1030 GUESTDND_LOCK_RET(0);
1031
1032 size_t cTargets = m_lstTgt.size();
1033
1034 GUESTDND_UNLOCK();
1035 return cTargets;
1036}
1037
1038/**
1039 * Static main dispatcher function to handle callbacks from the DnD host service.
1040 *
1041 * @returns VBox status code.
1042 * @param pvExtension Pointer to service extension.
1043 * @param u32Function Callback HGCM message ID.
1044 * @param pvParms Pointer to optional data provided for a particular message. Optional.
1045 * @param cbParms Size (in bytes) of \a pvParms.
1046 */
1047/* static */
1048DECLCALLBACK(int) GuestDnD::notifyDnDDispatcher(void *pvExtension, uint32_t u32Function,
1049 void *pvParms, uint32_t cbParms)
1050{
1051 LogFlowFunc(("pvExtension=%p, u32Function=%RU32, pvParms=%p, cbParms=%RU32\n",
1052 pvExtension, u32Function, pvParms, cbParms));
1053
1054 GuestDnD *pGuestDnD = reinterpret_cast<GuestDnD*>(pvExtension);
1055 AssertPtrReturn(pGuestDnD, VERR_INVALID_POINTER);
1056
1057 /** @todo In case we need to handle multiple guest DnD responses at a time this
1058 * would be the place to lookup and dispatch to those. For the moment we
1059 * only have one response -- simple. */
1060 if (pGuestDnD->m_pState)
1061 return pGuestDnD->m_pState->onDispatch(u32Function, pvParms, cbParms);
1062
1063 return VERR_NOT_SUPPORTED;
1064}
1065
1066/**
1067 * Static helper function to determine whether a format is part of a given MIME list.
1068 *
1069 * @returns \c true if found, \c false if not.
1070 * @param strFormat Format to search for.
1071 * @param lstFormats MIME list to search in.
1072 */
1073/* static */
1074bool GuestDnD::isFormatInFormatList(const com::Utf8Str &strFormat, const GuestDnDMIMEList &lstFormats)
1075{
1076 return std::find(lstFormats.begin(), lstFormats.end(), strFormat) != lstFormats.end();
1077}
1078
1079/**
1080 * Static helper function to create a GuestDnDMIMEList out of a format list string.
1081 *
1082 * @returns MIME list object.
1083 * @param strFormats List of formats to convert.
1084 * @param strSep Separator to use. If not specified, DND_FORMATS_SEPARATOR_STR will be used.
1085 */
1086/* static */
1087GuestDnDMIMEList GuestDnD::toFormatList(const com::Utf8Str &strFormats, const com::Utf8Str &strSep /* = DND_FORMATS_SEPARATOR_STR */)
1088{
1089 GuestDnDMIMEList lstFormats;
1090 RTCList<RTCString> lstFormatsTmp = strFormats.split(strSep);
1091
1092 for (size_t i = 0; i < lstFormatsTmp.size(); i++)
1093 lstFormats.push_back(com::Utf8Str(lstFormatsTmp.at(i)));
1094
1095 return lstFormats;
1096}
1097
1098/**
1099 * Static helper function to create a format list string from a given GuestDnDMIMEList object.
1100 *
1101 * @returns Format list string.
1102 * @param lstFormats GuestDnDMIMEList to convert.
1103 * @param strSep Separator to use between formats.
1104 * Uses DND_FORMATS_SEPARATOR_STR as default.
1105 */
1106/* static */
1107com::Utf8Str GuestDnD::toFormatString(const GuestDnDMIMEList &lstFormats, const com::Utf8Str &strSep /* = DND_FORMATS_SEPARATOR_STR */)
1108{
1109 com::Utf8Str strFormat;
1110 for (size_t i = 0; i < lstFormats.size(); i++)
1111 {
1112 const com::Utf8Str &f = lstFormats.at(i);
1113 strFormat += f + strSep;
1114 }
1115
1116 return strFormat;
1117}
1118
1119/**
1120 * Static helper function to create a filtered GuestDnDMIMEList object from supported and wanted formats.
1121 *
1122 * @returns Filtered MIME list object.
1123 * @param lstFormatsSupported MIME list of supported formats.
1124 * @param lstFormatsWanted MIME list of wanted formats in returned object.
1125 */
1126/* static */
1127GuestDnDMIMEList GuestDnD::toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const GuestDnDMIMEList &lstFormatsWanted)
1128{
1129 GuestDnDMIMEList lstFormats;
1130
1131 for (size_t i = 0; i < lstFormatsWanted.size(); i++)
1132 {
1133 /* Only keep supported format types. */
1134 if (std::find(lstFormatsSupported.begin(),
1135 lstFormatsSupported.end(), lstFormatsWanted.at(i)) != lstFormatsSupported.end())
1136 {
1137 lstFormats.push_back(lstFormatsWanted[i]);
1138 }
1139 }
1140
1141 return lstFormats;
1142}
1143
1144/**
1145 * Static helper function to create a filtered GuestDnDMIMEList object from supported and wanted formats.
1146 *
1147 * @returns Filtered MIME list object.
1148 * @param lstFormatsSupported MIME list of supported formats.
1149 * @param strFormatsWanted Format list string of wanted formats in returned object.
1150 */
1151/* static */
1152GuestDnDMIMEList GuestDnD::toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const com::Utf8Str &strFormatsWanted)
1153{
1154 GuestDnDMIMEList lstFmt;
1155
1156 RTCList<RTCString> lstFormats = strFormatsWanted.split(DND_FORMATS_SEPARATOR_STR);
1157 size_t i = 0;
1158 while (i < lstFormats.size())
1159 {
1160 /* Only keep allowed format types. */
1161 if (std::find(lstFormatsSupported.begin(),
1162 lstFormatsSupported.end(), lstFormats.at(i)) != lstFormatsSupported.end())
1163 {
1164 lstFmt.push_back(lstFormats[i]);
1165 }
1166 i++;
1167 }
1168
1169 return lstFmt;
1170}
1171
1172/**
1173 * Static helper function to convert a Main DnD action an internal DnD action.
1174 *
1175 * @returns Internal DnD action, or VBOX_DND_ACTION_IGNORE if not found / supported.
1176 * @param enmAction Main DnD action to convert.
1177 */
1178/* static */
1179VBOXDNDACTION GuestDnD::toHGCMAction(DnDAction_T enmAction)
1180{
1181 VBOXDNDACTION dndAction = VBOX_DND_ACTION_IGNORE;
1182 switch (enmAction)
1183 {
1184 case DnDAction_Copy:
1185 dndAction = VBOX_DND_ACTION_COPY;
1186 break;
1187 case DnDAction_Move:
1188 dndAction = VBOX_DND_ACTION_MOVE;
1189 break;
1190 case DnDAction_Link:
1191 /* For now it doesn't seems useful to allow a link
1192 action between host & guest. Later? */
1193 case DnDAction_Ignore:
1194 /* Ignored. */
1195 break;
1196 default:
1197 AssertMsgFailed(("Action %RU32 not recognized!\n", enmAction));
1198 break;
1199 }
1200
1201 return dndAction;
1202}
1203
1204/**
1205 * Static helper function to convert a Main DnD default action and allowed Main actions to their
1206 * corresponding internal representations.
1207 *
1208 * @param enmDnDActionDefault Default Main action to convert.
1209 * @param pDnDActionDefault Where to store the converted default action.
1210 * @param vecDnDActionsAllowed Allowed Main actions to convert.
1211 * @param pDnDLstActionsAllowed Where to store the converted allowed actions.
1212 */
1213/* static */
1214void GuestDnD::toHGCMActions(DnDAction_T enmDnDActionDefault,
1215 VBOXDNDACTION *pDnDActionDefault,
1216 const std::vector<DnDAction_T> vecDnDActionsAllowed,
1217 VBOXDNDACTIONLIST *pDnDLstActionsAllowed)
1218{
1219 VBOXDNDACTIONLIST dndLstActionsAllowed = VBOX_DND_ACTION_IGNORE;
1220 VBOXDNDACTION dndActionDefault = toHGCMAction(enmDnDActionDefault);
1221
1222 if (!vecDnDActionsAllowed.empty())
1223 {
1224 /* First convert the allowed actions to a bit array. */
1225 for (size_t i = 0; i < vecDnDActionsAllowed.size(); i++)
1226 dndLstActionsAllowed |= toHGCMAction(vecDnDActionsAllowed[i]);
1227
1228 /*
1229 * If no default action is set (ignoring), try one of the
1230 * set allowed actions, preferring copy, move (in that order).
1231 */
1232 if (isDnDIgnoreAction(dndActionDefault))
1233 {
1234 if (hasDnDCopyAction(dndLstActionsAllowed))
1235 dndActionDefault = VBOX_DND_ACTION_COPY;
1236 else if (hasDnDMoveAction(dndLstActionsAllowed))
1237 dndActionDefault = VBOX_DND_ACTION_MOVE;
1238 }
1239 }
1240
1241 if (pDnDActionDefault)
1242 *pDnDActionDefault = dndActionDefault;
1243 if (pDnDLstActionsAllowed)
1244 *pDnDLstActionsAllowed = dndLstActionsAllowed;
1245}
1246
1247/**
1248 * Static helper function to convert an internal DnD action to its Main representation.
1249 *
1250 * @returns Converted Main DnD action.
1251 * @param dndAction DnD action to convert.
1252 */
1253/* static */
1254DnDAction_T GuestDnD::toMainAction(VBOXDNDACTION dndAction)
1255{
1256 /* For now it doesn't seems useful to allow a
1257 * link action between host & guest. Maybe later! */
1258 return isDnDCopyAction(dndAction) ? DnDAction_Copy
1259 : isDnDMoveAction(dndAction) ? DnDAction_Move
1260 : DnDAction_Ignore;
1261}
1262
1263/**
1264 * Static helper function to convert an internal DnD action list to its Main representation.
1265 *
1266 * @returns Converted Main DnD action list.
1267 * @param dndActionList DnD action list to convert.
1268 */
1269/* static */
1270std::vector<DnDAction_T> GuestDnD::toMainActions(VBOXDNDACTIONLIST dndActionList)
1271{
1272 std::vector<DnDAction_T> vecActions;
1273
1274 /* For now it doesn't seems useful to allow a
1275 * link action between host & guest. Maybe later! */
1276 RTCList<DnDAction_T> lstActions;
1277 if (hasDnDCopyAction(dndActionList))
1278 lstActions.append(DnDAction_Copy);
1279 if (hasDnDMoveAction(dndActionList))
1280 lstActions.append(DnDAction_Move);
1281
1282 for (size_t i = 0; i < lstActions.size(); ++i)
1283 vecActions.push_back(lstActions.at(i));
1284
1285 return vecActions;
1286}
1287
1288/*********************************************************************************************************************************
1289 * GuestDnDBase implementation. *
1290 ********************************************************************************************************************************/
1291
1292GuestDnDBase::GuestDnDBase(VirtualBoxBase *pBase)
1293 : m_pBase(pBase)
1294 , m_fIsPending(false)
1295{
1296 /* Initialize public attributes. */
1297 m_lstFmtSupported = GuestDnDInst()->defaultFormats();
1298}
1299
1300GuestDnDBase::~GuestDnDBase(void)
1301{
1302}
1303
1304/**
1305 * Checks whether a given DnD format is supported or not.
1306 *
1307 * @returns \c true if supported, \c false if not.
1308 * @param aFormat DnD format to check.
1309 */
1310bool GuestDnDBase::i_isFormatSupported(const com::Utf8Str &aFormat) const
1311{
1312 return std::find(m_lstFmtSupported.begin(), m_lstFmtSupported.end(), aFormat) != m_lstFmtSupported.end();
1313}
1314
1315/**
1316 * Returns the currently supported DnD formats.
1317 *
1318 * @returns List of the supported DnD formats.
1319 */
1320const GuestDnDMIMEList &GuestDnDBase::i_getFormats(void) const
1321{
1322 return m_lstFmtSupported;
1323}
1324
1325/**
1326 * Adds DnD formats to the supported formats list.
1327 *
1328 * @returns HRESULT
1329 * @param aFormats List of DnD formats to add.
1330 */
1331HRESULT GuestDnDBase::i_addFormats(const GuestDnDMIMEList &aFormats)
1332{
1333 for (size_t i = 0; i < aFormats.size(); ++i)
1334 {
1335 Utf8Str strFormat = aFormats.at(i);
1336 if (std::find(m_lstFmtSupported.begin(),
1337 m_lstFmtSupported.end(), strFormat) == m_lstFmtSupported.end())
1338 {
1339 m_lstFmtSupported.push_back(strFormat);
1340 }
1341 }
1342
1343 return S_OK;
1344}
1345
1346/**
1347 * Removes DnD formats from tehh supported formats list.
1348 *
1349 * @returns HRESULT
1350 * @param aFormats List of DnD formats to remove.
1351 */
1352HRESULT GuestDnDBase::i_removeFormats(const GuestDnDMIMEList &aFormats)
1353{
1354 for (size_t i = 0; i < aFormats.size(); ++i)
1355 {
1356 Utf8Str strFormat = aFormats.at(i);
1357 GuestDnDMIMEList::iterator itFormat = std::find(m_lstFmtSupported.begin(),
1358 m_lstFmtSupported.end(), strFormat);
1359 if (itFormat != m_lstFmtSupported.end())
1360 m_lstFmtSupported.erase(itFormat);
1361 }
1362
1363 return S_OK;
1364}
1365
1366/**
1367 * Prints an error in the release log and sets the COM error info.
1368 *
1369 * @returns HRESULT
1370 * @param vrc IPRT-style error code to print in addition.
1371 * Will not be printed if set to a non-error (e.g. VINF _ / VWRN_) code.
1372 * @param pcszMsgFmt Format string.
1373 * @param va Format arguments.
1374 * @note
1375 */
1376HRESULT GuestDnDBase::i_setErrorV(int vrc, const char *pcszMsgFmt, va_list va)
1377{
1378 char *psz = NULL;
1379 if (RTStrAPrintfV(&psz, pcszMsgFmt, va) < 0)
1380 return E_OUTOFMEMORY;
1381 AssertPtrReturn(psz, E_OUTOFMEMORY);
1382
1383 HRESULT hrc;
1384 if (RT_FAILURE(vrc))
1385 {
1386 LogRel(("DnD: Error: %s (%Rrc)\n", psz, vrc));
1387 hrc = m_pBase->setErrorBoth(VBOX_E_DND_ERROR, vrc, "DnD: Error: %s (%Rrc)", psz, vrc);
1388 }
1389 else
1390 {
1391 LogRel(("DnD: Error: %s\n", psz));
1392 hrc = m_pBase->setErrorBoth(VBOX_E_DND_ERROR, vrc, "DnD: Error: %s", psz);
1393 }
1394
1395 RTStrFree(psz);
1396 return hrc;
1397}
1398
1399/**
1400 * Prints an error in the release log and sets the COM error info.
1401 *
1402 * @returns HRESULT
1403 * @param vrc IPRT-style error code to print in addition.
1404 * Will not be printed if set to a non-error (e.g. VINF _ / VWRN_) code.
1405 * @param pcszMsgFmt Format string.
1406 * @param ... Format arguments.
1407 * @note
1408 */
1409HRESULT GuestDnDBase::i_setError(int vrc, const char *pcszMsgFmt, ...)
1410{
1411 va_list va;
1412 va_start(va, pcszMsgFmt);
1413 HRESULT const hrc = i_setErrorV(vrc, pcszMsgFmt, va);
1414 va_end(va);
1415
1416 return hrc;
1417}
1418
1419/**
1420 * Prints an error in the release log, sets the COM error info and calls the object's reset function.
1421 *
1422 * @returns HRESULT
1423 * @param pcszMsgFmt Format string.
1424 * @param va Format arguments.
1425 * @note
1426 */
1427HRESULT GuestDnDBase::i_setErrorAndReset(const char *pcszMsgFmt, ...)
1428{
1429 va_list va;
1430 va_start(va, pcszMsgFmt);
1431 HRESULT const hrc = i_setErrorV(VINF_SUCCESS, pcszMsgFmt, va);
1432 va_end(va);
1433
1434 i_reset();
1435
1436 return hrc;
1437}
1438
1439/**
1440 * Prints an error in the release log, sets the COM error info and calls the object's reset function.
1441 *
1442 * @returns HRESULT
1443 * @param vrc IPRT-style error code to print in addition.
1444 * Will not be printed if set to a non-error (e.g. VINF _ / VWRN_) code.
1445 * @param pcszMsgFmt Format string.
1446 * @param ... Format arguments.
1447 * @note
1448 */
1449HRESULT GuestDnDBase::i_setErrorAndReset(int vrc, const char *pcszMsgFmt, ...)
1450{
1451 va_list va;
1452 va_start(va, pcszMsgFmt);
1453 HRESULT const hrc = i_setErrorV(vrc, pcszMsgFmt, va);
1454 va_end(va);
1455
1456 i_reset();
1457
1458 return hrc;
1459}
1460
1461/**
1462 * Adds a new guest DnD message to the internal message queue.
1463 *
1464 * @returns VBox status code.
1465 * @param pMsg Pointer to message to add.
1466 */
1467int GuestDnDBase::msgQueueAdd(GuestDnDMsg *pMsg)
1468{
1469 m_DataBase.lstMsgOut.push_back(pMsg);
1470 return VINF_SUCCESS;
1471}
1472
1473/**
1474 * Returns the next guest DnD message in the internal message queue (FIFO).
1475 *
1476 * @returns Pointer to guest DnD message, or NULL if none found.
1477 */
1478GuestDnDMsg *GuestDnDBase::msgQueueGetNext(void)
1479{
1480 if (m_DataBase.lstMsgOut.empty())
1481 return NULL;
1482 return m_DataBase.lstMsgOut.front();
1483}
1484
1485/**
1486 * Removes the next guest DnD message from the internal message queue.
1487 */
1488void GuestDnDBase::msgQueueRemoveNext(void)
1489{
1490 if (!m_DataBase.lstMsgOut.empty())
1491 {
1492 GuestDnDMsg *pMsg = m_DataBase.lstMsgOut.front();
1493 if (pMsg)
1494 delete pMsg;
1495 m_DataBase.lstMsgOut.pop_front();
1496 }
1497}
1498
1499/**
1500 * Clears the internal message queue.
1501 */
1502void GuestDnDBase::msgQueueClear(void)
1503{
1504 LogFlowFunc(("cMsg=%zu\n", m_DataBase.lstMsgOut.size()));
1505
1506 GuestDnDMsgList::iterator itMsg = m_DataBase.lstMsgOut.begin();
1507 while (itMsg != m_DataBase.lstMsgOut.end())
1508 {
1509 GuestDnDMsg *pMsg = *itMsg;
1510 if (pMsg)
1511 delete pMsg;
1512
1513 itMsg++;
1514 }
1515
1516 m_DataBase.lstMsgOut.clear();
1517}
1518
1519/**
1520 * Sends a request to the guest side to cancel the current DnD operation.
1521 *
1522 * @returns VBox status code.
1523 */
1524int GuestDnDBase::sendCancel(void)
1525{
1526 GuestDnDMsg Msg;
1527 Msg.setType(HOST_DND_FN_CANCEL);
1528 if (m_pState->m_uProtocolVersion >= 3)
1529 Msg.appendUInt32(0); /** @todo ContextID not used yet. */
1530
1531 LogRel2(("DnD: Cancelling operation on guest ...\n"));
1532
1533 int vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
1534 if (RT_FAILURE(vrc))
1535 LogRel(("DnD: Cancelling operation on guest failed with %Rrc\n", vrc));
1536
1537 return vrc;
1538}
1539
1540/**
1541 * Helper function to update the progress based on given a GuestDnDData object.
1542 *
1543 * @returns VBox status code.
1544 * @param pData GuestDnDData object to use for accounting.
1545 * @param pState Guest state to update its progress object for.
1546 * @param cbDataAdd By how much data (in bytes) to update the progress.
1547 */
1548int GuestDnDBase::updateProgress(GuestDnDData *pData, GuestDnDState *pState,
1549 size_t cbDataAdd /* = 0 */)
1550{
1551 AssertPtrReturn(pData, VERR_INVALID_POINTER);
1552 AssertPtrReturn(pState, VERR_INVALID_POINTER);
1553 /* cbDataAdd is optional. */
1554
1555 LogFlowFunc(("cbExtra=%zu, cbProcessed=%zu, cbRemaining=%zu, cbDataAdd=%zu\n",
1556 pData->cbExtra, pData->cbProcessed, pData->getRemaining(), cbDataAdd));
1557
1558 if (!cbDataAdd) /* Only update if something really changes. */
1559 return VINF_SUCCESS;
1560
1561 pData->addProcessed(cbDataAdd);
1562
1563 const uint8_t uPercent = pData->getPercentComplete();
1564
1565 LogRel2(("DnD: Transfer %RU8%% complete\n", uPercent));
1566
1567 int vrc = pState->setProgress(uPercent, pData->isComplete() ? DND_PROGRESS_COMPLETE : DND_PROGRESS_RUNNING);
1568 LogFlowFuncLeaveRC(vrc);
1569 return vrc;
1570}
1571
1572/**
1573 * Waits for a specific guest callback event to get signalled.
1574 *
1575 * @returns VBox status code. Will return VERR_CANCELLED if the user has cancelled the progress object.
1576 * @param pEvent Callback event to wait for.
1577 * @param pState Guest state to update.
1578 * @param msTimeout Timeout (in ms) to wait.
1579 */
1580int GuestDnDBase::waitForEvent(GuestDnDCallbackEvent *pEvent, GuestDnDState *pState, RTMSINTERVAL msTimeout)
1581{
1582 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1583 AssertPtrReturn(pState, VERR_INVALID_POINTER);
1584
1585 int vrc;
1586
1587 LogFlowFunc(("msTimeout=%RU32\n", msTimeout));
1588
1589 uint64_t tsStart = RTTimeMilliTS();
1590 do
1591 {
1592 /*
1593 * Wait until our desired callback triggered the
1594 * wait event. As we don't want to block if the guest does not
1595 * respond, do busy waiting here.
1596 */
1597 vrc = pEvent->Wait(500 /* ms */);
1598 if (RT_SUCCESS(vrc))
1599 {
1600 vrc = pEvent->Result();
1601 LogFlowFunc(("Callback done, result is %Rrc\n", vrc));
1602 break;
1603 }
1604 if (vrc == VERR_TIMEOUT) /* Continue waiting. */
1605 vrc = VINF_SUCCESS;
1606
1607 if ( msTimeout != RT_INDEFINITE_WAIT
1608 && RTTimeMilliTS() - tsStart > msTimeout)
1609 {
1610 vrc = VERR_TIMEOUT;
1611 LogRel2(("DnD: Error: Guest did not respond within time\n"));
1612 }
1613 else if (pState->isProgressCanceled())
1614 {
1615 LogRel2(("DnD: Operation was canceled by user\n"));
1616 vrc = VERR_CANCELLED;
1617 }
1618
1619 } while (RT_SUCCESS(vrc));
1620
1621 LogFlowFuncLeaveRC(vrc);
1622 return vrc;
1623}
1624
1625#endif /* VBOX_WITH_DRAG_AND_DROP */
1626
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