summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/include/GuestDnDPrivate.h
blob: ca5d3a96763412d8ba736a55aea6d866ba43f8af (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
/* $Id: GuestDnDPrivate.h $ */
/** @file
 * Private guest drag and drop code, used by GuestDnDTarget +
 * GuestDnDSource.
 */

/*
 * Copyright (C) 2011-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
 */

#ifndef MAIN_INCLUDED_GuestDnDPrivate_h
#define MAIN_INCLUDED_GuestDnDPrivate_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif

#include <iprt/dir.h>
#include <iprt/file.h>
#include <iprt/path.h>

#include <VBox/hgcmsvc.h> /* For PVBOXHGCMSVCPARM. */
#include <VBox/GuestHost/DragAndDrop.h>
#include <VBox/GuestHost/DragAndDropDefs.h>
#include <VBox/HostServices/DragAndDropSvc.h>

/**
 * Forward prototype declarations.
 */
class Guest;
class GuestDnDBase;
class GuestDnDState;
class GuestDnDSource;
class GuestDnDTarget;
class Progress;

/**
 * Type definitions.
 */

/** List (vector) of MIME types. */
typedef std::vector<com::Utf8Str> GuestDnDMIMEList;

/**
 * Class to handle a guest DnD callback event.
 */
class GuestDnDCallbackEvent
{
public:

    GuestDnDCallbackEvent(void)
        : m_SemEvent(NIL_RTSEMEVENT)
        , m_vrc(VINF_SUCCESS) { }

    virtual ~GuestDnDCallbackEvent(void);

public:

    int Reset(void);

    int Notify(int vrc = VINF_SUCCESS);

    int Result(void) const { return m_vrc; }

    int Wait(RTMSINTERVAL msTimeout);

protected:

    /** Event semaphore to notify on error/completion. */
    RTSEMEVENT m_SemEvent;
    /** Callback result. */
    int        m_vrc;
};

/**
 * Struct for handling the (raw) meta data.
 */
struct GuestDnDMetaData
{
    GuestDnDMetaData(void)
        : pvData(NULL)
        , cbData(0)
        , cbAllocated(0)
        , cbAnnounced(0) { }

    virtual ~GuestDnDMetaData(void)
    {
        reset();
    }

    /**
     * Adds new meta data.
     *
     * @returns New (total) meta data size in bytes.
     * @param   pvDataAdd       Pointer of data to add.
     * @param   cbDataAdd       Size (in bytes) of data to add.
     */
    size_t add(const void *pvDataAdd, size_t cbDataAdd)
    {
        LogFlowThisFunc(("cbAllocated=%zu, cbAnnounced=%zu, pvDataAdd=%p, cbDataAdd=%zu\n",
                         cbAllocated, cbAnnounced, pvDataAdd, cbDataAdd));
        if (!cbDataAdd)
            return 0;
        AssertPtrReturn(pvDataAdd, 0);

        const size_t cbAllocatedTmp = cbData + cbDataAdd;
        if (cbAllocatedTmp > cbAllocated)
        {
            int vrc = resize(cbAllocatedTmp);
            if (RT_FAILURE(vrc))
                return 0;
        }

        Assert(cbAllocated >= cbData + cbDataAdd);
        memcpy((uint8_t *)pvData + cbData, pvDataAdd, cbDataAdd);

        cbData     += cbDataAdd;
        cbAnnounced = cbData;

        return cbData;
    }

    /**
     * Adds new meta data.
     *
     * @returns New (total) meta data size in bytes.
     * @param   vecAdd          Meta data to add.
     */
    size_t add(const std::vector<BYTE> &vecAdd)
    {
        if (!vecAdd.size())
            return 0;

        if (vecAdd.size() > UINT32_MAX) /* Paranoia. */
            return 0;

        return add(&vecAdd.front(), (uint32_t)vecAdd.size());
    }

    /**
     * Resets (clears) all data.
     */
    void reset(void)
    {
        strFmt = "";

        if (pvData)
        {
            Assert(cbAllocated);
            RTMemFree(pvData);
            pvData = NULL;
        }

        cbData      = 0;
        cbAllocated = 0;
        cbAnnounced = 0;
    }

    /**
     * Resizes the allocation size.
     *
     * @returns VBox status code.
     * @param   cbSize          New allocation size (in bytes).
     */
    int resize(size_t cbSize)
    {
        if (!cbSize)
        {
            reset();
            return VINF_SUCCESS;
        }

        if (cbSize == cbAllocated)
            return VINF_SUCCESS;

        cbSize = RT_ALIGN_Z(cbSize, PAGE_SIZE);

        if (cbSize > _32M) /* Meta data can be up to 32MB. */
            return VERR_BUFFER_OVERFLOW;

        void *pvTmp = NULL;
        if (!cbAllocated)
        {
            Assert(cbData == 0);
            pvTmp = RTMemAllocZ(cbSize);
        }
        else
        {
            AssertPtr(pvData);
            pvTmp = RTMemRealloc(pvData, cbSize);
        }

        if (pvTmp)
        {
            pvData      = pvTmp;
            cbAllocated = cbSize;
            return VINF_SUCCESS;
        }

        return VERR_NO_MEMORY;
    }

    /** Format string of this meta data. */
    com::Utf8Str strFmt;
    /** Pointer to allocated meta data. */
    void        *pvData;
    /** Used bytes of meta data. Must not exceed cbAllocated. */
    size_t       cbData;
    /** Size (in bytes) of allocated meta data. */
    size_t       cbAllocated;
    /** Size (in bytes) of announced meta data. */
    size_t       cbAnnounced;
};

/**
 * Struct for accounting shared DnD data to be sent/received.
 */
struct GuestDnDData
{
    GuestDnDData(void)
        : cbExtra(0)
        , cbProcessed(0) { }

    virtual ~GuestDnDData(void)
    {
        reset();
    }

    /**
     * Adds processed data to the internal accounting.
     *
     * @returns New processed data size.
     * @param   cbDataAdd       Bytes to add as done processing.
     */
    size_t addProcessed(size_t cbDataAdd)
    {
        const size_t cbTotal = getTotalAnnounced(); RT_NOREF(cbTotal);
        AssertReturn(cbProcessed + cbDataAdd <= cbTotal, 0);
        cbProcessed += cbDataAdd;
        return cbProcessed;
    }

    /**
     * Returns whether all data has been processed or not.
     *
     * @returns \c true if all data has been processed, \c false if not.
     */
    bool isComplete(void) const
    {
        const size_t cbTotal = getTotalAnnounced();
        LogFlowFunc(("cbProcessed=%zu, cbTotal=%zu\n", cbProcessed, cbTotal));
        AssertReturn(cbProcessed <= cbTotal, true);
        return (cbProcessed == cbTotal);
    }

    /**
     * Returns the percentage (0-100) of the already processed data.
     *
     * @returns Percentage (0-100) of the already processed data.
     */
    uint8_t getPercentComplete(void) const
    {
        const size_t cbTotal = getTotalAnnounced();
        return (uint8_t)(cbProcessed * 100 / RT_MAX(cbTotal, 1));
    }

    /**
     * Returns the remaining (outstanding) data left for processing.
     *
     * @returns Remaining (outstanding) data (in bytes) left for processing.
     */
    size_t getRemaining(void) const
    {
        const size_t cbTotal = getTotalAnnounced();
        AssertReturn(cbProcessed <= cbTotal, 0);
        return cbTotal - cbProcessed;
    }

    /**
     * Returns the total data size (in bytes) announced.
     *
     * @returns Total data size (in bytes) announced.
     */
    size_t getTotalAnnounced(void) const
    {
        return Meta.cbAnnounced + cbExtra;
    }

    /**
     * Returns the total data size (in bytes) available.
     * For receiving data, this represents the already received data.
     * For sending data, this represents the data left to send.
     *
     * @returns Total data size (in bytes) available.
     */
    size_t getTotalAvailable(void) const
    {
        return Meta.cbData + cbExtra;
    }

    /**
     * Resets all data.
     */
    void reset(void)
    {
        Meta.reset();

        cbExtra     = 0;
        cbProcessed = 0;
    }

    /** For storing the actual meta data.
     *  This might be an URI list or just plain raw data,
     *  according to the format being sent. */
    GuestDnDMetaData   Meta;
    /** Extra data to send/receive (in bytes). Can be 0 for raw data.
     *  For (file) transfers this is the total size for all files. */
    size_t             cbExtra;
    /** Overall size (in bytes) of processed data. */
    size_t             cbProcessed;
};

/** Initial object context state / no state set. */
#define DND_OBJ_STATE_NONE           0
/** The header was received / sent. */
#define DND_OBJ_STATE_HAS_HDR        RT_BIT(0)
/** Validation mask for object context state. */
#define DND_OBJ_STATE_VALID_MASK     UINT32_C(0x00000001)

/**
 * Base class for keeping around DnD (file) transfer data.
 * Used for sending / receiving transfer data.
 */
struct GuestDnDTransferData
{

public:

    GuestDnDTransferData(void)
        : cObjToProcess(0)
        , cObjProcessed(0)
        , pvScratchBuf(NULL)
        , cbScratchBuf(0) { }

    virtual ~GuestDnDTransferData(void)
    {
        destroy();
    }

    /**
     * Initializes a transfer data object.
     *
     * @param   cbBuf           Scratch buffer size (in bytes) to use.
     *                          If not specified, DND_DEFAULT_CHUNK_SIZE will be used.
     */
    int init(size_t cbBuf = DND_DEFAULT_CHUNK_SIZE)
    {
        reset();

        pvScratchBuf = RTMemAlloc(cbBuf);
        if (!pvScratchBuf)
            return VERR_NO_MEMORY;

        cbScratchBuf = cbBuf;
        return VINF_SUCCESS;
    }

    /**
     * Destroys a transfer data object.
     */
    void destroy(void)
    {
        reset();

        if (pvScratchBuf)
        {
            Assert(cbScratchBuf);
            RTMemFree(pvScratchBuf);
            pvScratchBuf = NULL;
        }
        cbScratchBuf = 0;
    }

    /**
     * Resets a transfer data object.
     */
    void reset(void)
    {
        LogFlowFuncEnter();

        cObjToProcess = 0;
        cObjProcessed = 0;
    }

    /**
     * Returns whether this transfer object is complete or not.
     *
     * @returns \c true if complete, \c false if not.
     */
    bool isComplete(void) const
    {
        return (cObjProcessed == cObjToProcess);
    }

    /** Number of objects to process. */
    uint64_t cObjToProcess;
    /** Number of objects already processed. */
    uint64_t cObjProcessed;
    /** Pointer to an optional scratch buffer to use for
     *  doing the actual chunk transfers. */
    void    *pvScratchBuf;
    /** Size (in bytes) of scratch buffer. */
    size_t   cbScratchBuf;
};

/**
 * Class for keeping around DnD transfer send data (Host -> Guest).
 */
struct GuestDnDTransferSendData : public GuestDnDTransferData
{
    GuestDnDTransferSendData()
        : fObjState(0)
    {
        RT_ZERO(List);
        int vrc2 = DnDTransferListInit(&List);
        AssertRC(vrc2);
    }

    virtual ~GuestDnDTransferSendData()
    {
        destroy();
    }

    /**
     * Destroys the object.
     */
    void destroy(void)
    {
        DnDTransferListDestroy(&List);
    }

    /**
     * Resets the object.
     */
    void reset(void)
    {
        DnDTransferListReset(&List);
        fObjState = 0;

        GuestDnDTransferData::reset();
    }

    /** Transfer List to handle. */
    DNDTRANSFERLIST                     List;
    /** Current state of object in transfer.
     *  This is needed for keeping compatibility to old(er) DnD HGCM protocols.
     *
     *  At the moment we only support transferring one object at a time. */
    uint32_t                            fObjState;
};

/**
 * Context structure for sending data to the guest.
 */
struct GuestDnDSendCtx : public GuestDnDData
{
    GuestDnDSendCtx(void);

    /**
     * Resets the object.
     */
    void reset(void);

    /** Pointer to guest target class this context belongs to. */
    GuestDnDTarget                     *pTarget;
    /** Pointer to guest state this context belongs to. */
    GuestDnDState                      *pState;
    /** Target (VM) screen ID. */
    uint32_t                            uScreenID;
    /** Transfer data structure. */
    GuestDnDTransferSendData            Transfer;
    /** Callback event to use. */
    GuestDnDCallbackEvent               EventCallback;
};

struct GuestDnDTransferRecvData : public GuestDnDTransferData
{
    GuestDnDTransferRecvData()
    {
        RT_ZERO(DroppedFiles);
        int vrc2 = DnDDroppedFilesInit(&DroppedFiles);
        AssertRC(vrc2);

        RT_ZERO(List);
        vrc2 = DnDTransferListInit(&List);
        AssertRC(vrc2);

        RT_ZERO(ObjCur);
        vrc2 = DnDTransferObjectInit(&ObjCur);
        AssertRC(vrc2);
    }

    virtual ~GuestDnDTransferRecvData()
    {
        destroy();
    }

    /**
     * Destroys the object.
     */
    void destroy(void)
    {
        DnDTransferListDestroy(&List);
    }

    /**
     * Resets the object.
     */
    void reset(void)
    {
        DnDDroppedFilesClose(&DroppedFiles);
        DnDTransferListReset(&List);
        DnDTransferObjectReset(&ObjCur);

        GuestDnDTransferData::reset();
    }

    /** The "VirtualBox Dropped Files" directory on the host we're going
     *  to utilize for transferring files from guest to the host. */
    DNDDROPPEDFILES                     DroppedFiles;
    /** Transfer List to handle.
     *  Currently we only support one transfer list at a time. */
    DNDTRANSFERLIST                     List;
    /** Current transfer object being handled.
     *  Currently we only support one transfer object at a time. */
    DNDTRANSFEROBJECT                   ObjCur;
};

/**
 * Context structure for receiving data from the guest.
 */
struct GuestDnDRecvCtx : public GuestDnDData
{
    GuestDnDRecvCtx(void);

    /**
     * Resets the object.
     */
    void reset(void);

    /** Pointer to guest source class this context belongs to. */
    GuestDnDSource                     *pSource;
    /** Pointer to guest state this context belongs to. */
    GuestDnDState                      *pState;
    /** Formats offered by the guest (and supported by the host). */
    GuestDnDMIMEList                    lstFmtOffered;
    /** Original drop format requested to receive from the guest. */
    com::Utf8Str                        strFmtReq;
    /** Intermediate drop format to be received from the guest.
     *  Some original drop formats require a different intermediate
     *  drop format:
     *
     *  Receiving a file link as "text/plain"  requires still to
     *  receive the file from the guest as "text/uri-list" first,
     *  then pointing to the file path on the host with the data
     *  in "text/plain" format returned. */
    com::Utf8Str                        strFmtRecv;
    /** Desired drop action to perform on the host.
     *  Needed to tell the guest if data has to be
     *  deleted e.g. when moving instead of copying. */
    VBOXDNDACTION                       enmAction;
    /** Transfer data structure. */
    GuestDnDTransferRecvData            Transfer;
    /** Callback event to use. */
    GuestDnDCallbackEvent               EventCallback;
};

/**
 * Class for maintainig a (buffered) guest DnD message.
 */
class GuestDnDMsg
{
public:

    GuestDnDMsg(void)
        : uMsg(0)
        , cParms(0)
        , cParmsAlloc(0)
        , paParms(NULL) { }

    virtual ~GuestDnDMsg(void)
    {
        reset();
    }

public:

    /**
     * Appends a new HGCM parameter to the message and returns the pointer to it.
     */
    PVBOXHGCMSVCPARM getNextParam(void)
    {
        if (cParms >= cParmsAlloc)
        {
            if (!paParms)
                paParms = (PVBOXHGCMSVCPARM)RTMemAlloc(4 * sizeof(VBOXHGCMSVCPARM));
            else
                paParms = (PVBOXHGCMSVCPARM)RTMemRealloc(paParms, (cParmsAlloc + 4) * sizeof(VBOXHGCMSVCPARM));
            if (!paParms)
                throw VERR_NO_MEMORY;
            RT_BZERO(&paParms[cParmsAlloc], 4 * sizeof(VBOXHGCMSVCPARM));
            cParmsAlloc += 4;
        }

        return &paParms[cParms++];
    }

    /**
     * Returns the current parameter count.
     *
     * @returns Current parameter count.
     */
    uint32_t getCount(void) const { return cParms; }

    /**
     * Returns the pointer to the beginning of the HGCM parameters array. Use with care.
     *
     * @returns Pointer to the beginning of the HGCM parameters array.
     */
    PVBOXHGCMSVCPARM getParms(void) const { return paParms; }

    /**
     * Returns the message type.
     *
     * @returns Message type.
     */
    uint32_t getType(void) const { return uMsg; }

    /**
     * Resets the object.
     */
    void reset(void)
    {
        if (paParms)
        {
            /* Remove deep copies. */
            for (uint32_t i = 0; i < cParms; i++)
            {
                if (   paParms[i].type == VBOX_HGCM_SVC_PARM_PTR
                    && paParms[i].u.pointer.size)
                {
                    AssertPtr(paParms[i].u.pointer.addr);
                    RTMemFree(paParms[i].u.pointer.addr);
                }
            }

            RTMemFree(paParms);
            paParms = NULL;
        }

        uMsg = cParms = cParmsAlloc = 0;
    }

    /**
     * Appends a new message parameter of type pointer.
     *
     * @returns VBox status code.
     * @param   pvBuf           Pointer to data to use.
     * @param   cbBuf           Size (in bytes) of data to use.
     */
    int appendPointer(void *pvBuf, uint32_t cbBuf)
    {
        PVBOXHGCMSVCPARM pParm = getNextParam();
        if (!pParm)
            return VERR_NO_MEMORY;

        void *pvTmp = NULL;
        if (cbBuf)
        {
            AssertPtr(pvBuf);
            pvTmp = RTMemDup(pvBuf, cbBuf);
            if (!pvTmp)
                return VERR_NO_MEMORY;
        }

        HGCMSvcSetPv(pParm, pvTmp, cbBuf);
        return VINF_SUCCESS;
    }

    /**
     * Appends a new message parameter of type string.
     *
     * @returns VBox status code.
     * @param   pszString       Pointer to string data to use.
     */
    int appendString(const char *pszString)
    {
        PVBOXHGCMSVCPARM pParm = getNextParam();
        if (!pParm)
            return VERR_NO_MEMORY;

        char *pszTemp = RTStrDup(pszString);
        if (!pszTemp)
            return VERR_NO_MEMORY;

        HGCMSvcSetStr(pParm, pszTemp);
        return VINF_SUCCESS;
    }

    /**
     * Appends a new message parameter of type uint32_t.
     *
     * @returns VBox status code.
     * @param   u32Val          uint32_t value to use.
     */
    int appendUInt32(uint32_t u32Val)
    {
        PVBOXHGCMSVCPARM pParm = getNextParam();
        if (!pParm)
            return VERR_NO_MEMORY;

        HGCMSvcSetU32(pParm, u32Val);
        return VINF_SUCCESS;
    }

    /**
     * Appends a new message parameter of type uint64_t.
     *
     * @returns VBox status code.
     * @param   u64Val          uint64_t value to use.
     */
    int appendUInt64(uint64_t u64Val)
    {
        PVBOXHGCMSVCPARM pParm = getNextParam();
        if (!pParm)
            return VERR_NO_MEMORY;

        HGCMSvcSetU64(pParm, u64Val);
        return VINF_SUCCESS;
    }

    /**
     * Sets the HGCM message type (function number).
     *
     * @param   uMsgType        Message type to set.
     */
    void setType(uint32_t uMsgType) { uMsg = uMsgType; }

protected:

    /** Message type. */
    uint32_t                    uMsg;
    /** Message parameters. */
    uint32_t                    cParms;
    /** Size of array. */
    uint32_t                    cParmsAlloc;
    /** Array of HGCM parameters */
    PVBOXHGCMSVCPARM            paParms;
};

/** Guest DnD callback function definition. */
typedef DECLCALLBACKPTR(int, PFNGUESTDNDCALLBACK,(uint32_t uMsg, void *pvParms, size_t cbParms, void *pvUser));

/**
 * Structure for keeping a guest DnD callback.
 * Each callback can handle one HGCM message, however, multiple HGCM messages can be registered
 * to the same callback (function).
 */
typedef struct GuestDnDCallback
{
    GuestDnDCallback(void)
        : uMessgage(0)
        , pfnCallback(NULL)
        , pvUser(NULL) { }

    GuestDnDCallback(PFNGUESTDNDCALLBACK pvCB, uint32_t uMsg, void *pvUsr = NULL)
        : uMessgage(uMsg)
        , pfnCallback(pvCB)
        , pvUser(pvUsr) { }

    /** The HGCM message ID to handle. */
    uint32_t             uMessgage;
    /** Pointer to callback function. */
    PFNGUESTDNDCALLBACK  pfnCallback;
    /** Pointer to user-supplied data. */
    void                *pvUser;
} GuestDnDCallback;

/** Contains registered callback pointers for specific HGCM message types. */
typedef std::map<uint32_t, GuestDnDCallback> GuestDnDCallbackMap;

/**
 * Class for keeping a DnD guest state around.
 */
class GuestDnDState
{

public:
    DECLARE_TRANSLATE_METHODS(GuestDnDState)

    GuestDnDState(const ComObjPtr<Guest>& pGuest);
    virtual ~GuestDnDState(void);

public:

    VBOXDNDSTATE get(void) const { return m_enmState; }
    int set(VBOXDNDSTATE enmState) { LogRel3(("DnD: State %s -> %s\n", DnDStateToStr(m_enmState), DnDStateToStr(enmState))); m_enmState = enmState; return 0; }
    void lock() { RTCritSectEnter(&m_CritSect); };
    void unlock() { RTCritSectLeave(&m_CritSect); };

    /** @name Guest response handling.
     * @{ */
    int notifyAboutGuestResponse(int vrcGuest = VINF_SUCCESS);
    int waitForGuestResponseEx(RTMSINTERVAL msTimeout = 3000, int *pvrcGuest = NULL);
    int waitForGuestResponse(int *pvrcGuest = NULL);
    /** @} */

    void setActionsAllowed(VBOXDNDACTIONLIST a) { m_dndLstActionsAllowed = a; }
    VBOXDNDACTIONLIST getActionsAllowed(void) const { return m_dndLstActionsAllowed; }

    void setActionDefault(VBOXDNDACTION a) { m_dndActionDefault = a; }
    VBOXDNDACTION getActionDefault(void) const { return m_dndActionDefault; }

    void setFormats(const GuestDnDMIMEList &lstFormats) { m_lstFormats = lstFormats; }
    GuestDnDMIMEList formats(void) const { return m_lstFormats; }

    void reset(void);

    /** @name Callback handling.
     * @{ */
    static DECLCALLBACK(int) i_defaultCallback(uint32_t uMsg, void *pvParms, size_t cbParms, void *pvUser);
    int setCallback(uint32_t uMsg, PFNGUESTDNDCALLBACK pfnCallback, void *pvUser = NULL);
    /** @} */

    /** @name Progress handling.
     * @{ */
    bool isProgressCanceled(void) const;
    bool isProgressRunning(void) const;
    int setProgress(unsigned uPercentage, uint32_t uStatus, int vrcOp = VINF_SUCCESS, const Utf8Str &strMsg = Utf8Str::Empty);
    HRESULT resetProgress(const ComObjPtr<Guest>& pParent, const Utf8Str &strDesc);
    HRESULT queryProgressTo(IProgress **ppProgress);
    /** @} */

public:

    /** @name HGCM callback handling.
       @{ */
    int onDispatch(uint32_t u32Function, void *pvParms, uint32_t cbParms);
    /** @}  */

public:

    /** Pointer to context this class is tied to. */
    void                 *m_pvCtx;
    RTCRITSECT            m_CritSect;
    /** The current state we're in. */
    VBOXDNDSTATE          m_enmState;
    /** The DnD protocol version to use, depending on the
     *  installed Guest Additions. See DragAndDropSvc.h for
     *  a protocol changelog. */
    uint32_t              m_uProtocolVersion;
    /** The guest feature flags reported to the host (VBOX_DND_GF_XXX).  */
    uint64_t              m_fGuestFeatures0;
    /** Event for waiting for response. */
    RTSEMEVENT            m_EventSem;
    /** Last error reported from guest.
     *  Set to VERR_IPE_UNINITIALIZED_STATUS if not set yet. */
    int                   m_vrcGuest;
    /** Default action to perform in case of a
     *  successful drop. */
    VBOXDNDACTION         m_dndActionDefault;
    /** Actions supported by the guest in case of a successful drop. */
    VBOXDNDACTIONLIST     m_dndLstActionsAllowed;
    /** Format(s) requested/supported from the guest. */
    GuestDnDMIMEList      m_lstFormats;
    /** Pointer to IGuest parent object. */
    ComObjPtr<Guest>      m_pParent;
    /** Pointer to associated progress object. Optional. */
    ComObjPtr<Progress>   m_pProgress;
    /** Callback map. */
    GuestDnDCallbackMap   m_mapCallbacks;
};

/**
 * Private singleton class for the guest's DnD implementation.
 *
 * Can't be instanciated directly, only via the factory pattern.
 * Keeps track of all ongoing DnD transfers.
 */
class GuestDnD
{
public:

    /**
     * Creates the Singleton GuestDnD object.
     *
     * @returns Newly created Singleton object, or NULL on failure.
     */
    static GuestDnD *createInstance(const ComObjPtr<Guest>& pGuest)
    {
        Assert(NULL == GuestDnD::s_pInstance);
        GuestDnD::s_pInstance = new GuestDnD(pGuest);
        return GuestDnD::s_pInstance;
    }

    /**
     * Destroys the Singleton GuestDnD object.
     */
    static void destroyInstance(void)
    {
        if (GuestDnD::s_pInstance)
        {
            delete GuestDnD::s_pInstance;
            GuestDnD::s_pInstance = NULL;
        }
    }

    /**
     * Returns the Singleton GuestDnD object.
     *
     * @returns Pointer to Singleton GuestDnD object, or NULL if not created yet.
     */
    static inline GuestDnD *getInstance(void)
    {
        AssertPtr(GuestDnD::s_pInstance);
        return GuestDnD::s_pInstance;
    }

protected:

    /** List of registered DnD sources. */
    typedef std::list< ComObjPtr<GuestDnDSource> > GuestDnDSrcList;
    /** List of registered DnD targets. */
    typedef std::list< ComObjPtr<GuestDnDTarget> > GuestDnDTgtList;

    /** Constructor; will throw vrc on failure. */
    GuestDnD(const ComObjPtr<Guest>& pGuest);
    virtual ~GuestDnD(void);

public:

    /** @name Public helper functions.
     * @{ */
    HRESULT           adjustScreenCoordinates(ULONG uScreenId, ULONG *puX, ULONG *puY) const;
    GuestDnDState    *getState(uint32_t = 0) const;
    int               hostCall(uint32_t u32Function, uint32_t cParms, PVBOXHGCMSVCPARM paParms) const;
    GuestDnDMIMEList  defaultFormats(void) const { return m_strDefaultFormats; }
    /** @}  */

    /** @name Source / target management.
     * @{ */
    int               registerSource(const ComObjPtr<GuestDnDSource> &Source);
    int               unregisterSource(const ComObjPtr<GuestDnDSource> &Source);
    size_t            getSourceCount(void);

    int               registerTarget(const ComObjPtr<GuestDnDTarget> &Target);
    int               unregisterTarget(const ComObjPtr<GuestDnDTarget> &Target);
    size_t            getTargetCount(void);
    /** @}  */

public:

    /** @name Static low-level HGCM callback handler.
     * @{ */
    static DECLCALLBACK(int)   notifyDnDDispatcher(void *pvExtension, uint32_t u32Function, void *pvParms, uint32_t cbParms);
    /** @}  */

    /** @name Static helper methods.
     * @{ */
    static bool                     isFormatInFormatList(const com::Utf8Str &strFormat, const GuestDnDMIMEList &lstFormats);
    static GuestDnDMIMEList         toFormatList(const com::Utf8Str &strFormats, const com::Utf8Str &strSep = DND_FORMATS_SEPARATOR_STR);
    static com::Utf8Str             toFormatString(const GuestDnDMIMEList &lstFormats, const com::Utf8Str &strSep = DND_FORMATS_SEPARATOR_STR);
    static GuestDnDMIMEList         toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const GuestDnDMIMEList &lstFormatsWanted);
    static GuestDnDMIMEList         toFilteredFormatList(const GuestDnDMIMEList &lstFormatsSupported, const com::Utf8Str &strFormatsWanted);
    static DnDAction_T              toMainAction(VBOXDNDACTION dndAction);
    static std::vector<DnDAction_T> toMainActions(VBOXDNDACTIONLIST dndActionList);
    static VBOXDNDACTION            toHGCMAction(DnDAction_T enmAction);
    static void                     toHGCMActions(DnDAction_T enmDefAction, VBOXDNDACTION *pDefAction, const std::vector<DnDAction_T> vecAllowedActions, VBOXDNDACTIONLIST *pLstAllowedActions);
    /** @}  */

protected:

    /** @name Singleton properties.
     * @{ */
    /** List of supported default MIME/Content-type formats. */
    GuestDnDMIMEList            m_strDefaultFormats;
    /** Pointer to guest implementation. */
    const ComObjPtr<Guest>      m_pGuest;
    /** The current state from the guest. At the
     *  moment we only support only state a time (ARQ-style). */
    GuestDnDState              *m_pState;
    /** Critical section to serialize access. */
    RTCRITSECT                  m_CritSect;
    /** Number of active transfers (guest->host or host->guest). */
    uint32_t                    m_cTransfersPending;
    GuestDnDSrcList             m_lstSrc;
    GuestDnDTgtList             m_lstTgt;
    /** @}  */

private:

    /** Static pointer to singleton instance. */
    static GuestDnD           *s_pInstance;
};

/** Access to the GuestDnD's singleton instance. */
#define GuestDnDInst() GuestDnD::getInstance()

/** List of pointers to guest DnD Messages. */
typedef std::list<GuestDnDMsg *> GuestDnDMsgList;

/**
 * IDnDBase class implementation for sharing code between
 * IGuestDnDSource and IGuestDnDTarget implementation.
 */
class GuestDnDBase
{
protected:

    GuestDnDBase(VirtualBoxBase *pBase);

    virtual ~GuestDnDBase(void);

protected:

    /** Shared (internal) IDnDBase method implementations.
     * @{ */
    bool i_isFormatSupported(const com::Utf8Str &aFormat) const;
    const GuestDnDMIMEList &i_getFormats(void) const;
    HRESULT i_addFormats(const GuestDnDMIMEList &aFormats);
    HRESULT i_removeFormats(const GuestDnDMIMEList &aFormats);
    /** @}  */

    /** @name Error handling.
     * @{ */
    HRESULT i_setErrorV(int vrc, const char *pcszMsgFmt, va_list va);
    HRESULT i_setError(int vrc, const char *pcszMsgFmt, ...);
    HRESULT i_setErrorAndReset(const char *pcszMsgFmt, ...);
    HRESULT i_setErrorAndReset(int vrc, const char *pcszMsgFmt, ...);
    /** @}  */

protected:

    /** @name Pure virtual functions needed to be implemented by the actual (derived) implementation.
     * @{ */
    virtual void i_reset(void) = 0;
    /** @}  */

protected:

    /** @name Functions for handling a simple host HGCM message queue.
     * @{ */
    int msgQueueAdd(GuestDnDMsg *pMsg);
    GuestDnDMsg *msgQueueGetNext(void);
    void msgQueueRemoveNext(void);
    void msgQueueClear(void);
    /** @}  */

    int sendCancel(void);
    int updateProgress(GuestDnDData *pData, GuestDnDState *pState, size_t cbDataAdd = 0);
    int waitForEvent(GuestDnDCallbackEvent *pEvent, GuestDnDState *pState, RTMSINTERVAL msTimeout);

protected:

    /** Pointer to base class to use for stuff like error handlng. */
    VirtualBoxBase                 *m_pBase;
    /** @name Public attributes (through getters/setters).
     * @{ */
    /** Pointer to guest implementation. */
    const ComObjPtr<Guest>          m_pGuest;
    /** List of supported MIME types by the source. */
    GuestDnDMIMEList                m_lstFmtSupported;
    /** List of offered MIME types to the counterpart. */
    GuestDnDMIMEList                m_lstFmtOffered;
    /** Whether the object still is in pending state. */
    bool                            m_fIsPending;
    /** Pointer to state bound to this object. */
    GuestDnDState                  *m_pState;
    /** @}  */

    /**
     * Internal stuff.
     */
    struct
    {
        /** Outgoing message queue (FIFO). */
        GuestDnDMsgList             lstMsgOut;
    } m_DataBase;
};
#endif /* !MAIN_INCLUDED_GuestDnDPrivate_h */