summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VirtualBox/src/globals/COMDefs.h
blob: 57c99266d3dcdc979ac5b8a7ad7f11f736c4118d (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
/* $Id$ */
/** @file
 * VBox Qt GUI - Various COM definitions and COM wrapper class declarations.
 *
 * This header is used in conjunction with the header generated from
 * XIDL expressed interface definitions to provide cross-platform Qt-based
 * interface wrapper classes.
 */

/*
 * Copyright (C) 2006-2020 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#ifndef FEQT_INCLUDED_SRC_globals_COMDefs_h
#define FEQT_INCLUDED_SRC_globals_COMDefs_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif

/** @defgroup   grp_QT_COM  Qt-COM Support Layer
 * @{
 *
 * The Qt-COM support layer provides a set of definitions and smart classes for
 * writing simple, clean and platform-independent code to access COM/XPCOM
 * components through exposed COM interfaces. This layer is based on the
 * COM/XPCOM Abstraction Layer library (the VBoxCOM glue library defined in
 * include/VBox/com and implemented in src/VBox/Main/glue).
 *
 * ...
 *
 * @defgroup   grp_QT_COM_arrays    Arrays
 * @{
 *
 * COM/XPCOM arrays are mapped to QVector objects. QVector templates declared
 * with a type that corresponds to the COM type of elements in the array using
 * normal Qt-COM type mapping rules. Here is a code example that demonstrates
 * how to call interface methods that take and return arrays (this example is
 * based on examples given in @ref grp_COM_arrays):
 * @code

    CSomething component;

    // ...

    QVector<LONG> in(3);
    in[0] = -1;
    in[1] = -2;
    in[2] = -3;

    QVector<LONG> out;
    QVector<LONG> ret;

    ret = component.TestArrays(in, out);

    for (size_t i = 0; i < ret.size(); ++ i)
        LogFlow(("*** ret[%u]=%d\n", i, ret[i]));

 * @endcode
 * @}
 */

/* Both VBox/com/assert.h and qglobal.h contain a definition of ASSERT.
 * Either of them can be already included here, so try to shut them up.  */
#undef ASSERT

#include <VBox/com/com.h>
#include <VBox/com/array.h>

#undef ASSERT

/* Qt includes */
#include <QString>
#include <QUuid>
#include <QVector>

/* GUI includes: */
#include "UILibraryDefs.h"

/*
 * Additional COM / XPCOM defines and includes
 */

#if !defined(VBOX_WITH_XPCOM)

#else /* !defined(VBOX_WITH_XPCOM) */

#include <nsXPCOM.h>
#include <nsMemory.h>
#include <nsIComponentManager.h>

class XPCOMEventQSocketListener;

#endif /* !defined(VBOX_WITH_XPCOM) */

/////////////////////////////////////////////////////////////////////////////

class CVirtualBoxErrorInfo;

/** Represents extended error information */
class SHARED_LIBRARY_STUFF COMErrorInfo
{
public:

    COMErrorInfo()
        : mIsNull(true),
          mIsBasicAvailable(false),
          mIsFullAvailable(false),
          mResultCode(S_OK),
          m_pNext(NULL)
    {}

    COMErrorInfo(const COMErrorInfo &info)
    {
        copyFrom(info);
    }

    COMErrorInfo(const CVirtualBoxErrorInfo &info)
    {
        init(info);
    }

    ~COMErrorInfo()
    {
        cleanup();
    }

    COMErrorInfo& operator=(const COMErrorInfo &info)
    {
        cleanup();
        copyFrom(info);
        return *this;
    }

    bool isNull() const { return mIsNull; }

    bool isBasicAvailable() const { return mIsBasicAvailable; }
    bool isFullAvailable() const { return mIsFullAvailable; }

    HRESULT resultCode() const { return mResultCode; }
    QUuid interfaceID() const { return mInterfaceID; }
    QString component() const { return mComponent; }
    QString text() const { return mText; }

    const COMErrorInfo *next() const { return m_pNext; }

    QString interfaceName() const { return mInterfaceName; }
    QUuid calleeIID() const { return mCalleeIID; }
    QString calleeName() const { return mCalleeName; }

private:
    void init(const CVirtualBoxErrorInfo &info);
    void copyFrom(const COMErrorInfo &x);
    void cleanup();

    void fetchFromCurrentThread(IUnknown *callee, const GUID *calleeIID);

    static QString getInterfaceNameFromIID(const QUuid &id);

    bool mIsNull : 1;
    bool mIsBasicAvailable : 1;
    bool mIsFullAvailable : 1;

    HRESULT mResultCode;
    QUuid mInterfaceID;
    QString mComponent;
    QString mText;

    COMErrorInfo *m_pNext;

    QString mInterfaceName;
    QUuid mCalleeIID;
    QString mCalleeName;

    friend class COMBaseWithEI;
};

/////////////////////////////////////////////////////////////////////////////

/**
 * Base COM class the CInterface template and all wrapper classes are derived
 * from. Provides common functionality for all COM wrappers.
 */
class SHARED_LIBRARY_STUFF COMBase
{
public:

    static HRESULT InitializeCOM(bool fGui);
    static HRESULT CleanupCOM();

    /**
     * Returns the result code of the last interface method called by the
     * wrapper instance or the result of CInterface::createInstance()
     * operation.
     */
    HRESULT lastRC() const { return mRC; }

#if !defined(VBOX_WITH_XPCOM)

    /** Converts a GUID value to QUuid */
    static QUuid ToQUuid(const GUID &id)
    {
        return QUuid(id.Data1, id.Data2, id.Data3,
                     id.Data4[0], id.Data4[1], id.Data4[2], id.Data4[3],
                     id.Data4[4], id.Data4[5], id.Data4[6], id.Data4[7]);
    }

#else /* !defined(VBOX_WITH_XPCOM) */

    /** Converts a GUID value to QUuid */
    static QUuid ToQUuid(const nsID &id)
    {
        return QUuid(id.m0, id.m1, id.m2,
                     id.m3[0], id.m3[1], id.m3[2], id.m3[3],
                     id.m3[4], id.m3[5], id.m3[6], id.m3[7]);
    }

#endif /* !defined(VBOX_WITH_XPCOM) */

    /* Arrays of arbitrary types */

    template <typename QT, typename CT>
    static void ToSafeArray(const QVector<QT> &aVec, com::SafeArray<CT> &aArr)
    {
        aArr.reset(aVec.size());
        for (int i = 0; i < aVec.size(); ++i)
            aArr[i] = static_cast<CT>(aVec.at(i));
    }

    template <typename CT, typename QT>
    static void FromSafeArray(const com::SafeArray<CT> &aArr, QVector<QT> &aVec)
    {
        aVec.resize(static_cast<int>(aArr.size()));
        for (int i = 0; i < aVec.size(); ++i)
            aVec[i] = static_cast<QT>(aArr[i]);
    }

    template <typename QT, typename CT>
    static void ToSafeArray(const QVector<QT *> &aVec, com::SafeArray<CT *> &aArr)
    {
        Q_UNUSED(aVec);
        Q_UNUSED(aArr);
        AssertMsgFailedReturnVoid(("No conversion!\n"));
    }

    template <typename CT, typename QT>
    static void FromSafeArray(const com::SafeArray<CT *> &aArr, QVector<QT *> &aVec)
    {
        Q_UNUSED(aArr);
        Q_UNUSED(aVec);
        AssertMsgFailedReturnVoid(("No conversion!\n"));
    }

    /* Arrays of equal types */

    template <typename T>
    static void ToSafeArray(const QVector<T> &aVec, com::SafeArray<T> &aArr)
    {
        aArr.reset(aVec.size());
        for (int i = 0; i < aVec.size(); ++i)
            aArr[i] = aVec.at(i);
    }

    template <typename T>
    static void FromSafeArray(const com::SafeArray<T> &aArr, QVector<T> &aVec)
    {
        aVec.resize(static_cast<int>(aArr.size()));
        memcpy(&aVec[0], aArr.raw(), aArr.size() * sizeof(T));
    }

    /* Arrays of strings */

    static void ToSafeArray(const QVector<QString> &aVec,
                            com::SafeArray<BSTR> &aArr);
    static void FromSafeArray(const com::SafeArray<BSTR> &aArr,
                              QVector<QString> &aVec);

    /* Arrays of GUID */

    static void ToSafeArray(const QVector<QUuid> &aVec,
                            com::SafeGUIDArray &aArr);
    static void FromSafeArray(const com::SafeGUIDArray &aArr,
                              QVector<QUuid> &aVec);

    /* Arrays of GUID as BSTR */

    static void ToSafeArray(const QVector<QUuid> &aVec,
                            com::SafeArray<BSTR> &aArr);
    static void FromSafeArray(const com::SafeArray<BSTR> &aArr,
                              QVector<QUuid> &aVec);

    /* Arrays of enums. Does a cast similar to what ENUMOut does. */

    template <typename QE, typename CE>
    static void ToSafeArray(const QVector<QE> &aVec,
                            com::SafeIfaceArray<CE> &aArr)
    {
        aArr.reset(static_cast<int>(aVec.size()));
        for (int i = 0; i < aVec.size(); ++i)
            aArr[i] = static_cast<CE>(aVec.at(i));
    }

    template <typename CE, typename QE>
    static void FromSafeArray(const com::SafeIfaceArray<CE> &aArr,
                              QVector<QE> &aVec)
    {
        aVec.resize(static_cast<int>(aArr.size()));
        for (int i = 0; i < aVec.size(); ++i)
            aVec[i] = static_cast<QE>(aArr[i]);
    }

    /* Arrays of interface pointers. Note: we need a separate pair of names
     * only because the MSVC8 template matching algorithm is poor and tries to
     * instantiate a com::SafeIfaceArray<BSTR> (!!!) template otherwise for
     * *no* reason and fails. Note that it's also not possible to choose the
     * correct function by specifying template arguments explicitly because then
     * it starts to try to instantiate the com::SafeArray<I> template for
     * *no* reason again and fails too. Definitely, broken. Works in GCC like a
     * charm. */

    template <class CI, class I>
    static void ToSafeIfaceArray(const QVector<CI> &aVec,
                                 com::SafeIfaceArray<I> &aArr)
    {
        aArr.reset(static_cast<int>(aVec.size()));
        for (int i = 0; i < aVec.size(); ++i)
        {
            aArr[i] = aVec.at(i).raw();
            if (aArr[i])
                aArr[i]->AddRef();
        }
    }

    template <class I, class CI>
    static void FromSafeIfaceArray(const com::SafeIfaceArray<I> &aArr,
                                   QVector<CI> &aVec)
    {
        aVec.resize(static_cast<int>(aArr.size()));
        for (int i = 0; i < aVec.size(); ++i)
            aVec[i].attach(aArr[i]);
    }

protected:

    /* no arbitrary instance creations */
    COMBase() : mRC(S_OK) {}

#if defined(VBOX_WITH_XPCOM)
    static XPCOMEventQSocketListener *sSocketListener;
#endif

    /** Adapter to pass QString as input BSTR params */
    class BSTRIn
    {
    public:

        BSTRIn(const QString &s) : bstr(SysAllocString((const OLECHAR *)
            (s.isNull() ? 0 : s.utf16()))) {}

        ~BSTRIn()
        {
            if (bstr)
                SysFreeString(bstr);
        }

        operator BSTR() const { return bstr; }

    private:

        BSTR bstr;
    };

    /** Adapter to pass QString as output BSTR params */
    class BSTROut
    {
    public:

        BSTROut(QString &s) : str(s), bstr(0) {}

        ~BSTROut()
        {
            if (bstr) {
                str = QString::fromUtf16(bstr);
                SysFreeString(bstr);
            }
        }

        operator BSTR *() { return &bstr; }

    private:

        QString &str;
        BSTR bstr;
    };

    /** Adapter to pass QUuid as input BSTR params */
    class GuidAsBStrIn
    {
    public:

        GuidAsBStrIn(const QUuid &s) : bstr(SysAllocString((const OLECHAR *)
            (s.isNull() ? 0 : s.toString().utf16()))) {}

        ~GuidAsBStrIn()
        {
            if (bstr)
                SysFreeString(bstr);
        }

        operator BSTR() const { return bstr; }

    private:

        BSTR bstr;
    };

    /** Adapter to pass QUuid as output BSTR params */
    class GuidAsBStrOut
    {
    public:

        GuidAsBStrOut(QUuid &s) : uuid(s), bstr(0) {}

        ~GuidAsBStrOut()
        {
            if (bstr) {
                uuid = QUuid(QString::fromUtf16(bstr));
                SysFreeString(bstr);
            }
        }

        operator BSTR *() { return &bstr; }

    private:

        QUuid &uuid;
        BSTR bstr;
    };

    /**
     * Adapter to pass K* enums as output COM enum params (*_T).
     *
     * @param QE    K* enum.
     * @param CE    COM enum.
     */
    template <typename QE, typename CE>
    class ENUMOut
    {
    public:

        ENUMOut(QE &e) : qe(e), ce((CE)0) {}
        ~ENUMOut() { qe = (QE)ce; }
        operator CE *() { return &ce; }

    private:

        QE &qe;
        CE ce;
    };

#if !defined(VBOX_WITH_XPCOM)

    /** Adapter to pass QUuid as input GUID params */
    static GUID GUIDIn(const QUuid &uuid) { return uuid; }

    /** Adapter to pass QUuid as output GUID params */
    class GUIDOut
    {
    public:

        GUIDOut(QUuid &id) : uuid(id)
        {
            ::memset(&guid, 0, sizeof(GUID));
        }

        ~GUIDOut()
        {
            uuid = QUuid(
                guid.Data1, guid.Data2, guid.Data3,
                guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
                guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
        }

        operator GUID *() { return &guid; }

    private:

        QUuid &uuid;
        GUID guid;
    };

#else /* !defined(VBOX_WITH_XPCOM) */

    /** Adapter to pass QUuid as input GUID params */
    static const nsID &GUIDIn(const QUuid &uuid)
    {
        return *(const nsID *) &uuid;
    }

    /** Adapter to pass QUuid as output GUID params */
    class GUIDOut
    {
    public:

        GUIDOut(QUuid &id) : uuid(id), nsid(0) {}

        ~GUIDOut()
        {
            if (nsid)
            {
                uuid = QUuid(
                    nsid->m0, nsid->m1, nsid->m2,
                    nsid->m3[0], nsid->m3[1], nsid->m3[2], nsid->m3[3],
                    nsid->m3[4], nsid->m3[5], nsid->m3[6], nsid->m3[7]);
                nsMemory::Free(nsid);
            }
        }

        operator nsID **() { return &nsid; }

    private:

        QUuid &uuid;
        nsID *nsid;
    };

#endif /* !defined(VBOX_WITH_XPCOM) */

    static void addref(IUnknown *aIface) { if (aIface) aIface->AddRef(); }
    static void release(IUnknown *aIface) { if (aIface) aIface->Release(); }

protected:

    mutable HRESULT mRC;

    friend class COMErrorInfo;
};

/////////////////////////////////////////////////////////////////////////////

/**
 * Alternative base class for the CInterface template that adds the errorInfo()
 * method for providing extended error info about unsuccessful invocation of the
 * last called interface method.
 */
class COMBaseWithEI : public COMBase
{
public:

    /**
     * Returns error info set by the last unsuccessfully invoked interface
     * method. Returned error info is useful only if CInterface::lastRC()
     * represents a failure or a warning (i.e. CInterface::isReallyOk() is
     * false).
     */
    const COMErrorInfo &errorInfo() const { return mErrInfo; }

protected:

    /* no arbitrary instance creation */
    COMBaseWithEI() : COMBase() {};

    void setErrorInfo(const COMErrorInfo &aErrInfo) { mErrInfo = aErrInfo; }

    void fetchErrorInfo(IUnknown *aCallee, const GUID *aCalleeIID) const
    {
        mErrInfo.fetchFromCurrentThread(aCallee, aCalleeIID);
    }

    mutable COMErrorInfo mErrInfo;
};

/////////////////////////////////////////////////////////////////////////////

/**
 * Simple class that encapsulates the result code and COMErrorInfo.
 */
class COMResult
{
public:

    COMResult() : mRC(S_OK) {}

    /**
     * Queries the current result code from the given component.
     */
    explicit COMResult(const COMBase &aComponent)
        : mRC(aComponent.lastRC()) {}

    /**
     * Queries the current result code and error info from the given component.
     */
    COMResult(const COMBaseWithEI &aComponent)
        : mRC(aComponent.lastRC()),
          mErrInfo(aComponent.errorInfo())
    { }

    /**
     * Queries the current result code from the given component.
     */
    COMResult &operator=(const COMBase &aComponent)
    {
        mRC = aComponent.lastRC();
        return *this;
    }

    /**
     * Queries the current result code and error info from the given component.
     */
    COMResult &operator=(const COMBaseWithEI &aComponent)
    {
        mRC = aComponent.lastRC();
        mErrInfo = aComponent.errorInfo();
        return *this;
    }

    bool isNull() const { return mErrInfo.isNull(); }

    /**
     * Returns @c true if the result code represents success (with or without
     * warnings).
     */
    bool isOk() const { return SUCCEEDED(mRC); }

    /**
     * Returns @c true if the result code represents success with one or more
     * warnings.
     */
    bool isWarning() const { return SUCCEEDED_WARNING(mRC); }

    /**
     * Returns @c true if the result code represents success with no warnings.
     */
    bool isReallyOk() const { return mRC == S_OK; }

    COMErrorInfo errorInfo() const { return mErrInfo; }
    HRESULT rc() const { return mRC; }

private:

    HRESULT mRC;
    COMErrorInfo mErrInfo;
};

/////////////////////////////////////////////////////////////////////////////

/**
 * Wrapper template class for all interfaces.
 *
 * All interface methods named as they are in the original, i.e. starting
 * with the capital letter. All utility non-interface methods are named
 * starting with the small letter. Utility methods should be not normally
 * called by the end-user client application.
 *
 * @param  I    Interface class (i.e. derived from IUnknown/nsISupports).
 * @param  B    Base class, either COMBase (by default) or COMBaseWithEI.
 */
template <class I, class B = COMBase>
class CInterface : public B
{
public:

    typedef B Base;
    typedef I Iface;

    // constructors & destructor

    CInterface()
    {
        clear();
    }

    CInterface(const CInterface &that) : B(that)
    {
        clear();
        mIface = that.mIface;
        this->addref((IUnknown*)ptr());
    }

    CInterface(I *aIface)
    {
        clear();
        setPtr(aIface);
        this->addref((IUnknown*)aIface);
    }

    virtual ~CInterface()
    {
        detach();
#ifdef RT_STRICT
        mDead = true;
#endif
    }

#ifdef VBOX_WITH_LESS_VIRTUALBOX_INCLUDING
    virtual IID const &getIID() const = 0;
#else
    IID const &getIID() const { return COM_IIDOF(I); }
#endif

    // utility methods
    void createInstance(const CLSID &aClsId)
    {
        AssertMsg(ptr() == NULL, ("Instance is already non-NULL\n"));
        if (ptr() == NULL)
        {
            I* pObj = NULL;
#if !defined(VBOX_WITH_XPCOM)
            B::mRC = CoCreateInstance(aClsId, NULL, CLSCTX_ALL, getIID(), (void **)&pObj);
#else
            nsCOMPtr<nsIComponentManager> manager;
            B::mRC = NS_GetComponentManager(getter_AddRefs(manager));
            if (SUCCEEDED(B::mRC))
                B::mRC = manager->CreateInstance(aClsId, nsnull, getIID(), (void **)&pObj);
#endif

            if (SUCCEEDED(B::mRC))
               setPtr(pObj);
            else
               setPtr(NULL);

            /* fetch error info, but don't assert if it's missing -- many other
             * reasons can lead to an error (w/o providing error info), not only
             * the instance initialization code (that should always provide it) */
            B::fetchErrorInfo(NULL, NULL);
         }
    }

    /**
     * Attaches to the given foreign interface pointer by querying the own
     * interface on it. The operation may fail.
     */
    template <class OI>
    void attach(OI *aIface)
    {
        Assert(!mDead);
        /* be aware of self assignment */
        I* amIface = ptr();
        this->addref((IUnknown*)aIface);
        this->release((IUnknown*)amIface);
        if (aIface)
        {
            amIface = NULL;
            B::mRC = aIface->QueryInterface(getIID(), (void **)&amIface);
            this->release((IUnknown*)aIface);
            setPtr(amIface);
        }
        else
        {
            setPtr(NULL);
            B::mRC = S_OK;
        }
    };

    /** Specialization of attach() for our own interface I. Never fails. */
    void attach(I *aIface)
    {
        Assert(!mDead);
        /* be aware of self assignment */
        this->addref((IUnknown*)aIface);
        this->release((IUnknown*)ptr());
        setPtr(aIface);
        B::mRC = S_OK;
    };

    /** Detaches from the underlying interface pointer. */
    void detach()
    {
       Assert(!mDead);
       this->release((IUnknown*)ptr());
       setPtr(NULL);
    }

    /** Returns @c true if not attached to any interface pointer. */
    bool isNull() const
    {
       Assert(!mDead);
       return mIface == NULL;
    }

    /** Returns @c true if attached to an interface pointer. */
    bool isNotNull() const
    {
       Assert(!mDead);
       return mIface != NULL;
    }

    /**
     * Returns @c true if the result code represents success (with or without
     * warnings).
     */
    bool isOk() const { return !isNull() && SUCCEEDED(B::mRC); }

    /**
     * Returns @c true if the result code represents success with one or more
     * warnings.
     */
    bool isWarning() const { return !isNull() && SUCCEEDED_WARNING(B::mRC); }

    /**
     * Returns @c true if the result code represents success with no warnings.
     */
    bool isReallyOk() const { return !isNull() && B::mRC == S_OK; }

    // utility operators

    CInterface &operator=(const CInterface &that)
    {
        attach(that.ptr());
        B::operator=(that);
        return *this;
    }

    CInterface &operator=(I *aIface)
    {
        attach(aIface);
        return *this;
    }

    /**
     * Returns the raw interface pointer. Not intended to be used for anything
     * else but in generated wrappers and for debugging. You've been warned.
     */
    I *raw() const
    {
       return ptr();
    }

    bool operator==(const CInterface &that) const { return ptr() == that.ptr(); }
    bool operator!=(const CInterface &that) const { return ptr() != that.ptr(); }

    I *ptr() const
    {
        Assert(!mDead);
        return mIface;
    }

    void setPtr(I* aObj) const
    {
        Assert(!mDead);
        mIface = aObj;
    }

private:
#ifdef RT_STRICT
    bool          mDead;
#endif
    mutable I *   mIface;

    void clear()
    {
       mIface = NULL;
#ifdef RT_STRICT
       mDead = false;
#endif
    }
};

/**
 * Partial specialization for CInterface template class above for a case when B == COMBase.
 *
 * We had to add it because on exporting template to a library at least on Windows there is
 * an implicit instantiation of the createInstance() member (even if it's not used) which
 * in case of base template uses API present in COMBaseWithEI class only, not in COMBase.
 *
 * @param  I  Brings the interface class (i.e. derived from IUnknown/nsISupports).
 */
template <class I>
class CInterface<I, COMBase> : public COMBase
{
public:

    typedef COMBase Base;
    typedef I       Iface;

    // constructors & destructor

    CInterface()
    {
        clear();
    }

    CInterface(const CInterface &that) : COMBase(that)
    {
        clear();
        mIface = that.mIface;
        this->addref((IUnknown*)ptr());
    }

    CInterface(I *pIface)
    {
        clear();
        setPtr(pIface);
        this->addref((IUnknown*)pIface);
    }

    virtual ~CInterface()
    {
        detach();
#ifdef RT_STRICT
        mDead = true;
#endif
    }

#ifdef VBOX_WITH_LESS_VIRTUALBOX_INCLUDING
    virtual IID const &getIID() const = 0;
#else
    IID const &getIID() const { return COM_IIDOF(I); }
#endif

    // utility methods

    void createInstance(const CLSID &clsId)
    {
        AssertMsg(ptr() == NULL, ("Instance is already non-NULL\n"));
        if (ptr() == NULL)
        {
            I* pObj = NULL;
#if !defined(VBOX_WITH_XPCOM)
            COMBase::mRC = CoCreateInstance(clsId, NULL, CLSCTX_ALL, getIID(), (void **)&pObj);
#else
            nsCOMPtr<nsIComponentManager> manager;
            COMBase::mRC = NS_GetComponentManager(getter_AddRefs(manager));
            if (SUCCEEDED(COMBase::mRC))
                COMBase::mRC = manager->CreateInstance(clsId, nsnull, getIID(), (void **)&pObj);
#endif

            if (SUCCEEDED(COMBase::mRC))
               setPtr(pObj);
            else
               setPtr(NULL);
         }
    }

    /**
     * Attaches to the given foreign interface pointer by querying the own
     * interface on it. The operation may fail.
     */
    template <class OI>
    void attach(OI *pIface)
    {
        Assert(!mDead);
        /* Be aware of self assignment: */
        I *pmIface = ptr();
        this->addref((IUnknown*)pIface);
        this->release((IUnknown*)pmIface);
        if (pIface)
        {
            pmIface = NULL;
            COMBase::mRC = pIface->QueryInterface(getIID(), (void **)&pmIface);
            this->release((IUnknown*)pIface);
            setPtr(pmIface);
        }
        else
        {
            setPtr(NULL);
            COMBase::mRC = S_OK;
        }
    };

    /** Specialization of attach() for our own interface I. Never fails. */
    void attach(I *pIface)
    {
        Assert(!mDead);
        /* Be aware of self assignment: */
        this->addref((IUnknown*)pIface);
        this->release((IUnknown*)ptr());
        setPtr(pIface);
        COMBase::mRC = S_OK;
    };

    /** Detaches from the underlying interface pointer. */
    void detach()
    {
        Assert(!mDead);
        this->release((IUnknown*)ptr());
        setPtr(NULL);
    }

    /** Returns @c true if not attached to any interface pointer. */
    bool isNull() const
    {
        Assert(!mDead);
        return mIface == NULL;
    }

    /** Returns @c true if attached to an interface pointer. */
    bool isNotNull() const
    {
        Assert(!mDead);
        return mIface != NULL;
    }

    /** Returns @c true if the result code represents success (with or without warnings). */
    bool isOk() const { return !isNull() && SUCCEEDED(COMBase::mRC); }

    /** Returns @c true if the result code represents success with one or more warnings. */
    bool isWarning() const { return !isNull() && SUCCEEDED_WARNING(COMBase::mRC); }

    /** Returns @c true if the result code represents success with no warnings. */
    bool isReallyOk() const { return !isNull() && COMBase::mRC == S_OK; }

    // utility operators

    CInterface &operator=(const CInterface &that)
    {
        attach(that.ptr());
        COMBase::operator=(that);
        return *this;
    }

    CInterface &operator=(I *pIface)
    {
        attach(pIface);
        return *this;
    }

    /**
     * Returns the raw interface pointer. Not intended to be used for anything
     * else but in generated wrappers and for debugging. You've been warned.
     */
    I *raw() const
    {
       return ptr();
    }

    bool operator==(const CInterface &that) const { return ptr() == that.ptr(); }
    bool operator!=(const CInterface &that) const { return ptr() != that.ptr(); }

    I *ptr() const
    {
        Assert(!mDead);
        return mIface;
    }

    void setPtr(I* aObj) const
    {
        Assert(!mDead);
        mIface = aObj;
    }

private:

#ifdef RT_STRICT
    bool       mDead;
#endif
    mutable I *mIface;

    void clear()
    {
       mIface = NULL;
#ifdef RT_STRICT
       mDead = false;
#endif
    }
};

/////////////////////////////////////////////////////////////////////////////

class CUnknown : public CInterface<IUnknown, COMBaseWithEI>
{
public:

    typedef CInterface<IUnknown, COMBaseWithEI> Base;

    CUnknown() {}

    /** Creates an instance given another CInterface-based instance. */
    template <class OI, class OB>
    explicit CUnknown(const CInterface<OI, OB> &that)
    {
        attach(that.ptr());
        if (SUCCEEDED(mRC))
        {
            /* preserve old error info if any */
            mRC = that.lastRC();
            setErrorInfo(that.errorInfo());
        }
    }

    /** Constructor specialization for IUnknown. */
    CUnknown(const CUnknown &that) : Base(that) {}

    /** Creates an instance given a foreign interface pointer. */
    template <class OI>
    explicit CUnknown(OI *aIface)
    {
        attach(aIface);
    }

    /** Constructor specialization for IUnknown. */
    explicit CUnknown(IUnknown *aIface) : Base(aIface) {}

    /** Assigns from another CInterface-based instance. */
    template <class OI, class OB>
    CUnknown &operator=(const CInterface<OI, OB> &that)
    {
        attach(that.ptr());
        if (SUCCEEDED(mRC))
        {
            /* preserve old error info if any */
            mRC = that.lastRC();
            setErrorInfo(that.errorInfo());
        }
        return *this;
    }

    /** Assignment specialization for CUnknown. */
    CUnknown &operator=(const CUnknown &that)
    {
        Base::operator=(that);
        return *this;
    }

    /** Assigns from a foreign interface pointer. */
    template <class OI>
    CUnknown &operator=(OI *aIface)
    {
        attach(aIface);
        return *this;
    }

    /** Assignment specialization for IUnknown. */
    CUnknown &operator=(IUnknown *aIface)
    {
        Base::operator=(aIface);
        return *this;
    }

#ifdef VBOX_WITH_LESS_VIRTUALBOX_INCLUDING
    IID const &getIID() const RT_OVERRIDE { return COM_IIDOF(IUnknown); }
#else
    IID const &getIID() const { return COM_IIDOF(IUnknown); }
#endif
};

/** @} */

#endif /* !FEQT_INCLUDED_SRC_globals_COMDefs_h */