summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/src-client/GuestDnDTargetImpl.cpp
blob: fa9827531c1daf1d9887dcd980d4661f8cf7b822 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
/* $Id: GuestDnDTargetImpl.cpp $ */
/** @file
 * VBox Console COM Class implementation - Guest drag'n drop target.
 */

/*
 * Copyright (C) 2014-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_GUEST_DND //LOG_GROUP_MAIN_GUESTDNDTARGET
#include "LoggingNew.h"

#include "GuestImpl.h"
#include "GuestDnDTargetImpl.h"
#include "ConsoleImpl.h"

#include "Global.h"
#include "AutoCaller.h"
#include "ThreadTask.h"

#include <algorithm>        /* For std::find(). */

#include <iprt/asm.h>
#include <iprt/file.h>
#include <iprt/dir.h>
#include <iprt/path.h>
#include <iprt/uri.h>
#include <iprt/cpp/utils.h> /* For unconst(). */

#include <VBox/com/array.h>

#include <VBox/GuestHost/DragAndDrop.h>
#include <VBox/HostServices/Service.h>


/**
 * Base class for a target task.
 */
class GuestDnDTargetTask : public ThreadTask
{
public:

    GuestDnDTargetTask(GuestDnDTarget *pTarget)
        : ThreadTask("GenericGuestDnDTargetTask")
        , mTarget(pTarget)
        , mRC(VINF_SUCCESS) { }

    virtual ~GuestDnDTargetTask(void) { }

    /** Returns the overall result of the task. */
    int getRC(void) const { return mRC; }
    /** Returns if the overall result of the task is ok (succeeded) or not. */
    bool isOk(void) const { return RT_SUCCESS(mRC); }

protected:

    /** COM object pointer to the parent (source). */
    const ComObjPtr<GuestDnDTarget>     mTarget;
    /** Overall result of the task. */
    int                                 mRC;
};

/**
 * Task structure for sending data to a target using
 * a worker thread.
 */
class GuestDnDSendDataTask : public GuestDnDTargetTask
{
public:

    GuestDnDSendDataTask(GuestDnDTarget *pTarget, GuestDnDSendCtx *pCtx)
        : GuestDnDTargetTask(pTarget),
          mpCtx(pCtx)
    {
        m_strTaskName = "dndTgtSndData";
    }

    void handler()
    {
        const ComObjPtr<GuestDnDTarget> pThis(mTarget);
        Assert(!pThis.isNull());

        AutoCaller autoCaller(pThis);
        if (autoCaller.isNotOk())
            return;

        pThis->i_sendData(mpCtx, RT_INDEFINITE_WAIT /* msTimeout */); /* ignore return code */
    }

    virtual ~GuestDnDSendDataTask(void) { }

protected:

    /** Pointer to send data context. */
    GuestDnDSendCtx *mpCtx;
};

// constructor / destructor
/////////////////////////////////////////////////////////////////////////////

GuestDnDTarget::GuestDnDTarget(void)
    : GuestDnDBase(this) { }

GuestDnDTarget::~GuestDnDTarget(void) { }

HRESULT GuestDnDTarget::FinalConstruct(void)
{
    /* Set the maximum block size our guests can handle to 64K. This always has
     * been hardcoded until now. */
    /* Note: Never ever rely on information from the guest; the host dictates what and
     *       how to do something, so try to negogiate a sensible value here later. */
    mData.mcbBlockSize = DND_DEFAULT_CHUNK_SIZE; /** @todo Make this configurable. */

    LogFlowThisFunc(("\n"));
    return BaseFinalConstruct();
}

void GuestDnDTarget::FinalRelease(void)
{
    LogFlowThisFuncEnter();
    uninit();
    BaseFinalRelease();
    LogFlowThisFuncLeave();
}

// public initializer/uninitializer for internal purposes only
/////////////////////////////////////////////////////////////////////////////

HRESULT GuestDnDTarget::init(const ComObjPtr<Guest>& pGuest)
{
    LogFlowThisFuncEnter();

    /* Enclose the state transition NotReady->InInit->Ready. */
    AutoInitSpan autoInitSpan(this);
    AssertReturn(autoInitSpan.isOk(), E_FAIL);

    unconst(m_pGuest) = pGuest;

    /* Set the response we're going to use for this object.
     *
     * At the moment we only have one response total, as we
     * don't allow
     *      1) parallel transfers (multiple G->H at the same time)
     *  nor 2) mixed transfers (G->H + H->G at the same time).
     */
    m_pState = GuestDnDInst()->getState();
    AssertPtrReturn(m_pState, E_POINTER);

    /* Confirm a successful initialization when it's the case. */
    autoInitSpan.setSucceeded();

    return S_OK;
}

/**
 * Uninitializes the instance.
 * Called from FinalRelease().
 */
void GuestDnDTarget::uninit(void)
{
    LogFlowThisFunc(("\n"));

    /* Enclose the state transition Ready->InUninit->NotReady. */
    AutoUninitSpan autoUninitSpan(this);
    if (autoUninitSpan.uninitDone())
        return;
}

// implementation of wrapped IDnDBase methods.
/////////////////////////////////////////////////////////////////////////////

HRESULT GuestDnDTarget::isFormatSupported(const com::Utf8Str &aFormat, BOOL *aSupported)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    AutoCaller autoCaller(this);
    if (autoCaller.isNotOk()) return autoCaller.hrc();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    *aSupported = GuestDnDBase::i_isFormatSupported(aFormat) ? TRUE : FALSE;

    return S_OK;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

HRESULT GuestDnDTarget::getFormats(GuestDnDMIMEList &aFormats)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    AutoCaller autoCaller(this);
    if (autoCaller.isNotOk()) return autoCaller.hrc();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aFormats = GuestDnDBase::i_getFormats();

    return S_OK;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

HRESULT GuestDnDTarget::addFormats(const GuestDnDMIMEList &aFormats)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    AutoCaller autoCaller(this);
    if (autoCaller.isNotOk()) return autoCaller.hrc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    return GuestDnDBase::i_addFormats(aFormats);
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

HRESULT GuestDnDTarget::removeFormats(const GuestDnDMIMEList &aFormats)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    AutoCaller autoCaller(this);
    if (autoCaller.isNotOk()) return autoCaller.hrc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    return GuestDnDBase::i_removeFormats(aFormats);
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

// implementation of wrapped IDnDTarget methods.
/////////////////////////////////////////////////////////////////////////////

HRESULT GuestDnDTarget::enter(ULONG aScreenId, ULONG aX, ULONG aY,
                              DnDAction_T                      aDefaultAction,
                              const std::vector<DnDAction_T>  &aAllowedActions,
                              const GuestDnDMIMEList          &aFormats,
                              DnDAction_T                     *aResultAction)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    /* Input validation. */
    if (aDefaultAction == DnDAction_Ignore)
        return setError(E_INVALIDARG, tr("No default action specified"));
    if (!aAllowedActions.size())
        return setError(E_INVALIDARG, tr("Number of allowed actions is empty"));
    if (!aFormats.size())
        return setError(E_INVALIDARG, tr("Number of supported formats is empty"));

    AutoCaller autoCaller(this);
    if (autoCaller.isNotOk()) return autoCaller.hrc();

    /* Default action is ignoring. */
    DnDAction_T resAction = DnDAction_Ignore;

    /* Check & convert the drag & drop actions. */
    VBOXDNDACTION     dndActionDefault     = 0;
    VBOXDNDACTIONLIST dndActionListAllowed = 0;
    GuestDnD::toHGCMActions(aDefaultAction, &dndActionDefault,
                            aAllowedActions, &dndActionListAllowed);

    /* If there is no usable action, ignore this request. */
    if (isDnDIgnoreAction(dndActionDefault))
        return S_OK;

    GuestDnDState *pState = GuestDnDInst()->getState();
    AssertPtrReturn(pState, E_POINTER);

    /*
     * Make a flat data string out of the supported format list.
     * In the GuestDnDTarget case the source formats are from the host,
     * as GuestDnDTarget acts as a source for the guest.
     */
    Utf8Str strFormats       = GuestDnD::toFormatString(GuestDnD::toFilteredFormatList(m_lstFmtSupported, aFormats));
    if (strFormats.isEmpty())
        return setError(E_INVALIDARG, tr("No or not supported format(s) specified"));
    const uint32_t cbFormats = (uint32_t)strFormats.length() + 1; /* Include terminating zero. */

    LogRel2(("DnD: Offered formats to guest:\n"));
    RTCList<RTCString> lstFormats = strFormats.split(DND_PATH_SEPARATOR_STR);
    for (size_t i = 0; i < lstFormats.size(); i++)
        LogRel2(("DnD: \t%s\n", lstFormats[i].c_str()));

    /* Save the formats offered to the guest. This is needed to later
     * decide what to do with the data when sending stuff to the guest. */
    m_lstFmtOffered = aFormats;
    Assert(m_lstFmtOffered.size());

    /* Adjust the coordinates in a multi-monitor setup. */
    HRESULT hrc = GuestDnDInst()->adjustScreenCoordinates(aScreenId, &aX, &aY);
    if (SUCCEEDED(hrc))
    {
        GuestDnDMsg Msg;
        Msg.setType(HOST_DND_FN_HG_EVT_ENTER);
        if (m_pState->m_uProtocolVersion >= 3)
            Msg.appendUInt32(0); /** @todo ContextID not used yet. */
        Msg.appendUInt32(aScreenId);
        Msg.appendUInt32(aX);
        Msg.appendUInt32(aY);
        Msg.appendUInt32(dndActionDefault);
        Msg.appendUInt32(dndActionListAllowed);
        Msg.appendPointer((void *)strFormats.c_str(), cbFormats);
        Msg.appendUInt32(cbFormats);

        int vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
        if (RT_SUCCESS(vrc))
        {
            int vrcGuest;
            if (RT_SUCCESS(vrc = pState->waitForGuestResponse(&vrcGuest)))
            {
                resAction = GuestDnD::toMainAction(m_pState->getActionDefault());

                LogRel2(("DnD: Host enters the VM window at %RU32,%RU32 (screen %u, default action is '%s') -> guest reported back action '%s'\n",
                         aX, aY, aScreenId, DnDActionToStr(dndActionDefault), DnDActionToStr(resAction)));

                pState->set(VBOXDNDSTATE_ENTERED);
            }
            else
                hrc = i_setErrorAndReset(vrc == VERR_DND_GUEST_ERROR ? vrcGuest : vrc, tr("Entering VM window failed"));
        }
        else
        {
            switch (vrc)
            {
                case VERR_ACCESS_DENIED:
                {
                    hrc = i_setErrorAndReset(tr("Drag and drop to guest not allowed. Select the right mode first"));
                    break;
                }

                case VERR_NOT_SUPPORTED:
                {
                    hrc = i_setErrorAndReset(tr("Drag and drop to guest not possible -- either the guest OS does not support this, "
                                                "or the Guest Additions are not installed"));
                    break;
                }

                default:
                    hrc = i_setErrorAndReset(vrc, tr("Entering VM window failed"));
                    break;
            }
        }
    }

    if (SUCCEEDED(hrc))
    {
        if (aResultAction)
            *aResultAction = resAction;
    }

    LogFlowFunc(("hrc=%Rhrc, resAction=%ld\n", hrc, resAction));
    return hrc;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

HRESULT GuestDnDTarget::move(ULONG aScreenId, ULONG aX, ULONG aY,
                             DnDAction_T                      aDefaultAction,
                             const std::vector<DnDAction_T>  &aAllowedActions,
                             const GuestDnDMIMEList          &aFormats,
                             DnDAction_T                     *aResultAction)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    /* Input validation. */

    AutoCaller autoCaller(this);
    if (autoCaller.isNotOk()) return autoCaller.hrc();

    /* Default action is ignoring. */
    DnDAction_T resAction = DnDAction_Ignore;

    /* Check & convert the drag & drop actions. */
    VBOXDNDACTION     dndActionDefault     = 0;
    VBOXDNDACTIONLIST dndActionListAllowed = 0;
    GuestDnD::toHGCMActions(aDefaultAction, &dndActionDefault,
                            aAllowedActions, &dndActionListAllowed);

    /* If there is no usable action, ignore this request. */
    if (isDnDIgnoreAction(dndActionDefault))
        return S_OK;

    GuestDnDState *pState = GuestDnDInst()->getState();
    AssertPtrReturn(pState, E_POINTER);

    /*
     * Make a flat data string out of the supported format list.
     * In the GuestDnDTarget case the source formats are from the host,
     * as GuestDnDTarget acts as a source for the guest.
     */
    Utf8Str strFormats       = GuestDnD::toFormatString(GuestDnD::toFilteredFormatList(m_lstFmtSupported, aFormats));
    if (strFormats.isEmpty())
        return setError(E_INVALIDARG, tr("No or not supported format(s) specified"));
    const uint32_t cbFormats = (uint32_t)strFormats.length() + 1; /* Include terminating zero. */

    HRESULT hrc = GuestDnDInst()->adjustScreenCoordinates(aScreenId, &aX, &aY);
    if (SUCCEEDED(hrc))
    {
        GuestDnDMsg Msg;
        Msg.setType(HOST_DND_FN_HG_EVT_MOVE);
        if (m_pState->m_uProtocolVersion >= 3)
            Msg.appendUInt32(0); /** @todo ContextID not used yet. */
        Msg.appendUInt32(aScreenId);
        Msg.appendUInt32(aX);
        Msg.appendUInt32(aY);
        Msg.appendUInt32(dndActionDefault);
        Msg.appendUInt32(dndActionListAllowed);
        Msg.appendPointer((void *)strFormats.c_str(), cbFormats);
        Msg.appendUInt32(cbFormats);

        int vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
        if (RT_SUCCESS(vrc))
        {
            int vrcGuest;
            if (RT_SUCCESS(vrc = pState->waitForGuestResponse(&vrcGuest)))
            {
                resAction = GuestDnD::toMainAction(pState->getActionDefault());

                LogRel2(("DnD: Host moved to %RU32,%RU32 in VM window (screen %u, default action is '%s') -> guest reported back action '%s'\n",
                         aX, aY, aScreenId, DnDActionToStr(dndActionDefault), DnDActionToStr(resAction)));

                pState->set(VBOXDNDSTATE_DRAGGING);
            }
            else
                hrc = i_setErrorAndReset(vrc == VERR_DND_GUEST_ERROR ? vrcGuest : vrc,
                                         tr("Moving to %RU32,%RU32 (screen %u) failed"), aX, aY, aScreenId);
        }
        else
        {
            switch (vrc)
            {
                case VERR_ACCESS_DENIED:
                {
                    hrc = i_setErrorAndReset(tr("Moving in guest not allowed. Select the right mode first"));
                    break;
                }

                case VERR_NOT_SUPPORTED:
                {
                    hrc = i_setErrorAndReset(tr("Moving in guest not possible -- either the guest OS does not support this, "
                                                "or the Guest Additions are not installed"));
                    break;
                }

                default:
                    hrc = i_setErrorAndReset(vrc, tr("Moving in VM window failed"));
                    break;
            }
        }
    }
    else
        hrc = i_setErrorAndReset(tr("Retrieving move coordinates failed"));

    if (SUCCEEDED(hrc))
    {
        if (aResultAction)
            *aResultAction = resAction;
    }

    LogFlowFunc(("hrc=%Rhrc, *pResultAction=%ld\n", hrc, resAction));
    return hrc;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

HRESULT GuestDnDTarget::leave(ULONG uScreenId)
{
    RT_NOREF(uScreenId);
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    AutoCaller autoCaller(this);
    if (autoCaller.isNotOk()) return autoCaller.hrc();

    GuestDnDState *pState = GuestDnDInst()->getState();
    AssertPtrReturn(pState, E_POINTER);

    if (pState->get() == VBOXDNDSTATE_DROP_STARTED)
        return S_OK;

    HRESULT hrc = S_OK;

    LogRel2(("DnD: Host left the VM window (screen %u)\n", uScreenId));

    GuestDnDMsg Msg;
    Msg.setType(HOST_DND_FN_HG_EVT_LEAVE);
    if (m_pState->m_uProtocolVersion >= 3)
        Msg.appendUInt32(0); /** @todo ContextID not used yet. */

    int vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
    if (RT_SUCCESS(vrc))
    {
        int vrcGuest;
        if (RT_SUCCESS(vrc = pState->waitForGuestResponse(&vrcGuest)))
        {
            pState->set(VBOXDNDSTATE_LEFT);
        }
        else
            hrc = i_setErrorAndReset(vrc == VERR_DND_GUEST_ERROR ? vrcGuest : vrc, tr("Leaving VM window failed"));
    }
    else
    {
        switch (vrc)
        {
            case VERR_ACCESS_DENIED:
            {
                hrc = i_setErrorAndReset(tr("Leaving guest not allowed. Select the right mode first"));
                break;
            }

            case VERR_NOT_SUPPORTED:
            {
                hrc = i_setErrorAndReset(tr("Leaving guest not possible -- either the guest OS does not support this, "
                                            "or the Guest Additions are not installed"));
                break;
            }

            default:
                hrc = i_setErrorAndReset(vrc, tr("Leaving VM window failed"));
                break;
        }
    }

    LogFlowFunc(("hrc=%Rhrc\n", hrc));
    return hrc;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

HRESULT GuestDnDTarget::drop(ULONG aScreenId, ULONG aX, ULONG aY,
                             DnDAction_T                      aDefaultAction,
                             const std::vector<DnDAction_T>  &aAllowedActions,
                             const GuestDnDMIMEList          &aFormats,
                             com::Utf8Str                    &aFormat,
                             DnDAction_T                     *aResultAction)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    if (aDefaultAction == DnDAction_Ignore)
        return setError(E_INVALIDARG, tr("Invalid default action specified"));
    if (!aAllowedActions.size())
        return setError(E_INVALIDARG, tr("Invalid allowed actions specified"));
    if (!aFormats.size())
        return setError(E_INVALIDARG, tr("No drop format(s) specified"));
    /* aResultAction is optional. */

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

    /* Default action is ignoring. */
    DnDAction_T resAct = DnDAction_Ignore;
    Utf8Str     resFmt;

    /* Check & convert the drag & drop actions to HGCM codes. */
    VBOXDNDACTION     dndActionDefault     = VBOX_DND_ACTION_IGNORE;
    VBOXDNDACTIONLIST dndActionListAllowed = 0;
    GuestDnD::toHGCMActions(aDefaultAction,  &dndActionDefault,
                            aAllowedActions, &dndActionListAllowed);

    /* If there is no usable action, ignore this request. */
    if (isDnDIgnoreAction(dndActionDefault))
    {
        aFormat = "";
        if (aResultAction)
            *aResultAction = DnDAction_Ignore;
        return S_OK;
    }

    GuestDnDState *pState = GuestDnDInst()->getState();
    AssertPtrReturn(pState, E_POINTER);

    /*
     * Make a flat data string out of the supported format list.
     * In the GuestDnDTarget case the source formats are from the host,
     * as GuestDnDTarget acts as a source for the guest.
     */
    Utf8Str strFormats       = GuestDnD::toFormatString(GuestDnD::toFilteredFormatList(m_lstFmtSupported, aFormats));
    if (strFormats.isEmpty())
        return setError(E_INVALIDARG, tr("No or not supported format(s) specified"));
    const uint32_t cbFormats = (uint32_t)strFormats.length() + 1; /* Include terminating zero. */

    /* Adjust the coordinates in a multi-monitor setup. */
    HRESULT hrc = GuestDnDInst()->adjustScreenCoordinates(aScreenId, &aX, &aY);
    if (SUCCEEDED(hrc))
    {
        GuestDnDMsg Msg;
        Msg.setType(HOST_DND_FN_HG_EVT_DROPPED);
        if (m_pState->m_uProtocolVersion >= 3)
            Msg.appendUInt32(0); /** @todo ContextID not used yet. */
        Msg.appendUInt32(aScreenId);
        Msg.appendUInt32(aX);
        Msg.appendUInt32(aY);
        Msg.appendUInt32(dndActionDefault);
        Msg.appendUInt32(dndActionListAllowed);
        Msg.appendPointer((void*)strFormats.c_str(), cbFormats);
        Msg.appendUInt32(cbFormats);

        LogRel2(("DnD: Host drops at %RU32,%RU32 in VM window (screen %u, default action is '%s')\n",
                 aX, aY, aScreenId, DnDActionToStr(dndActionDefault)));

        int vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
        if (RT_SUCCESS(vrc))
        {
            int vrcGuest;
            if (RT_SUCCESS(vrc = pState->waitForGuestResponse(&vrcGuest)))
            {
                resAct = GuestDnD::toMainAction(pState->getActionDefault());
                if (resAct != DnDAction_Ignore) /* Does the guest accept a drop at the current position? */
                {
                    GuestDnDMIMEList lstFormats = pState->formats();
                    if (lstFormats.size() == 1) /* Exactly one format to use specified? */
                    {
                        resFmt = lstFormats.at(0);

                        LogRel2(("DnD: Guest accepted drop in format '%s' (action %#x, %zu format(s))\n",
                                 resFmt.c_str(), resAct, lstFormats.size()));

                        pState->set(VBOXDNDSTATE_DROP_STARTED);
                    }
                    else
                    {
                        if (lstFormats.size() == 0)
                            hrc = i_setErrorAndReset(VERR_DND_GUEST_ERROR, tr("Guest accepted drop, but did not specify the format"));
                        else
                            hrc = i_setErrorAndReset(VERR_DND_GUEST_ERROR, tr("Guest accepted drop, but returned more than one drop format (%zu formats)"),
                                                     lstFormats.size());
                    }
                }
            }
            else
                hrc = i_setErrorAndReset(vrc == VERR_DND_GUEST_ERROR ? vrcGuest : vrc, tr("Dropping into VM failed"));
        }
        else
            hrc = i_setErrorAndReset(vrc, tr("Sending dropped event to guest failed"));
    }
    else
        hrc = i_setErrorAndReset(hrc, tr("Retrieving drop coordinates failed"));

    if (SUCCEEDED(hrc))
    {
        aFormat = resFmt;
        if (aResultAction)
            *aResultAction = resAct;
    }

    return hrc;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

/**
 * Initiates a data transfer from the host to the guest.
 *
 * The source is the host, whereas the target is the guest.
 *
 * @return  HRESULT
 * @param   aScreenId           Screen ID where this data transfer was initiated from.
 * @param   aFormat             Format of data to send. MIME-style.
 * @param   aData               Actual data to send.
 * @param   aProgress           Where to return the progress object on success.
 */
HRESULT GuestDnDTarget::sendData(ULONG aScreenId, const com::Utf8Str &aFormat, const std::vector<BYTE> &aData,
                                 ComPtr<IProgress> &aProgress)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

    /* Input validation. */
    if (RT_UNLIKELY((aFormat.c_str()) == NULL || *(aFormat.c_str()) == '\0'))
        return setError(E_INVALIDARG, tr("No data format specified"));
    if (RT_UNLIKELY(!aData.size()))
        return setError(E_INVALIDARG, tr("No data to send specified"));

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    /* Check if this object still is in a pending state and bail out if so. */
    if (m_fIsPending)
        return setError(E_FAIL, tr("Current drop operation to guest still in progress"));

    /* At the moment we only support one transfer at a time. */
    if (GuestDnDInst()->getTargetCount())
        return setError(E_INVALIDARG, tr("Another drag and drop operation to the guest already is in progress"));

    /* Reset progress object. */
    GuestDnDState *pState = GuestDnDInst()->getState();
    AssertPtr(pState);
    HRESULT hr = pState->resetProgress(m_pGuest, tr("Dropping data to guest"));
    if (FAILED(hr))
        return hr;

    GuestDnDSendDataTask *pTask = NULL;

    try
    {
        mData.mSendCtx.reset();

        mData.mSendCtx.pTarget   = this;
        mData.mSendCtx.pState    = pState;
        mData.mSendCtx.uScreenID = aScreenId;

        mData.mSendCtx.Meta.strFmt = aFormat;
        mData.mSendCtx.Meta.add(aData);

        LogRel2(("DnD: Host sends data in format '%s'\n", aFormat.c_str()));

        pTask = new GuestDnDSendDataTask(this, &mData.mSendCtx);
        if (!pTask->isOk())
        {
            delete pTask;
            LogRel(("DnD: Could not create SendDataTask object\n"));
            throw hr = E_FAIL;
        }

        /* This function delete pTask in case of exceptions,
         * so there is no need in the call of delete operator. */
        hr = pTask->createThreadWithType(RTTHREADTYPE_MAIN_WORKER);
        pTask = NULL; /* Note: pTask is now owned by the worker thread. */
    }
    catch (std::bad_alloc &)
    {
        hr = E_OUTOFMEMORY;
    }
    catch (...)
    {
        LogRel(("DnD: Could not create thread for data sending task\n"));
        hr = E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        /* Register ourselves at the DnD manager. */
        GuestDnDInst()->registerTarget(this);

        /* Return progress to caller. */
        hr = pState->queryProgressTo(aProgress.asOutParam());
        ComAssertComRC(hr);
    }
    else
        hr = i_setErrorAndReset(tr("Starting thread for GuestDnDTarget failed (%Rhrc)"), hr);

    LogFlowFunc(("Returning hr=%Rhrc\n", hr));
    return hr;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}

/**
 * Returns an error string from a guest DnD error.
 *
 * @returns Error string.
 * @param   guestRc             Guest error to return error string for.
 */
/* static */
Utf8Str GuestDnDTarget::i_guestErrorToString(int guestRc)
{
    Utf8Str strError;

    switch (guestRc)
    {
        case VERR_ACCESS_DENIED:
            strError += Utf8StrFmt(tr("For one or more guest files or directories selected for transferring to the host your guest "
                                      "user does not have the appropriate access rights for. Please make sure that all selected "
                                      "elements can be accessed and that your guest user has the appropriate rights"));
            break;

        case VERR_NOT_FOUND:
            /* Should not happen due to file locking on the guest, but anyway ... */
            strError += Utf8StrFmt(tr("One or more guest files or directories selected for transferring to the host were not"
                                      "found on the guest anymore. This can be the case if the guest files were moved and/or"
                                      "altered while the drag and drop operation was in progress"));
            break;

        case VERR_SHARING_VIOLATION:
            strError += Utf8StrFmt(tr("One or more guest files or directories selected for transferring to the host were locked. "
                                      "Please make sure that all selected elements can be accessed and that your guest user has "
                                      "the appropriate rights"));
            break;

        case VERR_TIMEOUT:
            strError += Utf8StrFmt(tr("The guest was not able to process the drag and drop data within time"));
            break;

        default:
            strError += Utf8StrFmt(tr("Drag and drop error from guest (%Rrc)"), guestRc);
            break;
    }

    return strError;
}

/**
 * Returns an error string from a host DnD error.
 *
 * @returns Error string.
 * @param   hostRc              Host error to return error string for.
 */
/* static */
Utf8Str GuestDnDTarget::i_hostErrorToString(int hostRc)
{
    Utf8Str strError;

    switch (hostRc)
    {
        case VERR_ACCESS_DENIED:
            strError += Utf8StrFmt(tr("For one or more host files or directories selected for transferring to the guest your host "
                                      "user does not have the appropriate access rights for. Please make sure that all selected "
                                      "elements can be accessed and that your host user has the appropriate rights."));
            break;

        case VERR_NOT_FOUND:
            /* Should not happen due to file locking on the host, but anyway ... */
            strError += Utf8StrFmt(tr("One or more host files or directories selected for transferring to the host were not"
                                      "found on the host anymore. This can be the case if the host files were moved and/or"
                                      "altered while the drag and drop operation was in progress."));
            break;

        case VERR_SHARING_VIOLATION:
            strError += Utf8StrFmt(tr("One or more host files or directories selected for transferring to the guest were locked. "
                                      "Please make sure that all selected elements can be accessed and that your host user has "
                                      "the appropriate rights."));
            break;

        default:
            strError += Utf8StrFmt(tr("Drag and drop error from host (%Rrc)"), hostRc);
            break;
    }

    return strError;
}

/**
 * Resets all internal data and state.
 */
void GuestDnDTarget::i_reset(void)
{
    LogRel2(("DnD: Target reset\n"));

    mData.mSendCtx.reset();

    m_fIsPending = false;

    /* Unregister ourselves from the DnD manager. */
    GuestDnDInst()->unregisterTarget(this);
}

/**
 * Main function for sending DnD host data to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 * @param   msTimeout           Timeout (in ms) to wait for getting the data sent.
 */
int GuestDnDTarget::i_sendData(GuestDnDSendCtx *pCtx, RTMSINTERVAL msTimeout)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);

    /* Don't allow receiving the actual data until our current transfer is complete. */
    if (m_fIsPending)
        return setError(E_FAIL, tr("Current drop operation to guest still in progress"));

    /* Clear all remaining outgoing messages. */
    m_DataBase.lstMsgOut.clear();

    /**
     * Do we need to build up a file tree?
     * Note: The decision whether we need to build up a file tree and sending
     *       actual file data only depends on the actual formats offered by this target.
     *       If the guest does not want a transfer list ("text/uri-list") but text ("TEXT" and
     *       friends) instead, still send the data over to the guest -- the file as such still
     *       is needed on the guest in this case, as the guest then just wants a simple path
     *       instead of a transfer list (pointing to a file on the guest itself).
     *
     ** @todo Support more than one format; add a format<->function handler concept. Later. */
    int vrc;
    const bool fHasURIList = std::find(m_lstFmtOffered.begin(),
                                       m_lstFmtOffered.end(), "text/uri-list") != m_lstFmtOffered.end();
    if (fHasURIList)
    {
        vrc = i_sendTransferData(pCtx, msTimeout);
    }
    else
    {
        vrc = i_sendRawData(pCtx, msTimeout);
    }

    GuestDnDState *pState = GuestDnDInst()->getState();
    AssertPtrReturn(pState, E_POINTER);

    if (RT_SUCCESS(vrc))
    {
        pState->set(VBOXDNDSTATE_DROP_ENDED);
    }
    else
    {
        if (vrc == VERR_CANCELLED)
        {
            LogRel(("DnD: Sending data to guest cancelled by the user\n"));
            pState->set(VBOXDNDSTATE_CANCELLED);
        }
        else
        {
            LogRel(("DnD: Sending data to guest failed with %Rrc\n", vrc));
            pState->set(VBOXDNDSTATE_ERROR);
        }

        /* Make sure to fire a cancel request to the guest side in any case to prevent any guest side hangs. */
        sendCancel();
    }

    /* Reset state. */
    i_reset();

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Sends the common meta data body to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 */
int GuestDnDTarget::i_sendMetaDataBody(GuestDnDSendCtx *pCtx)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);

    uint8_t *pvData = (uint8_t *)pCtx->Meta.pvData;
    size_t   cbData = pCtx->Meta.cbData;

    int vrc = VINF_SUCCESS;

    const size_t  cbFmt   = pCtx->Meta.strFmt.length() + 1; /* Include terminator. */
    const char   *pcszFmt = pCtx->Meta.strFmt.c_str();

    LogFlowFunc(("uProtoVer=%RU32, szFmt=%s, cbFmt=%RU32, cbData=%zu\n", m_pState->m_uProtocolVersion, pcszFmt, cbFmt, cbData));

    LogRel2(("DnD: Sending meta data to guest as '%s' (%zu bytes)\n", pcszFmt, cbData));

#ifdef DEBUG
    RTCList<RTCString> lstFilesURI = RTCString((char *)pvData, cbData).split(DND_PATH_SEPARATOR_STR);
    LogFlowFunc(("lstFilesURI=%zu\n", lstFilesURI.size()));
    for (size_t i = 0; i < lstFilesURI.size(); i++)
        LogFlowFunc(("\t%s\n", lstFilesURI.at(i).c_str()));
#endif

    uint8_t *pvChunk = pvData;
    size_t   cbChunk = RT_MIN(mData.mcbBlockSize, cbData);
    while (cbData)
    {
        GuestDnDMsg Msg;
        Msg.setType(HOST_DND_FN_HG_SND_DATA);

        if (m_pState->m_uProtocolVersion < 3)
        {
            Msg.appendUInt32(pCtx->uScreenID);                                 /* uScreenId */
            Msg.appendPointer(unconst(pcszFmt), (uint32_t)cbFmt);              /* pvFormat */
            Msg.appendUInt32((uint32_t)cbFmt);                                 /* cbFormat */
            Msg.appendPointer(pvChunk, (uint32_t)cbChunk);                     /* pvData */
            /* Fill in the current data block size to send.
             * Note: Only supports uint32_t. */
            Msg.appendUInt32((uint32_t)cbChunk);                               /* cbData */
        }
        else
        {
            Msg.appendUInt32(0); /** @todo ContextID not used yet. */
            Msg.appendPointer(pvChunk, (uint32_t)cbChunk);                     /* pvData */
            Msg.appendUInt32((uint32_t)cbChunk);                               /* cbData */
            Msg.appendPointer(NULL, 0);                                        /** @todo pvChecksum; not used yet. */
            Msg.appendUInt32(0);                                               /** @todo cbChecksum; not used yet. */
        }

        vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());
        if (RT_FAILURE(vrc))
            break;

        pvChunk += cbChunk;
        AssertBreakStmt(cbData >= cbChunk, VERR_BUFFER_UNDERFLOW);
        cbData  -= cbChunk;
    }

    if (RT_SUCCESS(vrc))
    {
        vrc = updateProgress(pCtx, pCtx->pState, (uint32_t)pCtx->Meta.cbData);
        AssertRC(vrc);
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Sends the common meta data header to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 */
int GuestDnDTarget::i_sendMetaDataHeader(GuestDnDSendCtx *pCtx)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);

    if (m_pState->m_uProtocolVersion < 3) /* Protocol < v3 did not support this, skip. */
        return VINF_SUCCESS;

    GuestDnDMsg Msg;
    Msg.setType(HOST_DND_FN_HG_SND_DATA_HDR);

    LogRel2(("DnD: Sending meta data header to guest (%RU64 bytes total data, %RU32 bytes meta data, %RU64 objects)\n",
             pCtx->getTotalAnnounced(), pCtx->Meta.cbData, pCtx->Transfer.cObjToProcess));

    Msg.appendUInt32(0);                                                /** @todo uContext; not used yet. */
    Msg.appendUInt32(0);                                                /** @todo uFlags; not used yet. */
    Msg.appendUInt32(pCtx->uScreenID);                                  /* uScreen */
    Msg.appendUInt64(pCtx->getTotalAnnounced());                        /* cbTotal */
    Msg.appendUInt32((uint32_t)pCtx->Meta.cbData);                      /* cbMeta*/
    Msg.appendPointer(unconst(pCtx->Meta.strFmt.c_str()), (uint32_t)pCtx->Meta.strFmt.length() + 1); /* pvMetaFmt */
    Msg.appendUInt32((uint32_t)pCtx->Meta.strFmt.length() + 1);                                      /* cbMetaFmt */
    Msg.appendUInt64(pCtx->Transfer.cObjToProcess);                     /* cObjects */
    Msg.appendUInt32(0);                                                /** @todo enmCompression; not used yet. */
    Msg.appendUInt32(0);                                                /** @todo enmChecksumType; not used yet. */
    Msg.appendPointer(NULL, 0);                                         /** @todo pvChecksum; not used yet. */
    Msg.appendUInt32(0);                                                /** @todo cbChecksum; not used yet. */

    int vrc = GuestDnDInst()->hostCall(Msg.getType(), Msg.getCount(), Msg.getParms());

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Sends a directory entry to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 * @param   pObj                Transfer object to send. Must be a directory.
 * @param   pMsg                Where to store the message to send.
 */
int GuestDnDTarget::i_sendDirectory(GuestDnDSendCtx *pCtx, PDNDTRANSFEROBJECT pObj, GuestDnDMsg *pMsg)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
    AssertPtrReturn(pMsg, VERR_INVALID_POINTER);

    const char *pcszDstPath = DnDTransferObjectGetDestPath(pObj);
    AssertPtrReturn(pcszDstPath, VERR_INVALID_POINTER);
    const size_t cchPath = RTStrNLen(pcszDstPath, RTPATH_MAX); /* Note: Maximum is RTPATH_MAX on guest side. */
    AssertReturn(cchPath, VERR_INVALID_PARAMETER);

    LogRel2(("DnD: Transferring host directory '%s' to guest\n", DnDTransferObjectGetSourcePath(pObj)));

    pMsg->setType(HOST_DND_FN_HG_SND_DIR);
    if (m_pState->m_uProtocolVersion >= 3)
        pMsg->appendUInt32(0); /** @todo ContextID not used yet. */
    pMsg->appendString(pcszDstPath);                    /* path */
    pMsg->appendUInt32((uint32_t)(cchPath + 1));        /* path length, including terminator. */
    pMsg->appendUInt32(DnDTransferObjectGetMode(pObj)); /* mode */

    return VINF_SUCCESS;
}

/**
 * Sends a file to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 * @param   pObj                Transfer object to send. Must be a file.
 * @param   pMsg                Where to store the message to send.
 */
int GuestDnDTarget::i_sendFile(GuestDnDSendCtx *pCtx,
                               PDNDTRANSFEROBJECT pObj, GuestDnDMsg *pMsg)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
    AssertPtrReturn(pObj, VERR_INVALID_POINTER);
    AssertPtrReturn(pMsg, VERR_INVALID_POINTER);

    const char *pcszSrcPath = DnDTransferObjectGetSourcePath(pObj);
    AssertPtrReturn(pcszSrcPath, VERR_INVALID_POINTER);
    const char *pcszDstPath = DnDTransferObjectGetDestPath(pObj);
    AssertPtrReturn(pcszDstPath, VERR_INVALID_POINTER);

    int vrc = VINF_SUCCESS;

    if (!DnDTransferObjectIsOpen(pObj))
    {
        LogRel2(("DnD: Opening host file '%s' for transferring to guest\n", pcszSrcPath));

        vrc = DnDTransferObjectOpen(pObj, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE, 0 /* fMode */,
                                    DNDTRANSFEROBJECT_FLAGS_NONE);
        if (RT_FAILURE(vrc))
            LogRel(("DnD: Opening host file '%s' failed, vrc=%Rrc\n", pcszSrcPath, vrc));
    }

    if (RT_FAILURE(vrc))
        return vrc;

    bool fSendData = false;
    if (RT_SUCCESS(vrc)) /** @todo r=aeichner Could save an identation level here as there is a error check above already... */
    {
        if (m_pState->m_uProtocolVersion >= 2)
        {
            if (!(pCtx->Transfer.fObjState & DND_OBJ_STATE_HAS_HDR))
            {
                const size_t  cchDstPath = RTStrNLen(pcszDstPath, RTPATH_MAX);
                const size_t  cbSize     = DnDTransferObjectGetSize(pObj);
                const RTFMODE fMode      = DnDTransferObjectGetMode(pObj);

                /*
                 * Since protocol v2 the file header and the actual file contents are
                 * separate messages, so send the file header first.
                 * The just registered callback will be called by the guest afterwards.
                 */
                pMsg->setType(HOST_DND_FN_HG_SND_FILE_HDR);
                pMsg->appendUInt32(0); /** @todo ContextID not used yet. */
                pMsg->appendString(pcszDstPath);                    /* pvName */
                pMsg->appendUInt32((uint32_t)(cchDstPath + 1));     /* cbName */
                pMsg->appendUInt32(0);                              /* uFlags */
                pMsg->appendUInt32(fMode);                          /* fMode */
                pMsg->appendUInt64(cbSize);                         /* uSize */

                LogRel2(("DnD: Transferring host file '%s' to guest (as '%s', %zu bytes, mode %#x)\n",
                         pcszSrcPath, pcszDstPath, cbSize, fMode));

                /** @todo Set progress object title to current file being transferred? */

                /* Update object state to reflect that we have sent the file header. */
                pCtx->Transfer.fObjState |= DND_OBJ_STATE_HAS_HDR;
            }
            else
            {
                /* File header was sent, so only send the actual file data. */
                fSendData = true;
            }
        }
        else /* Protocol v1. */
        {
            /* Always send the file data, every time. */
            fSendData = true;
        }
    }

    if (   RT_SUCCESS(vrc)
        && fSendData)
    {
        vrc = i_sendFileData(pCtx, pObj, pMsg);
    }

    if (RT_FAILURE(vrc))
        LogRel(("DnD: Sending host file '%s' to guest failed, vrc=%Rrc\n", pcszSrcPath, vrc));

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Helper function to send actual file data to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 * @param   pObj                Transfer object to send. Must be a file.
 * @param   pMsg                Where to store the message to send.
 */
int GuestDnDTarget::i_sendFileData(GuestDnDSendCtx *pCtx,
                                   PDNDTRANSFEROBJECT pObj, GuestDnDMsg *pMsg)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
    AssertPtrReturn(pObj, VERR_INVALID_POINTER);
    AssertPtrReturn(pMsg, VERR_INVALID_POINTER);

    AssertPtrReturn(pCtx->pState, VERR_WRONG_ORDER);

    /** @todo Don't allow concurrent reads per context! */

    /* Set the message type. */
    pMsg->setType(HOST_DND_FN_HG_SND_FILE_DATA);

    const char *pcszSrcPath = DnDTransferObjectGetSourcePath(pObj);
    const char *pcszDstPath = DnDTransferObjectGetDestPath(pObj);

    /* Protocol version 1 sends the file path *every* time with a new file chunk.
     * In protocol version 2 we only do this once with HOST_DND_FN_HG_SND_FILE_HDR. */
    if (m_pState->m_uProtocolVersion <= 1)
    {
        const size_t cchDstPath = RTStrNLen(pcszDstPath, RTPATH_MAX);

        pMsg->appendString(pcszDstPath);              /* pvName */
        pMsg->appendUInt32((uint32_t)cchDstPath + 1); /* cbName */
    }
    else if (m_pState->m_uProtocolVersion >= 2)
    {
        pMsg->appendUInt32(0);                        /** @todo ContextID not used yet. */
    }

    void *pvBuf  = pCtx->Transfer.pvScratchBuf;
    AssertPtr(pvBuf);
    size_t cbBuf = pCtx->Transfer.cbScratchBuf;
    Assert(cbBuf);

    uint32_t cbRead;

    int vrc = DnDTransferObjectRead(pObj, pvBuf, cbBuf, &cbRead);
    if (RT_SUCCESS(vrc))
    {
        LogFlowFunc(("cbBufe=%zu, cbRead=%RU32\n", cbBuf, cbRead));

        if (m_pState->m_uProtocolVersion <= 1)
        {
            pMsg->appendPointer(pvBuf, cbRead);                            /* pvData */
            pMsg->appendUInt32(cbRead);                                    /* cbData */
            pMsg->appendUInt32(DnDTransferObjectGetMode(pObj));            /* fMode */
        }
        else /* Protocol v2 and up. */
        {
            pMsg->appendPointer(pvBuf, cbRead);                            /* pvData */
            pMsg->appendUInt32(cbRead);                                    /* cbData */

            if (m_pState->m_uProtocolVersion >= 3)
            {
                /** @todo Calculate checksum. */
                pMsg->appendPointer(NULL, 0);                              /* pvChecksum */
                pMsg->appendUInt32(0);                                     /* cbChecksum */
            }
        }

        int vrc2 = updateProgress(pCtx, pCtx->pState, (uint32_t)cbRead);
        AssertRC(vrc2);

        /* DnDTransferObjectRead() will return VINF_EOF if reading is complete. */
        if (vrc == VINF_EOF)
            vrc = VINF_SUCCESS;

        if (DnDTransferObjectIsComplete(pObj)) /* Done reading? */
            LogRel2(("DnD: Transferring host file '%s' to guest complete\n", pcszSrcPath));
    }
    else
        LogRel(("DnD: Reading from host file '%s' failed, vrc=%Rrc\n", pcszSrcPath, vrc));

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Static HGCM service callback which handles sending transfer data to the guest.
 *
 * @returns VBox status code. Will get sent back to the host service.
 * @param   uMsg                HGCM message ID (function number).
 * @param   pvParms             Pointer to additional message data. Optional and can be NULL.
 * @param   cbParms             Size (in bytes) additional message data. Optional and can be 0.
 * @param   pvUser              User-supplied pointer on callback registration.
 */
/* static */
DECLCALLBACK(int) GuestDnDTarget::i_sendTransferDataCallback(uint32_t uMsg, void *pvParms, size_t cbParms, void *pvUser)
{
    GuestDnDSendCtx *pCtx = (GuestDnDSendCtx *)pvUser;
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);

    GuestDnDTarget *pThis = pCtx->pTarget;
    AssertPtrReturn(pThis, VERR_INVALID_POINTER);

    /* At the moment we only have one transfer list per transfer. */
    PDNDTRANSFERLIST pList = &pCtx->Transfer.List;

    LogFlowFunc(("pThis=%p, pList=%p, uMsg=%RU32\n", pThis, pList, uMsg));

    int  vrc      = VINF_SUCCESS;
    int  vrcGuest = VINF_SUCCESS; /* Contains error code from guest in case of VERR_DND_GUEST_ERROR. */
    bool fNotify  = false;

    switch (uMsg)
    {
        case GUEST_DND_FN_CONNECT:
            /* Nothing to do here (yet). */
            break;

        case GUEST_DND_FN_DISCONNECT:
            vrc = VERR_CANCELLED;
            break;

        case GUEST_DND_FN_GET_NEXT_HOST_MSG:
        {
            PVBOXDNDCBHGGETNEXTHOSTMSG pCBData = reinterpret_cast<PVBOXDNDCBHGGETNEXTHOSTMSG>(pvParms);
            AssertPtr(pCBData);
            AssertReturn(sizeof(VBOXDNDCBHGGETNEXTHOSTMSG) == cbParms, VERR_INVALID_PARAMETER);
            AssertReturn(CB_MAGIC_DND_HG_GET_NEXT_HOST_MSG == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);

            try
            {
                GuestDnDMsg *pMsg = new GuestDnDMsg();

                vrc = pThis->i_sendTransferListObject(pCtx, pList, pMsg);
                if (vrc == VINF_EOF) /* Transfer complete? */
                {
                    LogFlowFunc(("Last transfer item processed, bailing out\n"));
                }
                else if (RT_SUCCESS(vrc))
                {
                    vrc = pThis->msgQueueAdd(pMsg);
                    if (RT_SUCCESS(vrc)) /* Return message type & required parameter count to the guest. */
                    {
                        LogFlowFunc(("GUEST_DND_FN_GET_NEXT_HOST_MSG -> %RU32 (%RU32 params)\n", pMsg->getType(), pMsg->getCount()));
                        pCBData->uMsg   = pMsg->getType();
                        pCBData->cParms = pMsg->getCount();
                    }
                }

                if (   RT_FAILURE(vrc)
                    || vrc == VINF_EOF) /* Transfer complete? */
                {
                    delete pMsg;
                    pMsg = NULL;
                }
            }
            catch(std::bad_alloc & /*e*/)
            {
                vrc = VERR_NO_MEMORY;
            }
            break;
        }
        case GUEST_DND_FN_EVT_ERROR:
        {
            PVBOXDNDCBEVTERRORDATA pCBData = reinterpret_cast<PVBOXDNDCBEVTERRORDATA>(pvParms);
            AssertPtr(pCBData);
            AssertReturn(sizeof(VBOXDNDCBEVTERRORDATA) == cbParms, VERR_INVALID_PARAMETER);
            AssertReturn(CB_MAGIC_DND_EVT_ERROR == pCBData->hdr.uMagic, VERR_INVALID_PARAMETER);

            pCtx->pState->reset();

            if (RT_SUCCESS(pCBData->rc))
            {
                AssertMsgFailed(("Guest has sent an error event but did not specify an actual error code\n"));
                pCBData->rc = VERR_GENERAL_FAILURE; /* Make sure some error is set. */
            }

            vrc = pCtx->pState->setProgress(100, DND_PROGRESS_ERROR, pCBData->rc,
                                            GuestDnDTarget::i_guestErrorToString(pCBData->rc));
            if (RT_SUCCESS(vrc))
            {
                vrc      = VERR_DND_GUEST_ERROR;
                vrcGuest = pCBData->rc;
            }
            break;
        }
        case HOST_DND_FN_HG_SND_DIR:
        case HOST_DND_FN_HG_SND_FILE_HDR:
        case HOST_DND_FN_HG_SND_FILE_DATA:
        {
            PVBOXDNDCBHGGETNEXTHOSTMSGDATA pCBData
                = reinterpret_cast<PVBOXDNDCBHGGETNEXTHOSTMSGDATA>(pvParms);
            AssertPtr(pCBData);
            AssertReturn(sizeof(VBOXDNDCBHGGETNEXTHOSTMSGDATA) == cbParms, VERR_INVALID_PARAMETER);

            LogFlowFunc(("pCBData->uMsg=%RU32, paParms=%p, cParms=%RU32\n", pCBData->uMsg, pCBData->paParms, pCBData->cParms));

            GuestDnDMsg *pMsg = pThis->msgQueueGetNext();
            if (pMsg)
            {
                /*
                 * Sanity checks.
                 */
                if (   pCBData->uMsg    != uMsg
                    || pCBData->paParms == NULL
                    || pCBData->cParms  != pMsg->getCount())
                {
                    LogFlowFunc(("Current message does not match:\n"));
                    LogFlowFunc(("\tCallback: uMsg=%RU32, cParms=%RU32, paParms=%p\n",
                                 pCBData->uMsg, pCBData->cParms, pCBData->paParms));
                    LogFlowFunc(("\t    Next: uMsg=%RU32, cParms=%RU32\n", pMsg->getType(), pMsg->getCount()));

                    /* Start over. */
                    pThis->msgQueueClear();

                    vrc = VERR_INVALID_PARAMETER;
                }

                if (RT_SUCCESS(vrc))
                {
                    LogFlowFunc(("Returning uMsg=%RU32\n", uMsg));
                    vrc = HGCM::Message::CopyParms(pCBData->paParms, pCBData->cParms, pMsg->getParms(), pMsg->getCount(),
                                                   false /* fDeepCopy */);
                    if (RT_SUCCESS(vrc))
                    {
                        pCBData->cParms = pMsg->getCount();
                        pThis->msgQueueRemoveNext();
                    }
                    else
                        LogFlowFunc(("Copying parameters failed with vrc=%Rrc\n", vrc));
                }
            }
            else
                vrc = VERR_NO_DATA;

            LogFlowFunc(("Processing next message ended with vrc=%Rrc\n", vrc));
            break;
        }
        default:
            vrc = VERR_NOT_SUPPORTED;
            break;
    }

    int vrcToGuest = VINF_SUCCESS; /* Status which will be sent back to the guest. */

    /*
     * Resolve errors.
     */
    switch (vrc)
    {
        case VINF_SUCCESS:
            break;

        case VINF_EOF:
        {
            LogRel2(("DnD: Transfer to guest complete\n"));

            /* Complete operation on host side. */
            fNotify = true;

            /* The guest expects VERR_NO_DATA if the transfer is complete. */
            vrcToGuest = VERR_NO_DATA;
            break;
        }

        case VERR_DND_GUEST_ERROR:
        {
            LogRel(("DnD: Guest reported error %Rrc, aborting transfer to guest\n", vrcGuest));
            break;
        }

        case VERR_CANCELLED:
        {
            LogRel2(("DnD: Transfer to guest canceled\n"));
            vrcToGuest = VERR_CANCELLED; /* Also cancel on guest side. */
            break;
        }

        default:
        {
            LogRel(("DnD: Host error %Rrc occurred, aborting transfer to guest\n", vrc));
            vrcToGuest = VERR_CANCELLED; /* Also cancel on guest side. */
            break;
        }
    }

    if (RT_FAILURE(vrc))
    {
        /* Unregister this callback. */
        AssertPtr(pCtx->pState);
        int vrc2 = pCtx->pState->setCallback(uMsg, NULL /* PFNGUESTDNDCALLBACK */);
        AssertRC(vrc2);

        /* Let the waiter(s) know. */
        fNotify = true;
    }

    LogFlowFunc(("fNotify=%RTbool, vrc=%Rrc, vrcToGuest=%Rrc\n", fNotify, vrc, vrcToGuest));

    if (fNotify)
    {
        int vrc2 = pCtx->EventCallback.Notify(vrc); /** @todo Also pass guest error back? */
        AssertRC(vrc2);
    }

    LogFlowFuncLeaveRC(vrc);
    return vrcToGuest; /* Tell the guest. */
}

/**
 * Main function for sending the actual transfer data (i.e. files + directories) to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 * @param   msTimeout           Timeout (in ms) to use for getting the data sent.
 */
int GuestDnDTarget::i_sendTransferData(GuestDnDSendCtx *pCtx, RTMSINTERVAL msTimeout)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
    AssertPtr(pCtx->pState);

#define REGISTER_CALLBACK(x)                                                  \
    do {                                                                      \
        vrc = pCtx->pState->setCallback(x, i_sendTransferDataCallback, pCtx); \
        if (RT_FAILURE(vrc))                                                  \
            return vrc;                                                       \
    } while (0)

#define UNREGISTER_CALLBACK(x)                        \
    do {                                              \
        int vrc2 = pCtx->pState->setCallback(x, NULL); \
        AssertRC(vrc2);                                \
    } while (0)

    int vrc = pCtx->Transfer.init(mData.mcbBlockSize);
    if (RT_FAILURE(vrc))
        return vrc;

    vrc = pCtx->EventCallback.Reset();
    if (RT_FAILURE(vrc))
        return vrc;

    /*
     * Register callbacks.
     */
    /* Guest callbacks. */
    REGISTER_CALLBACK(GUEST_DND_FN_CONNECT);
    REGISTER_CALLBACK(GUEST_DND_FN_DISCONNECT);
    REGISTER_CALLBACK(GUEST_DND_FN_GET_NEXT_HOST_MSG);
    REGISTER_CALLBACK(GUEST_DND_FN_EVT_ERROR);
    /* Host callbacks. */
    REGISTER_CALLBACK(HOST_DND_FN_HG_SND_DIR);
    if (m_pState->m_uProtocolVersion >= 2)
        REGISTER_CALLBACK(HOST_DND_FN_HG_SND_FILE_HDR);
    REGISTER_CALLBACK(HOST_DND_FN_HG_SND_FILE_DATA);

    do
    {
        /*
         * Extract transfer list from current meta data.
         */
        vrc = DnDTransferListAppendPathsFromBuffer(&pCtx->Transfer.List, DNDTRANSFERLISTFMT_URI,
                                                   (const char *)pCtx->Meta.pvData, pCtx->Meta.cbData, DND_PATH_SEPARATOR_STR,
                                                   DNDTRANSFERLIST_FLAGS_RECURSIVE);
        if (RT_FAILURE(vrc))
            break;

        /*
         * Update internal state to reflect everything we need to work with it.
         */
        pCtx->cbExtra                = DnDTransferListObjTotalBytes(&pCtx->Transfer.List);
        /* cbExtra can be 0, if all files are of 0 bytes size. */
        pCtx->Transfer.cObjToProcess = DnDTransferListObjCount(&pCtx->Transfer.List);
        AssertBreakStmt(pCtx->Transfer.cObjToProcess, vrc = VERR_INVALID_PARAMETER);

        /* Update the meta data to have the current root transfer entries in the right shape. */
        if (DnDMIMEHasFileURLs(pCtx->Meta.strFmt.c_str(), RTSTR_MAX))
        {
            /* Save original format we're still going to use after updating the actual meta data. */
            Utf8Str strFmt = pCtx->Meta.strFmt;

            /* Reset stale data. */
            pCtx->Meta.reset();

            void  *pvData;
            size_t cbData;
#ifdef DEBUG
            vrc = DnDTransferListGetRootsEx(&pCtx->Transfer.List, DNDTRANSFERLISTFMT_URI, "" /* pcszPathBase */,
                                            "\n" /* pcszSeparator */, (char **)&pvData, &cbData);
            AssertRCReturn(vrc, vrc);
            LogFlowFunc(("URI data:\n%s", (char *)pvData));
            RTMemFree(pvData);
            cbData = 0;
#endif
            vrc = DnDTransferListGetRoots(&pCtx->Transfer.List, DNDTRANSFERLISTFMT_URI,
                                          (char **)&pvData, &cbData);
            AssertRCReturn(vrc, vrc);

            /* pCtx->Meta now owns the allocated data. */
            pCtx->Meta.strFmt      = strFmt;
            pCtx->Meta.pvData      = pvData;
            pCtx->Meta.cbData      = cbData;
            pCtx->Meta.cbAllocated = cbData;
            pCtx->Meta.cbAnnounced = cbData;
        }

        /*
         * The first message always is the data header. The meta data itself then follows
         * and *only* contains the root elements of a transfer list.
         *
         * After the meta data we generate the messages required to send the
         * file/directory data itself.
         *
         * Note: Protocol < v3 use the first data message to tell what's being sent.
         */

        /*
         * Send the data header first.
         */
        if (m_pState->m_uProtocolVersion >= 3)
            vrc = i_sendMetaDataHeader(pCtx);

        /*
         * Send the (meta) data body.
         */
        if (RT_SUCCESS(vrc))
            vrc = i_sendMetaDataBody(pCtx);

        if (RT_SUCCESS(vrc))
        {
            vrc = waitForEvent(&pCtx->EventCallback, pCtx->pState, msTimeout);
            if (RT_SUCCESS(vrc))
                pCtx->pState->setProgress(100, DND_PROGRESS_COMPLETE, VINF_SUCCESS);
        }

    } while (0);

    /*
     * Unregister callbacks.
     */
    /* Guest callbacks. */
    UNREGISTER_CALLBACK(GUEST_DND_FN_CONNECT);
    UNREGISTER_CALLBACK(GUEST_DND_FN_DISCONNECT);
    UNREGISTER_CALLBACK(GUEST_DND_FN_GET_NEXT_HOST_MSG);
    UNREGISTER_CALLBACK(GUEST_DND_FN_EVT_ERROR);
    /* Host callbacks. */
    UNREGISTER_CALLBACK(HOST_DND_FN_HG_SND_DIR);
    if (m_pState->m_uProtocolVersion >= 2)
        UNREGISTER_CALLBACK(HOST_DND_FN_HG_SND_FILE_HDR);
    UNREGISTER_CALLBACK(HOST_DND_FN_HG_SND_FILE_DATA);

#undef REGISTER_CALLBACK
#undef UNREGISTER_CALLBACK

    if (RT_FAILURE(vrc))
    {
        if (vrc == VERR_CANCELLED) /* Transfer was cancelled by the host. */
        {
            /*
             * Now that we've cleaned up tell the guest side to cancel.
             * This does not imply we're waiting for the guest to react, as the
             * host side never must depend on anything from the guest.
             */
            int vrc2 = sendCancel();
            AssertRC(vrc2);

            LogRel2(("DnD: Sending transfer data to guest cancelled by user\n"));

            vrc2 = pCtx->pState->setProgress(100, DND_PROGRESS_CANCELLED, VINF_SUCCESS);
            AssertRC(vrc2);

            /* Cancelling is not an error, just set success here. */
            vrc  = VINF_SUCCESS;
        }
        else if (vrc != VERR_DND_GUEST_ERROR) /* Guest-side error are already handled in the callback. */
        {
            LogRel(("DnD: Sending transfer data to guest failed with vrc=%Rrc\n", vrc));
            int vrc2 = pCtx->pState->setProgress(100, DND_PROGRESS_ERROR, vrc,
                                                 GuestDnDTarget::i_hostErrorToString(vrc));
            AssertRC(vrc2);
        }
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Sends the next object of a transfer list to the guest.
 *
 * @returns VBox status code. VINF_EOF if the transfer list is complete.
 * @param   pCtx                Send context to use.
 * @param   pList               Transfer list to use.
 * @param   pMsg                Message to store send data into.
 */
int GuestDnDTarget::i_sendTransferListObject(GuestDnDSendCtx *pCtx, PDNDTRANSFERLIST pList, GuestDnDMsg *pMsg)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
    AssertPtrReturn(pList, VERR_INVALID_POINTER);
    AssertPtrReturn(pMsg, VERR_INVALID_POINTER);

    int vrc = updateProgress(pCtx, pCtx->pState);
    AssertRCReturn(vrc, vrc);

    PDNDTRANSFEROBJECT pObj = DnDTransferListObjGetFirst(pList);
    if (!pObj) /* Transfer complete? */
        return VINF_EOF;

    switch (DnDTransferObjectGetType(pObj))
    {
        case DNDTRANSFEROBJTYPE_DIRECTORY:
            vrc = i_sendDirectory(pCtx, pObj, pMsg);
            break;

        case DNDTRANSFEROBJTYPE_FILE:
            vrc = i_sendFile(pCtx, pObj, pMsg);
            break;

        default:
            AssertFailedStmt(vrc = VERR_NOT_SUPPORTED);
            break;
    }

    if (   RT_SUCCESS(vrc)
        && DnDTransferObjectIsComplete(pObj))
    {
        DnDTransferListObjRemove(pList, pObj);
        pObj = NULL;

        AssertReturn(pCtx->Transfer.cObjProcessed + 1 <= pCtx->Transfer.cObjToProcess, VERR_WRONG_ORDER);
        pCtx->Transfer.cObjProcessed++;

        pCtx->Transfer.fObjState = DND_OBJ_STATE_NONE;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Main function for sending raw data (e.g. text, RTF, ...) to the guest.
 *
 * @returns VBox status code.
 * @param   pCtx                Send context to use.
 * @param   msTimeout           Timeout (in ms) to use for getting the data sent.
 */
int GuestDnDTarget::i_sendRawData(GuestDnDSendCtx *pCtx, RTMSINTERVAL msTimeout)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
    NOREF(msTimeout);

    /** @todo At the moment we only allow sending up to 64K raw data.
     *        For protocol v1+v2: Fix this by using HOST_DND_FN_HG_SND_MORE_DATA.
     *        For protocol v3   : Send another HOST_DND_FN_HG_SND_DATA message. */
    if (!pCtx->Meta.cbData)
        return VINF_SUCCESS;

    int vrc = i_sendMetaDataHeader(pCtx);
    if (RT_SUCCESS(vrc))
        vrc = i_sendMetaDataBody(pCtx);

    int vrc2;
    if (RT_FAILURE(vrc))
    {
        LogRel(("DnD: Sending raw data to guest failed with vrc=%Rrc\n", vrc));
        vrc2 = pCtx->pState->setProgress(100 /* Percent */, DND_PROGRESS_ERROR, vrc,
                                         GuestDnDTarget::i_hostErrorToString(vrc));
    }
    else
        vrc2 = pCtx->pState->setProgress(100 /* Percent */, DND_PROGRESS_COMPLETE, vrc);
    AssertRC(vrc2);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Cancels sending DnD data.
 *
 * @returns VBox status code.
 * @param   aVeto               Whether cancelling was vetoed or not.
 *                              Not implemented yet.
 */
HRESULT GuestDnDTarget::cancel(BOOL *aVeto)
{
#if !defined(VBOX_WITH_DRAG_AND_DROP)
    ReturnComNotImplemented();
#else /* VBOX_WITH_DRAG_AND_DROP */

    LogRel2(("DnD: Sending cancelling request to the guest ...\n"));

    int vrc = GuestDnDBase::sendCancel();

    if (aVeto)
        *aVeto = FALSE; /** @todo Implement vetoing. */

    HRESULT hrc = RT_SUCCESS(vrc) ? S_OK : VBOX_E_DND_ERROR;

    LogFlowFunc(("hrc=%Rhrc\n", hrc));
    return hrc;
#endif /* VBOX_WITH_DRAG_AND_DROP */
}