VirtualBox

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

Last change on this file since 100842 was 98286, checked in by vboxsync, 23 months ago

Main/src-client: doxygen. bugref:10223

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 53.9 KB
Line 
1/* $Id: GuestDnDPrivate.cpp 98286 2023-01-24 13:15:30Z 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 hrc = m_pProgress->i_notifyComplete(VBOX_E_DND_ERROR, COM_IIDOF(IGuest),
537 m_pParent->getComponentName(), strMsg.c_str());
538 break;
539 }
540
541 case DragAndDropSvc::DND_PROGRESS_CANCELLED:
542 {
543 LogRel2(("DnD: Guest cancelled operation\n"));
544
545 if (!fCanceled)
546 {
547 hrc = m_pProgress->Cancel();
548 AssertComRC(hrc);
549 }
550
551 if (!fCompleted)
552 {
553 hrc = m_pProgress->i_notifyComplete(S_OK);
554 AssertComRC(hrc);
555 }
556 break;
557 }
558
559 case DragAndDropSvc::DND_PROGRESS_RUNNING:
560 RT_FALL_THROUGH();
561 case DragAndDropSvc::DND_PROGRESS_COMPLETE:
562 {
563 LogRel2(("DnD: Guest reporting running/completion status with %u%%\n", uPercentage));
564
565 if ( !fCompleted
566 && !fCanceled)
567 {
568 hrc = m_pProgress->SetCurrentOperationProgress(uPercentage);
569 AssertComRCReturn(hrc, VERR_COM_UNEXPECTED);
570 if ( uStatus == DragAndDropSvc::DND_PROGRESS_COMPLETE
571 || uPercentage >= 100)
572 {
573 hrc = m_pProgress->i_notifyComplete(S_OK);
574 AssertComRCReturn(hrc, VERR_COM_UNEXPECTED);
575 }
576 }
577 break;
578 }
579
580 default:
581 break;
582 }
583
584 LogFlowFuncLeaveRC(vrc);
585 return vrc;
586}
587
588/**
589 * Dispatching function for handling the host service service callback.
590 *
591 * @returns VBox status code.
592 * @param u32Function HGCM message ID to handle.
593 * @param pvParms Pointer to optional data provided for a particular message. Optional.
594 * @param cbParms Size (in bytes) of \a pvParms.
595 */
596int GuestDnDState::onDispatch(uint32_t u32Function, void *pvParms, uint32_t cbParms)
597{
598 LogFlowFunc(("u32Function=%RU32, pvParms=%p, cbParms=%RU32\n", u32Function, pvParms, cbParms));
599
600 int vrc = VERR_WRONG_ORDER; /* Play safe. */
601
602 /* Whether or not to try calling host-installed callbacks after successfully processing the message. */
603 bool fTryCallbacks = false;
604
605 switch (u32Function)
606 {
607 case DragAndDropSvc::GUEST_DND_FN_CONNECT:
608 {
609 DragAndDropSvc::PVBOXDNDCBCONNECTDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBCONNECTDATA>(pvParms);
610 AssertPtr(pCBData);
611 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBCONNECTDATA) == cbParms, VERR_INVALID_PARAMETER);
612 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_CONNECT == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
613
614 m_uProtocolVersion = pCBData->uProtocolVersion;
615 /** @todo Handle flags. */
616
617 LogThisFunc(("Client connected, using protocol v%RU32\n", m_uProtocolVersion));
618
619 vrc = VINF_SUCCESS;
620 break;
621 }
622
623 case DragAndDropSvc::GUEST_DND_FN_REPORT_FEATURES:
624 {
625 DragAndDropSvc::PVBOXDNDCBREPORTFEATURESDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBREPORTFEATURESDATA>(pvParms);
626 AssertPtr(pCBData);
627 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBREPORTFEATURESDATA) == cbParms, VERR_INVALID_PARAMETER);
628 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_REPORT_FEATURES == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
629
630 m_fGuestFeatures0 = pCBData->fGuestFeatures0;
631
632 LogThisFunc(("Client reported features: %#RX64\n", m_fGuestFeatures0));
633
634 vrc = VINF_SUCCESS;
635 break;
636 }
637
638 /* Note: GUEST_DND_FN_EVT_ERROR is handled in either the state's default callback or in specific
639 * (overriden) callbacks (e.g. GuestDnDSendCtx / GuestDnDRecvCtx). */
640
641 case DragAndDropSvc::GUEST_DND_FN_DISCONNECT:
642 {
643 LogThisFunc(("Client disconnected\n"));
644 vrc = setProgress(100, DND_PROGRESS_CANCELLED, VINF_SUCCESS);
645 break;
646 }
647
648 case DragAndDropSvc::GUEST_DND_FN_HG_ACK_OP:
649 {
650 DragAndDropSvc::PVBOXDNDCBHGACKOPDATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGACKOPDATA>(pvParms);
651 AssertPtr(pCBData);
652 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGACKOPDATA) == cbParms, VERR_INVALID_PARAMETER);
653 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_ACK_OP == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
654
655 LogRel2(("DnD: Guest responded with action '%s' for host->guest drag event\n", DnDActionToStr(pCBData->uAction)));
656
657 setActionDefault(pCBData->uAction);
658 vrc = notifyAboutGuestResponse();
659 break;
660 }
661
662 case DragAndDropSvc::GUEST_DND_FN_HG_REQ_DATA:
663 {
664 DragAndDropSvc::PVBOXDNDCBHGREQDATADATA pCBData = reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGREQDATADATA>(pvParms);
665 AssertPtr(pCBData);
666 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGREQDATADATA) == cbParms, VERR_INVALID_PARAMETER);
667 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_REQ_DATA == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
668
669 if ( pCBData->cbFormat == 0
670 || pCBData->cbFormat > _64K /** @todo Make this configurable? */
671 || pCBData->pszFormat == NULL)
672 vrc = VERR_INVALID_PARAMETER;
673 else if (!RTStrIsValidEncoding(pCBData->pszFormat))
674 vrc = VERR_INVALID_PARAMETER;
675 else
676 {
677 setFormats(GuestDnD::toFormatList(pCBData->pszFormat));
678 vrc = VINF_SUCCESS;
679 }
680
681 int vrc2 = notifyAboutGuestResponse();
682 if (RT_SUCCESS(vrc))
683 vrc = vrc2;
684 break;
685 }
686
687 case DragAndDropSvc::GUEST_DND_FN_HG_EVT_PROGRESS:
688 {
689 DragAndDropSvc::PVBOXDNDCBHGEVTPROGRESSDATA pCBData =
690 reinterpret_cast<DragAndDropSvc::PVBOXDNDCBHGEVTPROGRESSDATA>(pvParms);
691 AssertPtr(pCBData);
692 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBHGEVTPROGRESSDATA) == cbParms, VERR_INVALID_PARAMETER);
693 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_HG_EVT_PROGRESS == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
694
695 vrc = setProgress(pCBData->uPercentage, pCBData->uStatus, pCBData->rc);
696 if (RT_SUCCESS(vrc))
697 vrc = notifyAboutGuestResponse(pCBData->rc);
698 break;
699 }
700#ifdef VBOX_WITH_DRAG_AND_DROP_GH
701 case DragAndDropSvc::GUEST_DND_FN_GH_ACK_PENDING:
702 {
703 DragAndDropSvc::PVBOXDNDCBGHACKPENDINGDATA pCBData =
704 reinterpret_cast<DragAndDropSvc::PVBOXDNDCBGHACKPENDINGDATA>(pvParms);
705 AssertPtr(pCBData);
706 AssertReturn(sizeof(DragAndDropSvc::VBOXDNDCBGHACKPENDINGDATA) == cbParms, VERR_INVALID_PARAMETER);
707 AssertReturn(DragAndDropSvc::CB_MAGIC_DND_GH_ACK_PENDING == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);
708
709 LogRel2(("DnD: Guest responded with pending action '%s' (%RU32 bytes format data) to guest->host drag event\n",
710 DnDActionToStr(pCBData->uDefAction), pCBData->cbFormat));
711
712 if ( pCBData->cbFormat == 0
713 || pCBData->cbFormat > _64K /** @todo Make the maximum size configurable? */
714 || pCBData->pszFormat == NULL)
715 vrc = VERR_INVALID_PARAMETER;
716 else if (!RTStrIsValidEncoding(pCBData->pszFormat))
717 vrc = VERR_INVALID_PARAMETER;
718 else
719 {
720 setFormats (GuestDnD::toFormatList(pCBData->pszFormat));
721 setActionDefault (pCBData->uDefAction);
722 setActionsAllowed(pCBData->uAllActions);
723
724 vrc = VINF_SUCCESS;
725 }
726
727 int vrc2 = notifyAboutGuestResponse();
728 if (RT_SUCCESS(vrc))
729 vrc = vrc2;
730 break;
731 }
732#endif /* VBOX_WITH_DRAG_AND_DROP_GH */
733 default:
734 /* * Try if the event is covered by a registered callback. */
735 fTryCallbacks = true;
736 break;
737 }
738
739 /*
740 * Try the host's installed callbacks (if any).
741 */
742 if (fTryCallbacks)
743 {
744 GuestDnDCallbackMap::const_iterator it = m_mapCallbacks.find(u32Function);
745 if (it != m_mapCallbacks.end())
746 {
747 AssertPtr(it->second.pfnCallback);
748 vrc = it->second.pfnCallback(u32Function, pvParms, cbParms, it->second.pvUser);
749 }
750 else
751 {
752 /* Invoke the default callback handler in case we don't have any registered callback above. */
753 vrc = i_defaultCallback(u32Function, pvParms, cbParms, this /* pvUser */);
754 }
755 }
756
757 LogFlowFunc(("Returning vrc=%Rrc\n", vrc));
758 return vrc;
759}
760
761/**
762 * Helper function to query the internal progress object to an IProgress interface.
763 *
764 * @returns HRESULT
765 * @param ppProgress Where to query the progress object to.
766 */
767HRESULT GuestDnDState::queryProgressTo(IProgress **ppProgress)
768{
769 return m_pProgress.queryInterfaceTo(ppProgress);
770}
771
772/**
773 * Waits for a guest response to happen, extended version.
774 *
775 * @returns VBox status code.
776 * @retval VERR_TIMEOUT when waiting has timed out.
777 * @retval VERR_DND_GUEST_ERROR on an error reported back from the guest.
778 * @param msTimeout Timeout (in ms) for waiting. Optional, waits 3000 ms if not specified.
779 * @param pvrcGuest Where to return the guest error when
780 * VERR_DND_GUEST_ERROR is returned. Optional.
781 */
782int GuestDnDState::waitForGuestResponseEx(RTMSINTERVAL msTimeout /* = 3000 */, int *pvrcGuest /* = NULL */)
783{
784 int vrc = RTSemEventWait(m_EventSem, msTimeout);
785 if (RT_SUCCESS(vrc))
786 {
787 if (RT_FAILURE(m_vrcGuest))
788 vrc = VERR_DND_GUEST_ERROR;
789 if (pvrcGuest)
790 *pvrcGuest = m_vrcGuest;
791 }
792 return vrc;
793}
794
795/**
796 * Waits for a guest response to happen.
797 *
798 * @returns VBox status code.
799 * @retval VERR_TIMEOUT when waiting has timed out.
800 * @retval VERR_DND_GUEST_ERROR on an error reported back from the guest.
801 * @param pvrcGuest Where to return the guest error when
802 * VERR_DND_GUEST_ERROR is returned. Optional.
803 *
804 * @note Uses the default timeout of 3000 ms.
805 */
806int GuestDnDState::waitForGuestResponse(int *pvrcGuest /* = NULL */)
807{
808 return waitForGuestResponseEx(3000 /* ms */, pvrcGuest);
809}
810
811/*********************************************************************************************************************************
812 * GuestDnD implementation. *
813 ********************************************************************************************************************************/
814
815/** Static (Singleton) instance of the GuestDnD object. */
816GuestDnD* GuestDnD::s_pInstance = NULL;
817
818GuestDnD::GuestDnD(const ComObjPtr<Guest> &pGuest)
819 : m_pGuest(pGuest)
820 , m_cTransfersPending(0)
821{
822 LogFlowFuncEnter();
823
824 try
825 {
826 m_pState = new GuestDnDState(pGuest);
827 }
828 catch (std::bad_alloc &)
829 {
830 throw VERR_NO_MEMORY;
831 }
832
833 int vrc = RTCritSectInit(&m_CritSect);
834 if (RT_FAILURE(vrc))
835 throw vrc;
836
837 /* List of supported default MIME types. */
838 LogRel2(("DnD: Supported default host formats:\n"));
839 const com::Utf8Str arrEntries[] = { VBOX_DND_FORMATS_DEFAULT };
840 for (size_t i = 0; i < RT_ELEMENTS(arrEntries); i++)
841 {
842 m_strDefaultFormats.push_back(arrEntries[i]);
843 LogRel2(("DnD: \t%s\n", arrEntries[i].c_str()));
844 }
845}
846
847GuestDnD::~GuestDnD(void)
848{
849 LogFlowFuncEnter();
850
851 Assert(m_cTransfersPending == 0); /* Sanity. */
852
853 RTCritSectDelete(&m_CritSect);
854
855 if (m_pState)
856 delete m_pState;
857}
858
859/**
860 * Adjusts coordinations to a given screen.
861 *
862 * @returns HRESULT
863 * @param uScreenId ID of screen to adjust coordinates to.
864 * @param puX Pointer to X coordinate to adjust. Will return the adjusted value on success.
865 * @param puY Pointer to Y coordinate to adjust. Will return the adjusted value on success.
866 */
867HRESULT GuestDnD::adjustScreenCoordinates(ULONG uScreenId, ULONG *puX, ULONG *puY) const
868{
869 /** @todo r=andy Save the current screen's shifting coordinates to speed things up.
870 * Only query for new offsets when the screen ID or the screen's resolution has changed. */
871
872 /* For multi-monitor support we need to add shift values to the coordinates
873 * (depending on the screen number). */
874 ComObjPtr<Console> pConsole = m_pGuest->i_getConsole();
875 ComPtr<IDisplay> pDisplay;
876 HRESULT hrc = pConsole->COMGETTER(Display)(pDisplay.asOutParam());
877 if (FAILED(hrc))
878 return hrc;
879
880 ULONG dummy;
881 LONG xShift, yShift;
882 GuestMonitorStatus_T monitorStatus;
883 hrc = pDisplay->GetScreenResolution(uScreenId, &dummy, &dummy, &dummy, &xShift, &yShift, &monitorStatus);
884 if (FAILED(hrc))
885 return hrc;
886
887 if (puX)
888 *puX += xShift;
889 if (puY)
890 *puY += yShift;
891
892 LogFlowFunc(("uScreenId=%RU32, x=%RU32, y=%RU32\n", uScreenId, puX ? *puX : 0, puY ? *puY : 0));
893 return S_OK;
894}
895
896/**
897 * Returns a DnD guest state.
898 *
899 * @returns Pointer to DnD guest state, or NULL if not found / invalid.
900 * @param uID ID of DnD guest state to return.
901 */
902GuestDnDState *GuestDnD::getState(uint32_t uID /* = 0 */) const
903{
904 AssertMsgReturn(uID == 0, ("Only one state (0) is supported at the moment\n"), NULL);
905
906 return m_pState;
907}
908
909/**
910 * Sends a (blocking) message to the host side of the host service.
911 *
912 * @returns VBox status code.
913 * @param u32Function HGCM message ID to send.
914 * @param cParms Number of parameters to send.
915 * @param paParms Array of parameters to send. Must match \c cParms.
916 */
917int GuestDnD::hostCall(uint32_t u32Function, uint32_t cParms, PVBOXHGCMSVCPARM paParms) const
918{
919 Assert(!m_pGuest.isNull());
920 ComObjPtr<Console> pConsole = m_pGuest->i_getConsole();
921
922 /* Forward the information to the VMM device. */
923 Assert(!pConsole.isNull());
924 VMMDev *pVMMDev = pConsole->i_getVMMDev();
925 if (!pVMMDev)
926 return VERR_COM_OBJECT_NOT_FOUND;
927
928 return pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", u32Function, cParms, paParms);
929}
930
931/**
932 * Registers a GuestDnDSource object with the GuestDnD manager.
933 *
934 * Currently only one source is supported at a time.
935 *
936 * @returns VBox status code.
937 * @param Source Source to register.
938 */
939int GuestDnD::registerSource(const ComObjPtr<GuestDnDSource> &Source)
940{
941 GUESTDND_LOCK();
942
943 Assert(m_lstSrc.size() == 0); /* We only support one source at a time at the moment. */
944 m_lstSrc.push_back(Source);
945
946 GUESTDND_UNLOCK();
947 return VINF_SUCCESS;
948}
949
950/**
951 * Unregisters a GuestDnDSource object from the GuestDnD manager.
952 *
953 * @returns VBox status code.
954 * @param Source Source to unregister.
955 */
956int GuestDnD::unregisterSource(const ComObjPtr<GuestDnDSource> &Source)
957{
958 GUESTDND_LOCK();
959
960 GuestDnDSrcList::iterator itSrc = std::find(m_lstSrc.begin(), m_lstSrc.end(), Source);
961 if (itSrc != m_lstSrc.end())
962 m_lstSrc.erase(itSrc);
963
964 GUESTDND_UNLOCK();
965 return VINF_SUCCESS;
966}
967
968/**
969 * Returns the current number of registered sources.
970 *
971 * @returns Current number of registered sources.
972 */
973size_t GuestDnD::getSourceCount(void)
974{
975 GUESTDND_LOCK_RET(0);
976
977 size_t cSources = m_lstSrc.size();
978
979 GUESTDND_UNLOCK();
980 return cSources;
981}
982
983/**
984 * Registers a GuestDnDTarget object with the GuestDnD manager.
985 *
986 * Currently only one target is supported at a time.
987 *
988 * @returns VBox status code.
989 * @param Target Target to register.
990 */
991int GuestDnD::registerTarget(const ComObjPtr<GuestDnDTarget> &Target)
992{
993 GUESTDND_LOCK();
994
995 Assert(m_lstTgt.size() == 0); /* We only support one target at a time at the moment. */
996 m_lstTgt.push_back(Target);
997
998 GUESTDND_UNLOCK();
999 return VINF_SUCCESS;
1000}
1001
1002/**
1003 * Unregisters a GuestDnDTarget object from the GuestDnD manager.
1004 *
1005 * @returns VBox status code.
1006 * @param Target Target to unregister.
1007 */
1008int GuestDnD::unregisterTarget(const ComObjPtr<GuestDnDTarget> &Target)
1009{
1010 GUESTDND_LOCK();
1011
1012 GuestDnDTgtList::iterator itTgt = std::find(m_lstTgt.begin(), m_lstTgt.end(), Target);
1013 if (itTgt != m_lstTgt.end())
1014 m_lstTgt.erase(itTgt);
1015
1016 GUESTDND_UNLOCK();
1017 return VINF_SUCCESS;
1018}
1019
1020/**
1021 * Returns the current number of registered targets.
1022 *
1023 * @returns Current number of registered targets.
1024 */
1025size_t GuestDnD::getTargetCount(void)
1026{
1027 GUESTDND_LOCK_RET(0);
1028
1029 size_t cTargets = m_lstTgt.size();
1030
1031 GUESTDND_UNLOCK();
1032 return cTargets;
1033}
1034
1035/**
1036 * Static main dispatcher function to handle callbacks from the DnD host service.
1037 *
1038 * @returns VBox status code.
1039 * @param pvExtension Pointer to service extension.
1040 * @param u32Function Callback HGCM message ID.
1041 * @param pvParms Pointer to optional data provided for a particular message. Optional.
1042 * @param cbParms Size (in bytes) of \a pvParms.
1043 */
1044/* static */
1045DECLCALLBACK(int) GuestDnD::notifyDnDDispatcher(void *pvExtension, uint32_t u32Function,
1046 void *pvParms, uint32_t cbParms)
1047{
1048 LogFlowFunc(("pvExtension=%p, u32Function=%RU32, pvParms=%p, cbParms=%RU32\n",
1049 pvExtension, u32Function, pvParms, cbParms));
1050
1051 GuestDnD *pGuestDnD = reinterpret_cast<GuestDnD*>(pvExtension);
1052 AssertPtrReturn(pGuestDnD, VERR_INVALID_POINTER);
1053
1054 /** @todo In case we need to handle multiple guest DnD responses at a time this
1055 * would be the place to lookup and dispatch to those. For the moment we
1056 * only have one response -- simple. */
1057 if (pGuestDnD->m_pState)
1058 return pGuestDnD->m_pState->onDispatch(u32Function, pvParms, cbParms);
1059
1060 return VERR_NOT_SUPPORTED;
1061}
1062
1063/**
1064 * Static helper function to determine whether a format is part of a given MIME list.
1065 *
1066 * @returns \c true if found, \c false if not.
1067 * @param strFormat Format to search for.
1068 * @param lstFormats MIME list to search in.
1069 */
1070/* static */
1071bool GuestDnD::isFormatInFormatList(const com::Utf8Str &strFormat, const GuestDnDMIMEList &lstFormats)
1072{
1073 return std::find(lstFormats.begin(), lstFormats.end(), strFormat) != lstFormats.end();
1074}
1075
1076/**
1077 * Static helper function to create a GuestDnDMIMEList out of a format list string.
1078 *
1079 * @returns MIME list object.
1080 * @param strFormats List of formats to convert.
1081 * @param strSep Separator to use. If not specified, DND_FORMATS_SEPARATOR_STR will be used.
1082 */
1083/* static */
1084GuestDnDMIMEList GuestDnD::toFormatList(const com::Utf8Str &strFormats, const com::Utf8Str &strSep /* = DND_FORMATS_SEPARATOR_STR */)
1085{
1086 GuestDnDMIMEList lstFormats;
1087 RTCList<RTCString> lstFormatsTmp = strFormats.split(strSep);
1088
1089 for (size_t i = 0; i < lstFormatsTmp.size(); i++)
1090 lstFormats.push_back(com::Utf8Str(lstFormatsTmp.at(i)));
1091
1092 return lstFormats;
1093}
1094
1095/**
1096 * Static helper function to create a format list string from a given GuestDnDMIMEList object.
1097 *
1098 * @returns Format list string.
1099 * @param lstFormats GuestDnDMIMEList to convert.
1100 * @param strSep Separator to use between formats.
1101 * Uses DND_FORMATS_SEPARATOR_STR as default.
1102 */
1103/* static */
1104com::Utf8Str GuestDnD::toFormatString(const GuestDnDMIMEList &lstFormats, const com::Utf8Str &strSep /* = DND_FORMATS_SEPARATOR_STR */)
1105{
1106 com::Utf8Str strFormat;
1107 for (size_t i = 0; i < lstFormats.size(); i++)
1108 {
1109 const com::Utf8Str &f = lstFormats.at(i);
1110 strFormat += f + strSep;
1111 }
1112
1113 return strFormat;
1114}
1115
1116/**
1117 * Static helper function to create a filtered GuestDnDMIMEList object from supported and wanted formats.
1118 *
1119 * @returns Filtered MIME list object.
1120 * @param lstFormatsSupported MIME list of supported formats.
1121 * @param lstFormatsWanted MIME list of wanted formats in returned object.
1122 */
1123/* static */
1124GuestDnDMIMEList GuestDnD::toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const GuestDnDMIMEList &lstFormatsWanted)
1125{
1126 GuestDnDMIMEList lstFormats;
1127
1128 for (size_t i = 0; i < lstFormatsWanted.size(); i++)
1129 {
1130 /* Only keep supported format types. */
1131 if (std::find(lstFormatsSupported.begin(),
1132 lstFormatsSupported.end(), lstFormatsWanted.at(i)) != lstFormatsSupported.end())
1133 {
1134 lstFormats.push_back(lstFormatsWanted[i]);
1135 }
1136 }
1137
1138 return lstFormats;
1139}
1140
1141/**
1142 * Static helper function to create a filtered GuestDnDMIMEList object from supported and wanted formats.
1143 *
1144 * @returns Filtered MIME list object.
1145 * @param lstFormatsSupported MIME list of supported formats.
1146 * @param strFormatsWanted Format list string of wanted formats in returned object.
1147 */
1148/* static */
1149GuestDnDMIMEList GuestDnD::toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const com::Utf8Str &strFormatsWanted)
1150{
1151 GuestDnDMIMEList lstFmt;
1152
1153 RTCList<RTCString> lstFormats = strFormatsWanted.split(DND_FORMATS_SEPARATOR_STR);
1154 size_t i = 0;
1155 while (i < lstFormats.size())
1156 {
1157 /* Only keep allowed format types. */
1158 if (std::find(lstFormatsSupported.begin(),
1159 lstFormatsSupported.end(), lstFormats.at(i)) != lstFormatsSupported.end())
1160 {
1161 lstFmt.push_back(lstFormats[i]);
1162 }
1163 i++;
1164 }
1165
1166 return lstFmt;
1167}
1168
1169/**
1170 * Static helper function to convert a Main DnD action an internal DnD action.
1171 *
1172 * @returns Internal DnD action, or VBOX_DND_ACTION_IGNORE if not found / supported.
1173 * @param enmAction Main DnD action to convert.
1174 */
1175/* static */
1176VBOXDNDACTION GuestDnD::toHGCMAction(DnDAction_T enmAction)
1177{
1178 VBOXDNDACTION dndAction = VBOX_DND_ACTION_IGNORE;
1179 switch (enmAction)
1180 {
1181 case DnDAction_Copy:
1182 dndAction = VBOX_DND_ACTION_COPY;
1183 break;
1184 case DnDAction_Move:
1185 dndAction = VBOX_DND_ACTION_MOVE;
1186 break;
1187 case DnDAction_Link:
1188 /* For now it doesn't seems useful to allow a link
1189 action between host & guest. Later? */
1190 case DnDAction_Ignore:
1191 /* Ignored. */
1192 break;
1193 default:
1194 AssertMsgFailed(("Action %RU32 not recognized!\n", enmAction));
1195 break;
1196 }
1197
1198 return dndAction;
1199}
1200
1201/**
1202 * Static helper function to convert a Main DnD default action and allowed Main actions to their
1203 * corresponding internal representations.
1204 *
1205 * @param enmDnDActionDefault Default Main action to convert.
1206 * @param pDnDActionDefault Where to store the converted default action.
1207 * @param vecDnDActionsAllowed Allowed Main actions to convert.
1208 * @param pDnDLstActionsAllowed Where to store the converted allowed actions.
1209 */
1210/* static */
1211void GuestDnD::toHGCMActions(DnDAction_T enmDnDActionDefault,
1212 VBOXDNDACTION *pDnDActionDefault,
1213 const std::vector<DnDAction_T> vecDnDActionsAllowed,
1214 VBOXDNDACTIONLIST *pDnDLstActionsAllowed)
1215{
1216 VBOXDNDACTIONLIST dndLstActionsAllowed = VBOX_DND_ACTION_IGNORE;
1217 VBOXDNDACTION dndActionDefault = toHGCMAction(enmDnDActionDefault);
1218
1219 if (!vecDnDActionsAllowed.empty())
1220 {
1221 /* First convert the allowed actions to a bit array. */
1222 for (size_t i = 0; i < vecDnDActionsAllowed.size(); i++)
1223 dndLstActionsAllowed |= toHGCMAction(vecDnDActionsAllowed[i]);
1224
1225 /*
1226 * If no default action is set (ignoring), try one of the
1227 * set allowed actions, preferring copy, move (in that order).
1228 */
1229 if (isDnDIgnoreAction(dndActionDefault))
1230 {
1231 if (hasDnDCopyAction(dndLstActionsAllowed))
1232 dndActionDefault = VBOX_DND_ACTION_COPY;
1233 else if (hasDnDMoveAction(dndLstActionsAllowed))
1234 dndActionDefault = VBOX_DND_ACTION_MOVE;
1235 }
1236 }
1237
1238 if (pDnDActionDefault)
1239 *pDnDActionDefault = dndActionDefault;
1240 if (pDnDLstActionsAllowed)
1241 *pDnDLstActionsAllowed = dndLstActionsAllowed;
1242}
1243
1244/**
1245 * Static helper function to convert an internal DnD action to its Main representation.
1246 *
1247 * @returns Converted Main DnD action.
1248 * @param dndAction DnD action to convert.
1249 */
1250/* static */
1251DnDAction_T GuestDnD::toMainAction(VBOXDNDACTION dndAction)
1252{
1253 /* For now it doesn't seems useful to allow a
1254 * link action between host & guest. Maybe later! */
1255 return isDnDCopyAction(dndAction) ? DnDAction_Copy
1256 : isDnDMoveAction(dndAction) ? DnDAction_Move
1257 : DnDAction_Ignore;
1258}
1259
1260/**
1261 * Static helper function to convert an internal DnD action list to its Main representation.
1262 *
1263 * @returns Converted Main DnD action list.
1264 * @param dndActionList DnD action list to convert.
1265 */
1266/* static */
1267std::vector<DnDAction_T> GuestDnD::toMainActions(VBOXDNDACTIONLIST dndActionList)
1268{
1269 std::vector<DnDAction_T> vecActions;
1270
1271 /* For now it doesn't seems useful to allow a
1272 * link action between host & guest. Maybe later! */
1273 RTCList<DnDAction_T> lstActions;
1274 if (hasDnDCopyAction(dndActionList))
1275 lstActions.append(DnDAction_Copy);
1276 if (hasDnDMoveAction(dndActionList))
1277 lstActions.append(DnDAction_Move);
1278
1279 for (size_t i = 0; i < lstActions.size(); ++i)
1280 vecActions.push_back(lstActions.at(i));
1281
1282 return vecActions;
1283}
1284
1285/*********************************************************************************************************************************
1286 * GuestDnDBase implementation. *
1287 ********************************************************************************************************************************/
1288
1289GuestDnDBase::GuestDnDBase(VirtualBoxBase *pBase)
1290 : m_pBase(pBase)
1291 , m_fIsPending(false)
1292{
1293 /* Initialize public attributes. */
1294 m_lstFmtSupported = GuestDnDInst()->defaultFormats();
1295}
1296
1297GuestDnDBase::~GuestDnDBase(void)
1298{
1299}
1300
1301/**
1302 * Checks whether a given DnD format is supported or not.
1303 *
1304 * @returns \c true if supported, \c false if not.
1305 * @param aFormat DnD format to check.
1306 */
1307bool GuestDnDBase::i_isFormatSupported(const com::Utf8Str &aFormat) const
1308{
1309 return std::find(m_lstFmtSupported.begin(), m_lstFmtSupported.end(), aFormat) != m_lstFmtSupported.end();
1310}
1311
1312/**
1313 * Returns the currently supported DnD formats.
1314 *
1315 * @returns List of the supported DnD formats.
1316 */
1317const GuestDnDMIMEList &GuestDnDBase::i_getFormats(void) const
1318{
1319 return m_lstFmtSupported;
1320}
1321
1322/**
1323 * Adds DnD formats to the supported formats list.
1324 *
1325 * @returns HRESULT
1326 * @param aFormats List of DnD formats to add.
1327 */
1328HRESULT GuestDnDBase::i_addFormats(const GuestDnDMIMEList &aFormats)
1329{
1330 for (size_t i = 0; i < aFormats.size(); ++i)
1331 {
1332 Utf8Str strFormat = aFormats.at(i);
1333 if (std::find(m_lstFmtSupported.begin(),
1334 m_lstFmtSupported.end(), strFormat) == m_lstFmtSupported.end())
1335 {
1336 m_lstFmtSupported.push_back(strFormat);
1337 }
1338 }
1339
1340 return S_OK;
1341}
1342
1343/**
1344 * Removes DnD formats from tehh supported formats list.
1345 *
1346 * @returns HRESULT
1347 * @param aFormats List of DnD formats to remove.
1348 */
1349HRESULT GuestDnDBase::i_removeFormats(const GuestDnDMIMEList &aFormats)
1350{
1351 for (size_t i = 0; i < aFormats.size(); ++i)
1352 {
1353 Utf8Str strFormat = aFormats.at(i);
1354 GuestDnDMIMEList::iterator itFormat = std::find(m_lstFmtSupported.begin(),
1355 m_lstFmtSupported.end(), strFormat);
1356 if (itFormat != m_lstFmtSupported.end())
1357 m_lstFmtSupported.erase(itFormat);
1358 }
1359
1360 return S_OK;
1361}
1362
1363/**
1364 * Prints an error in the release log and sets the COM error info.
1365 *
1366 * @returns HRESULT
1367 * @param vrc IPRT-style error code to print in addition.
1368 * Will not be printed if set to a non-error (e.g. VINF _ / VWRN_) code.
1369 * @param pcszMsgFmt Format string.
1370 * @param va Format arguments.
1371 * @note
1372 */
1373HRESULT GuestDnDBase::i_setErrorV(int vrc, const char *pcszMsgFmt, va_list va)
1374{
1375 char *psz = NULL;
1376 if (RTStrAPrintfV(&psz, pcszMsgFmt, va) < 0)
1377 return E_OUTOFMEMORY;
1378 AssertPtrReturn(psz, E_OUTOFMEMORY);
1379
1380 HRESULT hrc;
1381 if (RT_FAILURE(vrc))
1382 {
1383 LogRel(("DnD: Error: %s (%Rrc)\n", psz, vrc));
1384 hrc = m_pBase->setErrorBoth(VBOX_E_DND_ERROR, vrc, "DnD: Error: %s (%Rrc)", psz, vrc);
1385 }
1386 else
1387 {
1388 LogRel(("DnD: Error: %s\n", psz));
1389 hrc = m_pBase->setErrorBoth(VBOX_E_DND_ERROR, vrc, "DnD: Error: %s", psz);
1390 }
1391
1392 RTStrFree(psz);
1393 return hrc;
1394}
1395
1396/**
1397 * Prints an error in the release log and sets the COM error info.
1398 *
1399 * @returns HRESULT
1400 * @param vrc IPRT-style error code to print in addition.
1401 * Will not be printed if set to a non-error (e.g. VINF _ / VWRN_) code.
1402 * @param pcszMsgFmt Format string.
1403 * @param ... Format arguments.
1404 * @note
1405 */
1406HRESULT GuestDnDBase::i_setError(int vrc, const char *pcszMsgFmt, ...)
1407{
1408 va_list va;
1409 va_start(va, pcszMsgFmt);
1410 HRESULT const hrc = i_setErrorV(vrc, pcszMsgFmt, va);
1411 va_end(va);
1412
1413 return hrc;
1414}
1415
1416/**
1417 * Prints an error in the release log, sets the COM error info and calls the object's reset function.
1418 *
1419 * @returns HRESULT
1420 * @param pcszMsgFmt Format string.
1421 * @param va Format arguments.
1422 * @note
1423 */
1424HRESULT GuestDnDBase::i_setErrorAndReset(const char *pcszMsgFmt, ...)
1425{
1426 va_list va;
1427 va_start(va, pcszMsgFmt);
1428 HRESULT const hrc = i_setErrorV(VINF_SUCCESS, pcszMsgFmt, va);
1429 va_end(va);
1430
1431 i_reset();
1432
1433 return hrc;
1434}
1435
1436/**
1437 * Prints an error in the release log, sets the COM error info and calls the object's reset function.
1438 *
1439 * @returns HRESULT
1440 * @param vrc IPRT-style error code to print in addition.
1441 * Will not be printed if set to a non-error (e.g. VINF _ / VWRN_) code.
1442 * @param pcszMsgFmt Format string.
1443 * @param ... Format arguments.
1444 * @note
1445 */
1446HRESULT GuestDnDBase::i_setErrorAndReset(int vrc, const char *pcszMsgFmt, ...)
1447{
1448 va_list va;
1449 va_start(va, pcszMsgFmt);
1450 HRESULT const hrc = i_setErrorV(vrc, pcszMsgFmt, va);
1451 va_end(va);
1452
1453 i_reset();
1454
1455 return hrc;
1456}
1457
1458/**
1459 * Adds a new guest DnD message to the internal message queue.
1460 *
1461 * @returns VBox status code.
1462 * @param pMsg Pointer to message to add.
1463 */
1464int GuestDnDBase::msgQueueAdd(GuestDnDMsg *pMsg)
1465{
1466 m_DataBase.lstMsgOut.push_back(pMsg);
1467 return VINF_SUCCESS;
1468}
1469
1470/**
1471 * Returns the next guest DnD message in the internal message queue (FIFO).
1472 *
1473 * @returns Pointer to guest DnD message, or NULL if none found.
1474 */
1475GuestDnDMsg *GuestDnDBase::msgQueueGetNext(void)
1476{
1477 if (m_DataBase.lstMsgOut.empty())
1478 return NULL;
1479 return m_DataBase.lstMsgOut.front();
1480}
1481
1482/**
1483 * Removes the next guest DnD message from the internal message queue.
1484 */
1485void GuestDnDBase::msgQueueRemoveNext(void)
1486{
1487 if (!m_DataBase.lstMsgOut.empty())
1488 {
1489 GuestDnDMsg *pMsg = m_DataBase.lstMsgOut.front();
1490 if (pMsg)
1491 delete pMsg;
1492 m_DataBase.lstMsgOut.pop_front();
1493 }
1494}
1495
1496/**
1497 * Clears the internal message queue.
1498 */
1499void GuestDnDBase::msgQueueClear(void)
1500{
1501 LogFlowFunc(("cMsg=%zu\n", m_DataBase.lstMsgOut.size()));
1502
1503 GuestDnDMsgList::iterator itMsg = m_DataBase.lstMsgOut.begin();
1504 while (itMsg != m_DataBase.lstMsgOut.end())
1505 {
1506 GuestDnDMsg *pMsg = *itMsg;
1507 if (pMsg)
1508 delete pMsg;
1509
1510 itMsg++;
1511 }
1512
1513 m_DataBase.lstMsgOut.clear();
1514}
1515
1516/**
1517 * Sends a request to the guest side to cancel the current DnD operation.
1518 *
1519 * @returns VBox status code.
1520 */
1521int GuestDnDBase::sendCancel(void)
1522{
1523 GuestDnDMsg Msg;
1524 Msg.setType(HOST_DND_FN_CANCEL);
1525 if (m_pState->m_uProtocolVersion >= 3)
1526 Msg.appendUInt32(0); /** @todo ContextID not used yet. */
1527
1528 LogRel2(("DnD: Cancelling operation on guest ...\n"));
1529
1530 int vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
1531 if (RT_FAILURE(vrc))
1532 LogRel(("DnD: Cancelling operation on guest failed with %Rrc\n", vrc));
1533
1534 return vrc;
1535}
1536
1537/**
1538 * Helper function to update the progress based on given a GuestDnDData object.
1539 *
1540 * @returns VBox status code.
1541 * @param pData GuestDnDData object to use for accounting.
1542 * @param pState Guest state to update its progress object for.
1543 * @param cbDataAdd By how much data (in bytes) to update the progress.
1544 */
1545int GuestDnDBase::updateProgress(GuestDnDData *pData, GuestDnDState *pState,
1546 size_t cbDataAdd /* = 0 */)
1547{
1548 AssertPtrReturn(pData, VERR_INVALID_POINTER);
1549 AssertPtrReturn(pState, VERR_INVALID_POINTER);
1550 /* cbDataAdd is optional. */
1551
1552 LogFlowFunc(("cbExtra=%zu, cbProcessed=%zu, cbRemaining=%zu, cbDataAdd=%zu\n",
1553 pData->cbExtra, pData->cbProcessed, pData->getRemaining(), cbDataAdd));
1554
1555 if ( !pState
1556 || !cbDataAdd) /* Only update if something really changes. */
1557 return VINF_SUCCESS;
1558
1559 if (cbDataAdd)
1560 pData->addProcessed(cbDataAdd);
1561
1562 const uint8_t uPercent = pData->getPercentComplete();
1563
1564 LogRel2(("DnD: Transfer %RU8%% complete\n", uPercent));
1565
1566 int vrc = pState->setProgress(uPercent, pData->isComplete() ? DND_PROGRESS_COMPLETE : DND_PROGRESS_RUNNING);
1567 LogFlowFuncLeaveRC(vrc);
1568 return vrc;
1569}
1570
1571/**
1572 * Waits for a specific guest callback event to get signalled.
1573 *
1574 * @returns VBox status code. Will return VERR_CANCELLED if the user has cancelled the progress object.
1575 * @param pEvent Callback event to wait for.
1576 * @param pState Guest state to update.
1577 * @param msTimeout Timeout (in ms) to wait.
1578 */
1579int GuestDnDBase::waitForEvent(GuestDnDCallbackEvent *pEvent, GuestDnDState *pState, RTMSINTERVAL msTimeout)
1580{
1581 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1582 AssertPtrReturn(pState, VERR_INVALID_POINTER);
1583
1584 int vrc;
1585
1586 LogFlowFunc(("msTimeout=%RU32\n", msTimeout));
1587
1588 uint64_t tsStart = RTTimeMilliTS();
1589 do
1590 {
1591 /*
1592 * Wait until our desired callback triggered the
1593 * wait event. As we don't want to block if the guest does not
1594 * respond, do busy waiting here.
1595 */
1596 vrc = pEvent->Wait(500 /* ms */);
1597 if (RT_SUCCESS(vrc))
1598 {
1599 vrc = pEvent->Result();
1600 LogFlowFunc(("Callback done, result is %Rrc\n", vrc));
1601 break;
1602 }
1603 if (vrc == VERR_TIMEOUT) /* Continue waiting. */
1604 vrc = VINF_SUCCESS;
1605
1606 if ( msTimeout != RT_INDEFINITE_WAIT
1607 && RTTimeMilliTS() - tsStart > msTimeout)
1608 {
1609 vrc = VERR_TIMEOUT;
1610 LogRel2(("DnD: Error: Guest did not respond within time\n"));
1611 }
1612 else if (pState->isProgressCanceled())
1613 {
1614 LogRel2(("DnD: Operation was canceled by user\n"));
1615 vrc = VERR_CANCELLED;
1616 }
1617
1618 } while (RT_SUCCESS(vrc));
1619
1620 LogFlowFuncLeaveRC(vrc);
1621 return vrc;
1622}
1623
1624#endif /* VBOX_WITH_DRAG_AND_DROP */
1625
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