summaryrefslogtreecommitdiff
path: root/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.cpp
blob: e98623891edad8ec643ef09d9c9e44df1b3e895e (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
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
/* $Id: VBoxTray.cpp $ */
/** @file
 * VBoxTray - Guest Additions Tray Application
 */

/*
 * Copyright (C) 2006-2013 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.
 */


/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include "VBoxTray.h"
#include "VBoxTrayMsg.h"
#include "VBoxHelpers.h"
#include "VBoxSeamless.h"
#include "VBoxClipboard.h"
#include "VBoxDisplay.h"
#include "VBoxRestore.h"
#include "VBoxVRDP.h"
#include "VBoxHostVersion.h"
#include "VBoxSharedFolders.h"
#include "VBoxIPC.h"
#include "VBoxLA.h"
#include "VBoxMMR.h"
#include <VBoxHook.h>
#include "resource.h"
#include <malloc.h>
#include <VBoxGuestInternal.h>

#include <sddl.h>

#include <iprt/buildconfig.h>
#include <iprt/ldr.h>

/* Default desktop state tracking */
#include <Wtsapi32.h>

/*
 * St (session [state] tracking) functionality API
 *
 * !!!NOTE: this API is NOT thread-safe!!!
 * it is supposed to be called & used from within the window message handler thread
 * of the window passed to vboxStInit */
static int vboxStInit(HWND hWnd);
static void vboxStTerm(void);
/* @returns true on "IsActiveConsole" state change */
static BOOL vboxStHandleEvent(WPARAM EventID, LPARAM SessionID);
static BOOL vboxStIsActiveConsole();
static BOOL vboxStCheckTimer(WPARAM wEvent);

/*
 * Dt (desktop [state] tracking) functionality API
 *
 * !!!NOTE: this API is NOT thread-safe!!!
 * */
static int vboxDtInit();
static void vboxDtTerm();
/* @returns true on "IsInputDesktop" state change */
static BOOL vboxDtHandleEvent();
/* @returns true iff the application (VBoxTray) desktop is input */
static BOOL vboxDtIsInputDesktop();
static HANDLE vboxDtGetNotifyEvent();
static BOOL vboxDtCheckTimer(WPARAM wParam);

/* caps API */
#define VBOXCAPS_ENTRY_IDX_SEAMLESS  0
#define VBOXCAPS_ENTRY_IDX_GRAPHICS  1
#define VBOXCAPS_ENTRY_IDX_COUNT     2

typedef enum VBOXCAPS_ENTRY_FUNCSTATE
{
    /* the cap is unsupported */
    VBOXCAPS_ENTRY_FUNCSTATE_UNSUPPORTED = 0,
    /* the cap is supported */
    VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED,
    /* the cap functionality is started, it can be disabled however if its AcState is not ACQUIRED */
    VBOXCAPS_ENTRY_FUNCSTATE_STARTED,
} VBOXCAPS_ENTRY_FUNCSTATE;


static void VBoxCapsEntryFuncStateSet(uint32_t iCup, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState);
static int VBoxCapsInit();
static int VBoxCapsReleaseAll();
static void VBoxCapsTerm();
static BOOL VBoxCapsEntryIsAcquired(uint32_t iCap);
static BOOL VBoxCapsEntryIsEnabled(uint32_t iCap);
static BOOL VBoxCapsCheckTimer(WPARAM wParam);
static int VBoxCapsEntryRelease(uint32_t iCap);
static int VBoxCapsEntryAcquire(uint32_t iCap);
static int VBoxCapsAcquireAllSupported();

/* console-related caps API */
static BOOL VBoxConsoleIsAllowed();
static void VBoxConsoleEnable(BOOL fEnable);
static void VBoxConsoleCapSetSupported(uint32_t iCap, BOOL fSupported);

static void VBoxGrapicsSetSupported(BOOL fSupported);

/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static int vboxTrayCreateTrayIcon(void);
static LRESULT CALLBACK vboxToolWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);

/* Global message handler prototypes. */
static int vboxTrayGlMsgTaskbarCreated(WPARAM lParam, LPARAM wParam);
/*static int vboxTrayGlMsgShowBalloonMsg(WPARAM lParam, LPARAM wParam);*/

static int VBoxAcquireGuestCaps(uint32_t fOr, uint32_t fNot, bool fCfg);

/*******************************************************************************
*   Global Variables                                                           *
*******************************************************************************/
HANDLE                ghVBoxDriver;
HANDLE                ghStopSem;
HANDLE                ghSeamlessWtNotifyEvent = 0;
HANDLE                ghSeamlessKmNotifyEvent = 0;
SERVICE_STATUS        gVBoxServiceStatus;
SERVICE_STATUS_HANDLE gVBoxServiceStatusHandle;
HINSTANCE             ghInstance;
HWND                  ghwndToolWindow;
NOTIFYICONDATA        gNotifyIconData;
DWORD                 gMajorVersion;


/* The service table. */
static VBOXSERVICEINFO vboxServiceTable[] =
{
    {
        "Display",
        VBoxDisplayInit,
        VBoxDisplayThread,
        NULL /* pfnStop */,
        VBoxDisplayDestroy
    },
    {
        "Shared Clipboard",
        VBoxClipboardInit,
        VBoxClipboardThread,
        NULL /* pfnStop */,
        VBoxClipboardDestroy
    },
    {
        "Seamless Windows",
        VBoxSeamlessInit,
        VBoxSeamlessThread,
        NULL /* pfnStop */,
        VBoxSeamlessDestroy
    },
#ifdef VBOX_WITH_VRDP_SESSION_HANDLING
    {
        "Restore",
        VBoxRestoreInit,
        VBoxRestoreThread,
        NULL /* pfnStop */,
        VBoxRestoreDestroy
    },
#endif
    {
        "VRDP",
        VBoxVRDPInit,
        VBoxVRDPThread,
        NULL /* pfnStop */,
        VBoxVRDPDestroy
    },
    {
        "IPC",
        VBoxIPCInit,
        VBoxIPCThread,
        VBoxIPCStop,
        VBoxIPCDestroy
    },
    {
        "Location Awareness",
        VBoxLAInit,
        VBoxLAThread,
        NULL /* pfnStop */,
        VBoxLADestroy
    },
#ifdef VBOX_WITH_MMR
    {
        "Multimedia Redirection",
        VBoxMMRInit,
        VBoxMMRThread,
        NULL /* pfnStop */,
        VBoxMMRDestroy
    },
#endif
    {
        NULL
    }
};

/* The global message table. */
static VBOXGLOBALMESSAGE s_vboxGlobalMessageTable[] =
{
    /* Windows specific stuff. */
    {
        "TaskbarCreated",
        vboxTrayGlMsgTaskbarCreated
    },

    /* VBoxTray specific stuff. */
    /** @todo Add new messages here! */

    {
        NULL
    }
};

/**
 * Gets called whenever the Windows main taskbar
 * get (re-)created. Nice to install our tray icon.
 *
 * @return  IPRT status code.
 * @param   wParam
 * @param   lParam
 */
static int vboxTrayGlMsgTaskbarCreated(WPARAM wParam, LPARAM lParam)
{
    return vboxTrayCreateTrayIcon();
}

static int vboxTrayCreateTrayIcon(void)
{
    HICON hIcon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_VIRTUALBOX));
    if (hIcon == NULL)
    {
        DWORD dwErr = GetLastError();
        Log(("VBoxTray: Could not load tray icon, error %08X\n", dwErr));
        return RTErrConvertFromWin32(dwErr);
    }

    /* Prepare the system tray icon. */
    RT_ZERO(gNotifyIconData);
    gNotifyIconData.cbSize           = NOTIFYICONDATA_V1_SIZE; // sizeof(NOTIFYICONDATA);
    gNotifyIconData.hWnd             = ghwndToolWindow;
    gNotifyIconData.uID              = ID_TRAYICON;
    gNotifyIconData.uFlags           = NIF_ICON | NIF_MESSAGE | NIF_TIP;
    gNotifyIconData.uCallbackMessage = WM_VBOXTRAY_TRAY_ICON;
    gNotifyIconData.hIcon            = hIcon;

    sprintf(gNotifyIconData.szTip, "%s Guest Additions %d.%d.%dr%d",
            VBOX_PRODUCT, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV);

    int rc = VINF_SUCCESS;
    if (!Shell_NotifyIcon(NIM_ADD, &gNotifyIconData))
    {
        DWORD dwErr = GetLastError();
        Log(("VBoxTray: Could not create tray icon, error = %08X\n", dwErr));
        rc = RTErrConvertFromWin32(dwErr);
        RT_ZERO(gNotifyIconData);
    }

    if (hIcon)
        DestroyIcon(hIcon);
    return rc;
}

static void vboxTrayRemoveTrayIcon()
{
    if (gNotifyIconData.cbSize > 0)
    {
        /* Remove the system tray icon and refresh system tray. */
        Shell_NotifyIcon(NIM_DELETE, &gNotifyIconData);
        HWND hTrayWnd = FindWindow("Shell_TrayWnd", NULL); /* We assume we only have one tray atm. */
        if (hTrayWnd)
        {
            HWND hTrayNotifyWnd = FindWindowEx(hTrayWnd, 0, "TrayNotifyWnd", NULL);
            if (hTrayNotifyWnd)
                SendMessage(hTrayNotifyWnd, WM_PAINT, 0, NULL);
        }
        RT_ZERO(gNotifyIconData);
    }
}

static int vboxTrayStartServices(VBOXSERVICEENV *pEnv, VBOXSERVICEINFO *pTable)
{
    AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
    AssertPtrReturn(pTable, VERR_INVALID_POINTER);

    Log(("VBoxTray: Starting services ...\n"));

    /** @todo Use IPRT events here. */
    pEnv->hStopEvent = CreateEvent(NULL, TRUE /* bManualReset */,
                                   FALSE /* bInitialState */, NULL);

    if (!pEnv->hStopEvent)
    {
        /* Could not create event. */
        return VERR_NOT_SUPPORTED;
    }

    while (   pTable
           && pTable->pszName)
    {
        Log(("VBoxTray: Starting %s ...\n", pTable->pszName));

        int rc = VINF_SUCCESS;

        bool fStartThread = false;

        pTable->hThread = (HANDLE)0;
        pTable->pInstance = NULL;
        pTable->fStarted = false;

        if (pTable->pfnInit)
            rc = pTable->pfnInit(pEnv, &pTable->pInstance, &fStartThread);

        if (RT_FAILURE(rc))
        {
            LogRel(("VBoxTray: Failed to initialize service \"%s\", rc=%Rrc\n",
                    pTable->pszName, rc));
        }
        else
        {
            if (   pTable->pfnThread
                && fStartThread)
            {
                unsigned threadid;
                /** @todo Use RTThread* here. */
                pTable->hThread = (HANDLE)_beginthreadex(NULL,  /* security */
                                                         0,     /* stacksize */
                                                         pTable->pfnThread,
                                                         pTable->pInstance,
                                                         0,     /* initflag */
                                                         &threadid);
                if (pTable->hThread == (HANDLE)(0))
                    rc = VERR_NOT_SUPPORTED;
            }

            if (RT_SUCCESS(rc))
                pTable->fStarted = true;
            else
            {
                Log(("VBoxTray: Failed to start the thread\n"));
                if (pTable->pfnDestroy)
                    pTable->pfnDestroy(pEnv, pTable->pInstance);
            }
        }

        /* Advance to next table element. */
        pTable++;
    }

    return VINF_SUCCESS;
}

static void vboxTrayStopServices(VBOXSERVICEENV *pEnv, VBOXSERVICEINFO *pTable)
{
    if (!pEnv->hStopEvent)
        return;

    /* Signal to all threads. */
    SetEvent(pEnv->hStopEvent);

    VBOXSERVICEINFO *pCurTable = pTable;
    while (   pCurTable
           && pCurTable->pszName)
    {
        if (pCurTable->pfnStop)
            pCurTable->pfnStop(pEnv, pCurTable->pInstance);

        /* Advance to next table element. */
        pCurTable++;
    }

    pCurTable = pTable; /* Reset to first element. */
    while (   pCurTable
           && pCurTable->pszName)
    {
        if (pCurTable->fStarted)
        {
            if (pCurTable->pfnThread)
            {
                /* There is a thread, wait for termination. */
                /** @todo Use RTThread* here. */
                /** @todo Don't wait forever here. Use a sensible default. */
                WaitForSingleObject(pCurTable->hThread, INFINITE);

                /** @todo Dito. */
                CloseHandle(pCurTable->hThread);
                pCurTable->hThread = NULL;
            }

            if (pCurTable->pfnDestroy)
                pCurTable->pfnDestroy(pEnv, pCurTable->pInstance);
            pCurTable->fStarted = false;
        }

        /* Advance to next table element. */
        pCurTable++;
    }

    CloseHandle(pEnv->hStopEvent);
}

static int vboxTrayRegisterGlobalMessages(PVBOXGLOBALMESSAGE pTable)
{
    int rc = VINF_SUCCESS;
    if (pTable == NULL) /* No table to register? Skip. */
        return rc;
    while (   pTable->pszName
           && RT_SUCCESS(rc))
    {
        /* Register global accessible window messages. */
        pTable->uMsgID = RegisterWindowMessage(TEXT(pTable->pszName));
        if (!pTable->uMsgID)
        {
            DWORD dwErr = GetLastError();
            Log(("VBoxTray: Registering global message \"%s\" failed, error = %08X\n", dwErr));
            rc = RTErrConvertFromWin32(dwErr);
        }

        /* Advance to next table element. */
        pTable++;
    }
    return rc;
}

static bool vboxTrayHandleGlobalMessages(PVBOXGLOBALMESSAGE pTable, UINT uMsg,
                                         WPARAM wParam, LPARAM lParam)
{
    if (pTable == NULL)
        return false;
    while (pTable && pTable->pszName)
    {
        if (pTable->uMsgID == uMsg)
        {
            if (pTable->pfnHandler)
                pTable->pfnHandler(wParam, lParam);
            return true;
        }

        /* Advance to next table element. */
        pTable++;
    }
    return false;
}

static int vboxTrayOpenBaseDriver(void)
{
    /* Open VBox guest driver. */
    DWORD dwErr = ERROR_SUCCESS;
    ghVBoxDriver = CreateFile(VBOXGUEST_DEVICE_NAME,
                             GENERIC_READ | GENERIC_WRITE,
                             FILE_SHARE_READ | FILE_SHARE_WRITE,
                             NULL,
                             OPEN_EXISTING,
                             FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                             NULL);
    if (ghVBoxDriver == INVALID_HANDLE_VALUE)
    {
        dwErr = GetLastError();
        LogRel(("VBoxTray: Could not open VirtualBox Guest Additions driver! Please install / start it first! Error = %08X\n", dwErr));
    }
    return RTErrConvertFromWin32(dwErr);
}

static void vboxTrayCloseBaseDriver(void)
{
    if (ghVBoxDriver)
    {
        CloseHandle(ghVBoxDriver);
        ghVBoxDriver = NULL;
    }
}

static void vboxTrayDestroyToolWindow(void)
{
    if (ghwndToolWindow)
    {
        Log(("VBoxTray: Destroying tool window ...\n"));

        /* Destroy the tool window. */
        DestroyWindow(ghwndToolWindow);
        ghwndToolWindow = NULL;

        UnregisterClass("VBoxTrayToolWndClass", ghInstance);
    }
}

static int vboxTrayCreateToolWindow(void)
{
    DWORD dwErr = ERROR_SUCCESS;

    /* Create a custom window class. */
    WNDCLASS windowClass = {0};
    windowClass.style         = CS_NOCLOSE;
    windowClass.lpfnWndProc   = (WNDPROC)vboxToolWndProc;
    windowClass.hInstance     = ghInstance;
    windowClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
    windowClass.lpszClassName = "VBoxTrayToolWndClass";
    if (!RegisterClass(&windowClass))
    {
        dwErr = GetLastError();
        Log(("VBoxTray: Registering invisible tool window failed, error = %08X\n", dwErr));
    }
    else
    {
        /*
         * Create our (invisible) tool window.
         * Note: The window name ("VBoxTrayToolWnd") and class ("VBoxTrayToolWndClass") is
         * needed for posting globally registered messages to VBoxTray and must not be
         * changed! Otherwise things get broken!
         *
         */
        ghwndToolWindow = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
                                         "VBoxTrayToolWndClass", "VBoxTrayToolWnd",
                                         WS_POPUPWINDOW,
                                         -200, -200, 100, 100, NULL, NULL, ghInstance, NULL);
        if (!ghwndToolWindow)
        {
            dwErr = GetLastError();
            Log(("VBoxTray: Creating invisible tool window failed, error = %08X\n", dwErr));
        }
        else
        {
            /* Reload the cursor(s). */
            hlpReloadCursor();

            Log(("VBoxTray: Invisible tool window handle = %p\n", ghwndToolWindow));
        }
    }

    if (dwErr != ERROR_SUCCESS)
         vboxTrayDestroyToolWindow();
    return RTErrConvertFromWin32(dwErr);
}

static int vboxTraySetupSeamless(void)
{
    OSVERSIONINFO info;
    gMajorVersion = 5; /* Default to Windows XP. */
    info.dwOSVersionInfoSize = sizeof(info);
    if (GetVersionEx(&info))
    {
        Log(("VBoxTray: Windows version %ld.%ld\n", info.dwMajorVersion, info.dwMinorVersion));
        gMajorVersion = info.dwMajorVersion;
    }

    /* We need to setup a security descriptor to allow other processes modify access to the seamless notification event semaphore. */
    SECURITY_ATTRIBUTES     SecAttr;
    DWORD                   dwErr = ERROR_SUCCESS;
    char                    secDesc[SECURITY_DESCRIPTOR_MIN_LENGTH];
    BOOL                    fRC;

    SecAttr.nLength              = sizeof(SecAttr);
    SecAttr.bInheritHandle       = FALSE;
    SecAttr.lpSecurityDescriptor = &secDesc;
    InitializeSecurityDescriptor(SecAttr.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
    fRC = SetSecurityDescriptorDacl(SecAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
    if (!fRC)
    {
        dwErr = GetLastError();
        Log(("VBoxTray: SetSecurityDescriptorDacl failed with last error = %08X\n", dwErr));
    }
    else
    {
        /* For Vista and up we need to change the integrity of the security descriptor, too. */
        if (gMajorVersion >= 6)
        {
            BOOL (WINAPI * pfnConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR StringSecurityDescriptor, DWORD StringSDRevision, PSECURITY_DESCRIPTOR  *SecurityDescriptor, PULONG  SecurityDescriptorSize);
            *(void **)&pfnConvertStringSecurityDescriptorToSecurityDescriptorA =
                RTLdrGetSystemSymbol("advapi32.dll", "ConvertStringSecurityDescriptorToSecurityDescriptorA");
            Log(("VBoxTray: pfnConvertStringSecurityDescriptorToSecurityDescriptorA = %x\n", pfnConvertStringSecurityDescriptorToSecurityDescriptorA));
            if (pfnConvertStringSecurityDescriptorToSecurityDescriptorA)
            {
                PSECURITY_DESCRIPTOR    pSD;
                PACL                    pSacl          = NULL;
                BOOL                    fSaclPresent   = FALSE;
                BOOL                    fSaclDefaulted = FALSE;

                fRC = pfnConvertStringSecurityDescriptorToSecurityDescriptorA("S:(ML;;NW;;;LW)", /* this means "low integrity" */
                                                                              SDDL_REVISION_1, &pSD, NULL);
                if (!fRC)
                {
                    dwErr = GetLastError();
                    Log(("VBoxTray: ConvertStringSecurityDescriptorToSecurityDescriptorA failed with last error = %08X\n", dwErr));
                }
                else
                {
                    fRC = GetSecurityDescriptorSacl(pSD, &fSaclPresent, &pSacl, &fSaclDefaulted);
                    if (!fRC)
                    {
                        dwErr = GetLastError();
                        Log(("VBoxTray: GetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
                    }
                    else
                    {
                        fRC = SetSecurityDescriptorSacl(SecAttr.lpSecurityDescriptor, TRUE, pSacl, FALSE);
                        if (!fRC)
                        {
                            dwErr = GetLastError();
                            Log(("VBoxTray: SetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
                        }
                    }
                }
            }
        }

        if (   dwErr == ERROR_SUCCESS
            && gMajorVersion >= 5) /* Only for W2K and up ... */
        {
            ghSeamlessWtNotifyEvent = CreateEvent(&SecAttr, FALSE, FALSE, VBOXHOOK_GLOBAL_WT_EVENT_NAME);
            if (ghSeamlessWtNotifyEvent == NULL)
            {
                dwErr = GetLastError();
                Log(("VBoxTray: CreateEvent for Seamless failed, last error = %08X\n", dwErr));
            }

            ghSeamlessKmNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
            if (ghSeamlessKmNotifyEvent == NULL)
            {
                dwErr = GetLastError();
                Log(("VBoxTray: CreateEvent for Seamless failed, last error = %08X\n", dwErr));
            }
        }
    }
    return RTErrConvertFromWin32(dwErr);
}

static void vboxTrayShutdownSeamless(void)
{
    if (ghSeamlessWtNotifyEvent)
    {
        CloseHandle(ghSeamlessWtNotifyEvent);
        ghSeamlessWtNotifyEvent = NULL;
    }

    if (ghSeamlessKmNotifyEvent)
    {
        CloseHandle(ghSeamlessKmNotifyEvent);
        ghSeamlessKmNotifyEvent = NULL;
    }
}

static void VBoxTrayCheckDt()
{
    BOOL fOldAllowedState = VBoxConsoleIsAllowed();
    if (vboxDtHandleEvent())
    {
        if (!VBoxConsoleIsAllowed() != !fOldAllowedState)
            VBoxConsoleEnable(!fOldAllowedState);
    }
}

static int vboxTrayServiceMain(void)
{
    int rc = VINF_SUCCESS;
    Log(("VBoxTray: Entering vboxTrayServiceMain\n"));

    ghStopSem = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (ghStopSem == NULL)
    {
        rc = RTErrConvertFromWin32(GetLastError());
        Log(("VBoxTray: CreateEvent for stopping VBoxTray failed, rc=%Rrc\n", rc));
    }
    else
    {
        /*
         * Start services listed in the vboxServiceTable.
         */
        VBOXSERVICEENV svcEnv;
        svcEnv.hInstance = ghInstance;
        svcEnv.hDriver   = ghVBoxDriver;

        /* Initializes disp-if to default (XPDM) mode. */
        VBoxDispIfInit(&svcEnv.dispIf); /* Cannot fail atm. */
    #ifdef VBOX_WITH_WDDM
        /*
         * For now the display mode will be adjusted to WDDM mode if needed
         * on display service initialization when it detects the display driver type.
         */
    #endif

        /* Finally start all the built-in services! */
        rc = vboxTrayStartServices(&svcEnv, vboxServiceTable);
        if (RT_FAILURE(rc))
        {
            /* Terminate service if something went wrong. */
            vboxTrayStopServices(&svcEnv, vboxServiceTable);
        }
        else
        {
            rc = vboxTrayCreateTrayIcon();
            if (   RT_SUCCESS(rc)
                && gMajorVersion >= 5) /* Only for W2K and up ... */
            {
                /* We're ready to create the tooltip balloon.
                   Check in 10 seconds (@todo make seconds configurable) ... */
                SetTimer(ghwndToolWindow,
                         TIMERID_VBOXTRAY_CHECK_HOSTVERSION,
                         10 * 1000, /* 10 seconds */
                         NULL       /* No timerproc */);
            }

            if (RT_SUCCESS(rc))
            {
                /* Do the Shared Folders auto-mounting stuff. */
                rc = VBoxSharedFoldersAutoMount();
                if (RT_SUCCESS(rc))
                {
                    /* Report the host that we're up and running! */
                    hlpReportStatus(VBoxGuestFacilityStatus_Active);
                }
            }

            if (RT_SUCCESS(rc))
            {
                /* Boost thread priority to make sure we wake up early for seamless window notifications
                 * (not sure if it actually makes any difference though). */
                SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);

                /*
                 * Main execution loop
                 * Wait for the stop semaphore to be posted or a window event to arrive
                 */

                HANDLE hWaitEvent[4] = {0};
                DWORD dwEventCount = 0;

                hWaitEvent[dwEventCount++] = ghStopSem;

                /* Check if seamless mode is not active and add seamless event to the list */
                if (0 != ghSeamlessWtNotifyEvent)
                {
                    hWaitEvent[dwEventCount++] = ghSeamlessWtNotifyEvent;
                }

                if (0 != ghSeamlessKmNotifyEvent)
                {
                    hWaitEvent[dwEventCount++] = ghSeamlessKmNotifyEvent;
                }

                if (0 != vboxDtGetNotifyEvent())
                {
                    hWaitEvent[dwEventCount++] = vboxDtGetNotifyEvent();
                }

                Log(("VBoxTray: Number of events to wait in main loop: %ld\n", dwEventCount));
                while (true)
                {
                    DWORD waitResult = MsgWaitForMultipleObjectsEx(dwEventCount, hWaitEvent, 500, QS_ALLINPUT, 0);
                    waitResult = waitResult - WAIT_OBJECT_0;

                    /* Only enable for message debugging, lots of traffic! */
                    //Log(("VBoxTray: Wait result  = %ld\n", waitResult));

                    if (waitResult == 0)
                    {
                        Log(("VBoxTray: Event 'Exit' triggered\n"));
                        /* exit */
                        break;
                    }
                    else
                    {
                        BOOL fHandled = FALSE;
                        if (waitResult < RT_ELEMENTS(hWaitEvent))
                        {
                            if (hWaitEvent[waitResult])
                            {
                                if (hWaitEvent[waitResult] == ghSeamlessWtNotifyEvent)
                                {
                                    Log(("VBoxTray: Event 'Seamless' triggered\n"));

                                    /* seamless window notification */
                                    VBoxSeamlessCheckWindows(false);
                                    fHandled = TRUE;
                                }
                                else if (hWaitEvent[waitResult] == ghSeamlessKmNotifyEvent)
                                {
                                    Log(("VBoxTray: Event 'Km Seamless' triggered\n"));

                                    /* seamless window notification */
                                    VBoxSeamlessCheckWindows(true);
                                    fHandled = TRUE;
                                }
                                else if (hWaitEvent[waitResult] == vboxDtGetNotifyEvent())
                                {
                                    Log(("VBoxTray: Event 'Dt' triggered\n"));
                                    VBoxTrayCheckDt();
                                    fHandled = TRUE;
                                }
                            }
                        }

                        if (!fHandled)
                        {
                            /* timeout or a window message, handle it */
                            MSG msg;
                            while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
                            {
                                Log(("VBoxTray: msg %p\n", msg.message));
                                if (msg.message == WM_QUIT)
                                {
                                    Log(("VBoxTray: WM_QUIT!\n"));
                                    SetEvent(ghStopSem);
                                }
                                TranslateMessage(&msg);
                                DispatchMessage(&msg);
                            }
                        }
                    }
                }
                Log(("VBoxTray: Returned from main loop, exiting ...\n"));
            }
            Log(("VBoxTray: Waiting for services to stop ...\n"));
            vboxTrayStopServices(&svcEnv, vboxServiceTable);
        } /* Services started */
        CloseHandle(ghStopSem);
    } /* Stop event created */

    vboxTrayRemoveTrayIcon();

    Log(("VBoxTray: Leaving vboxTrayServiceMain with rc=%Rrc\n", rc));
    return rc;
}

/**
 * Main function
 */
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    /* Do not use a global namespace ("Global\\") for mutex name here, will blow up NT4 compatibility! */
    HANDLE hMutexAppRunning = CreateMutex(NULL, FALSE, "VBoxTray");
    if (   hMutexAppRunning != NULL
        && GetLastError() == ERROR_ALREADY_EXISTS)
    {
        /* Close the mutex for this application instance. */
        CloseHandle (hMutexAppRunning);
        hMutexAppRunning = NULL;
        return 0;
    }

    LogRel(("VBoxTray: %s r%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr()));

    int rc = RTR3InitExeNoArguments(0);
    if (RT_SUCCESS(rc))
    {
        rc = VbglR3Init();
        if (RT_SUCCESS(rc))
            rc = vboxTrayOpenBaseDriver();
    }

    if (RT_SUCCESS(rc))
    {
        /* Save instance handle. */
        ghInstance = hInstance;

        hlpReportStatus(VBoxGuestFacilityStatus_Init);
        rc = vboxTrayCreateToolWindow();
        if (RT_SUCCESS(rc))
        {
            VBoxCapsInit();

            rc = vboxStInit(ghwndToolWindow);
            if (!RT_SUCCESS(rc))
            {
                WARN(("VBoxTray: vboxStInit failed, rc %d\n"));
                /* ignore the St Init failure. this can happen for < XP win that do not support WTS API
                 * in that case the session is treated as active connected to the physical console
                 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
                Assert(vboxStIsActiveConsole());
            }

            rc = vboxDtInit();
            if (!RT_SUCCESS(rc))
            {
                WARN(("VBoxTray: vboxDtInit failed, rc %d\n"));
                /* ignore the Dt Init failure. this can happen for < XP win that do not support WTS API
                 * in that case the session is treated as active connected to the physical console
                 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
                Assert(vboxDtIsInputDesktop());
            }

            rc = VBoxAcquireGuestCaps(VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, 0, true);
            if (!RT_SUCCESS(rc))
            {
                WARN(("VBoxAcquireGuestCaps cfg failed rc %d, ignoring..\n", rc));
            }

            rc = vboxTraySetupSeamless();
            if (RT_SUCCESS(rc))
            {
                Log(("VBoxTray: Init successful\n"));
                rc = vboxTrayServiceMain();
                if (RT_SUCCESS(rc))
                    hlpReportStatus(VBoxGuestFacilityStatus_Terminating);
                vboxTrayShutdownSeamless();
            }

            /* it should be safe to call vboxDtTerm even if vboxStInit above failed */
            vboxDtTerm();

            /* it should be safe to call vboxStTerm even if vboxStInit above failed */
            vboxStTerm();

            VBoxCapsTerm();

            vboxTrayDestroyToolWindow();
        }
        if (RT_SUCCESS(rc))
            hlpReportStatus(VBoxGuestFacilityStatus_Terminated);
    }

    if (RT_FAILURE(rc))
    {
        LogRel(("VBoxTray: Error while starting, rc=%Rrc\n", rc));
        hlpReportStatus(VBoxGuestFacilityStatus_Failed);
    }
    LogRel(("VBoxTray: Ended\n"));
    vboxTrayCloseBaseDriver();

    /* Release instance mutex. */
    if (hMutexAppRunning != NULL)
    {
        CloseHandle(hMutexAppRunning);
        hMutexAppRunning = NULL;
    }

    VbglR3Term();
    return RT_SUCCESS(rc) ? 0 : 1;
}

/**
 * Window procedure for our tool window
 */
static LRESULT CALLBACK vboxToolWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_CREATE:
        {
            Log(("VBoxTray: Tool window created\n"));

            int rc = vboxTrayRegisterGlobalMessages(&s_vboxGlobalMessageTable[0]);
            if (RT_FAILURE(rc))
                Log(("VBoxTray: Error registering global window messages, rc=%Rrc\n", rc));
            return 0;
        }

        case WM_CLOSE:
            return 0;

        case WM_DESTROY:
            Log(("VBoxTray: Tool window destroyed\n"));
            KillTimer(ghwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
            return 0;

        case WM_TIMER:
            if (VBoxCapsCheckTimer(wParam))
                return 0;
            if (vboxDtCheckTimer(wParam))
                return 0;
            if (vboxStCheckTimer(wParam))
                return 0;

            switch (wParam)
            {
                case TIMERID_VBOXTRAY_CHECK_HOSTVERSION:
                    if (RT_SUCCESS(VBoxCheckHostVersion()))
                    {
                        /* After successful run we don't need to check again. */
                        KillTimer(ghwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
                    }
                    return 0;

                default:
                    break;
            }
            break; /* Make sure other timers get processed the usual way! */

        case WM_VBOXTRAY_TRAY_ICON:
            switch (lParam)
            {
                case WM_LBUTTONDBLCLK:
                    break;

                case WM_RBUTTONDOWN:
                    break;
            }
            return 0;

        case WM_VBOX_SEAMLESS_ENABLE:
            VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
            return 0;

        case WM_VBOX_SEAMLESS_DISABLE:
            VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
            return 0;

        case WM_DISPLAYCHANGE:
        case WM_VBOX_SEAMLESS_UPDATE:
            if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
                VBoxSeamlessCheckWindows(true);
            return 0;

        case WM_VBOX_GRAPHICS_SUPPORTED:
            VBoxGrapicsSetSupported(TRUE);
            return 0;

        case WM_VBOX_GRAPHICS_UNSUPPORTED:
            VBoxGrapicsSetSupported(FALSE);
            return 0;

        case WM_VBOXTRAY_VM_RESTORED:
            VBoxRestoreSession();
            return 0;

        case WM_VBOXTRAY_VRDP_CHECK:
            VBoxRestoreCheckVRDP();
            return 0;

        case WM_WTSSESSION_CHANGE:
        {
            BOOL fOldAllowedState = VBoxConsoleIsAllowed();
            if (vboxStHandleEvent(wParam, lParam))
            {
                if (!VBoxConsoleIsAllowed() != !fOldAllowedState)
                    VBoxConsoleEnable(!fOldAllowedState);
            }
            return 0;
        }
        default:

            /* Handle all globally registered window messages. */
            if (vboxTrayHandleGlobalMessages(&s_vboxGlobalMessageTable[0], uMsg,
                                             wParam, lParam))
            {
                return 0; /* We handled the message. @todo Add return value!*/
            }
            break; /* We did not handle the message, dispatch to DefWndProc. */
    }

    /* Only if message was *not* handled by our switch above, dispatch
     * to DefWindowProc. */
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

/* St (session [state] tracking) functionality API impl */

typedef struct VBOXST
{
    HWND hWTSAPIWnd;
    RTLDRMOD hLdrModWTSAPI32;
    BOOL fIsConsole;
    WTS_CONNECTSTATE_CLASS enmConnectState;
    UINT_PTR idDelayedInitTimer;
    BOOL (WINAPI * pfnWTSRegisterSessionNotification)(HWND hWnd, DWORD dwFlags);
    BOOL (WINAPI * pfnWTSUnRegisterSessionNotification)(HWND hWnd);
    BOOL (WINAPI * pfnWTSQuerySessionInformationA)(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR *ppBuffer, DWORD *pBytesReturned);
} VBOXST;

static VBOXST gVBoxSt;

static int vboxStCheckState()
{
    int rc = VINF_SUCCESS;
    WTS_CONNECTSTATE_CLASS *penmConnectState = NULL;
    USHORT *pProtocolType = NULL;
    DWORD cbBuf = 0;
    if (gVBoxSt.pfnWTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSConnectState,
                                               (LPTSTR *)&penmConnectState, &cbBuf))
    {
        if (gVBoxSt.pfnWTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSClientProtocolType,
                                                   (LPTSTR *)&pProtocolType, &cbBuf))
        {
            gVBoxSt.fIsConsole = (*pProtocolType == 0);
            gVBoxSt.enmConnectState = *penmConnectState;
            return VINF_SUCCESS;
        }

        DWORD dwErr = GetLastError();
        WARN(("VBoxTray: WTSQuerySessionInformationA WTSClientProtocolType failed, error = %08X\n", dwErr));
        rc = RTErrConvertFromWin32(dwErr);
    }
    else
    {
        DWORD dwErr = GetLastError();
        WARN(("VBoxTray: WTSQuerySessionInformationA WTSConnectState failed, error = %08X\n", dwErr));
        rc = RTErrConvertFromWin32(dwErr);
    }

    /* failure branch, set to "console-active" state */
    gVBoxSt.fIsConsole = TRUE;
    gVBoxSt.enmConnectState = WTSActive;

    return rc;
}

static int vboxStInit(HWND hWnd)
{
    RT_ZERO(gVBoxSt);
    int rc = RTLdrLoadSystem("WTSAPI32.DLL", false /*fNoUnload*/, &gVBoxSt.hLdrModWTSAPI32);
    if (RT_SUCCESS(rc))
    {
        rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSRegisterSessionNotification",
                            (void **)&gVBoxSt.pfnWTSRegisterSessionNotification);
        if (RT_SUCCESS(rc))
        {
            rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSUnRegisterSessionNotification",
                                (void **)&gVBoxSt.pfnWTSUnRegisterSessionNotification);
            if (RT_SUCCESS(rc))
            {
                rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSQuerySessionInformationA",
                                    (void **)&gVBoxSt.pfnWTSQuerySessionInformationA);
                if (RT_FAILURE(rc))
                    WARN(("VBoxTray: WTSQuerySessionInformationA not found\n"));
            }
            else
                WARN(("VBoxTray: WTSUnRegisterSessionNotification not found\n"));
        }
        else
            WARN(("VBoxTray: WTSRegisterSessionNotification not found\n"));
        if (RT_SUCCESS(rc))
        {
            gVBoxSt.hWTSAPIWnd = hWnd;
            if (gVBoxSt.pfnWTSRegisterSessionNotification(gVBoxSt.hWTSAPIWnd, NOTIFY_FOR_THIS_SESSION))
                vboxStCheckState();
            else
            {
                DWORD dwErr = GetLastError();
                WARN(("VBoxTray: WTSRegisterSessionNotification failed, error = %08X\n", dwErr));
                if (dwErr == RPC_S_INVALID_BINDING)
                {
                    gVBoxSt.idDelayedInitTimer = SetTimer(gVBoxSt.hWTSAPIWnd, TIMERID_VBOXTRAY_ST_DELAYED_INIT_TIMER,
                                                          2000, (TIMERPROC)NULL);
                    gVBoxSt.fIsConsole = TRUE;
                    gVBoxSt.enmConnectState = WTSActive;
                    rc = VINF_SUCCESS;
                }
                else
                    rc = RTErrConvertFromWin32(dwErr);
            }

            if (RT_SUCCESS(rc))
                return VINF_SUCCESS;
        }

        RTLdrClose(gVBoxSt.hLdrModWTSAPI32);
    }
    else
        WARN(("VBoxTray: WTSAPI32 load failed, rc = %Rrc\n", rc));

    RT_ZERO(gVBoxSt);
    gVBoxSt.fIsConsole = TRUE;
    gVBoxSt.enmConnectState = WTSActive;
    return rc;
}

static void vboxStTerm(void)
{
    if (!gVBoxSt.hWTSAPIWnd)
    {
        WARN(("VBoxTray: vboxStTerm called for non-initialized St\n"));
        return;
    }

    if (gVBoxSt.idDelayedInitTimer)
    {
        /* notification is not registered, just kill timer */
        KillTimer(gVBoxSt.hWTSAPIWnd, gVBoxSt.idDelayedInitTimer);
        gVBoxSt.idDelayedInitTimer = 0;
    }
    else
    {
        if (!gVBoxSt.pfnWTSUnRegisterSessionNotification(gVBoxSt.hWTSAPIWnd))
        {
            DWORD dwErr = GetLastError();
            WARN(("VBoxTray: WTSAPI32 load failed, error = %08X\n", dwErr));
        }
    }

    RTLdrClose(gVBoxSt.hLdrModWTSAPI32);
    RT_ZERO(gVBoxSt);
}

#define VBOXST_DBG_MAKECASE(_val) case _val: return #_val;

static const char* vboxStDbgGetString(DWORD val)
{
    switch (val)
    {
        VBOXST_DBG_MAKECASE(WTS_CONSOLE_CONNECT);
        VBOXST_DBG_MAKECASE(WTS_CONSOLE_DISCONNECT);
        VBOXST_DBG_MAKECASE(WTS_REMOTE_CONNECT);
        VBOXST_DBG_MAKECASE(WTS_REMOTE_DISCONNECT);
        VBOXST_DBG_MAKECASE(WTS_SESSION_LOGON);
        VBOXST_DBG_MAKECASE(WTS_SESSION_LOGOFF);
        VBOXST_DBG_MAKECASE(WTS_SESSION_LOCK);
        VBOXST_DBG_MAKECASE(WTS_SESSION_UNLOCK);
        VBOXST_DBG_MAKECASE(WTS_SESSION_REMOTE_CONTROL);
        default:
            WARN(("VBoxTray: invalid WTS state %d\n", val));
            return "Unknown";
    }
}

static BOOL vboxStCheckTimer(WPARAM wEvent)
{
    if (wEvent != gVBoxSt.idDelayedInitTimer)
        return FALSE;

    if (gVBoxSt.pfnWTSRegisterSessionNotification(gVBoxSt.hWTSAPIWnd, NOTIFY_FOR_THIS_SESSION))
    {
        KillTimer(gVBoxSt.hWTSAPIWnd, gVBoxSt.idDelayedInitTimer);
        gVBoxSt.idDelayedInitTimer = 0;
        vboxStCheckState();
    }
    else
    {
        DWORD dwErr = GetLastError();
        WARN(("VBoxTray: timer WTSRegisterSessionNotification failed, error = %08X\n", dwErr));
        Assert(gVBoxSt.fIsConsole == TRUE);
        Assert(gVBoxSt.enmConnectState == WTSActive);
    }

    return TRUE;
}


static BOOL vboxStHandleEvent(WPARAM wEvent, LPARAM SessionID)
{
    WARN(("VBoxTray: WTS Event: %s\n", vboxStDbgGetString(wEvent)));
    BOOL fOldIsActiveConsole = vboxStIsActiveConsole();

    vboxStCheckState();

    return !vboxStIsActiveConsole() != !fOldIsActiveConsole;
}

static BOOL vboxStIsActiveConsole()
{
    return (gVBoxSt.enmConnectState == WTSActive && gVBoxSt.fIsConsole);
}

/*
 * Dt (desktop [state] tracking) functionality API impl
 *
 * !!!NOTE: this API is NOT thread-safe!!!
 * */

typedef struct VBOXDT
{
    HANDLE hNotifyEvent;
    BOOL fIsInputDesktop;
    UINT_PTR idTimer;
    RTLDRMOD hLdrModHook;
    BOOL (* pfnVBoxHookInstallActiveDesktopTracker)(HMODULE hDll);
    BOOL (* pfnVBoxHookRemoveActiveDesktopTracker)();
    HDESK (WINAPI * pfnGetThreadDesktop)(DWORD dwThreadId);
    HDESK (WINAPI * pfnOpenInputDesktop)(DWORD dwFlags, BOOL fInherit, ACCESS_MASK dwDesiredAccess);
    BOOL (WINAPI * pfnCloseDesktop)(HDESK hDesktop);
} VBOXDT;

static VBOXDT gVBoxDt;

static BOOL vboxDtCalculateIsInputDesktop()
{
    BOOL fIsInputDt = FALSE;
    HDESK hInput = gVBoxDt.pfnOpenInputDesktop(0, FALSE, DESKTOP_CREATEWINDOW);
    if (hInput)
    {
//        DWORD dwThreadId = GetCurrentThreadId();
//        HDESK hThreadDt = gVBoxDt.pfnGetThreadDesktop(dwThreadId);
//        if (hThreadDt)
//        {
            fIsInputDt = TRUE;
//        }
//        else
//        {
//            DWORD dwErr = GetLastError();
//            WARN(("VBoxTray: pfnGetThreadDesktop for Seamless failed, last error = %08X\n", dwErr));
//        }

        gVBoxDt.pfnCloseDesktop(hInput);
    }
    else
    {
        DWORD dwErr = GetLastError();
//        WARN(("VBoxTray: pfnOpenInputDesktop for Seamless failed, last error = %08X\n", dwErr));
    }
    return fIsInputDt;
}

static BOOL vboxDtCheckTimer(WPARAM wParam)
{
    if (wParam != gVBoxDt.idTimer)
        return FALSE;

    VBoxTrayCheckDt();

    return TRUE;
}

static int vboxDtInit()
{
    int rc = VINF_SUCCESS;
    OSVERSIONINFO info;
    gMajorVersion = 5; /* Default to Windows XP. */
    info.dwOSVersionInfoSize = sizeof(info);
    if (GetVersionEx(&info))
    {
        LogRel(("VBoxTray: Windows version %ld.%ld\n", info.dwMajorVersion, info.dwMinorVersion));
        gMajorVersion = info.dwMajorVersion;
    }

    RT_ZERO(gVBoxDt);

    gVBoxDt.hNotifyEvent = CreateEvent(NULL, FALSE, FALSE, VBOXHOOK_GLOBAL_DT_EVENT_NAME);
    if (gVBoxDt.hNotifyEvent != NULL)
    {
        /* Load the hook dll and resolve the necessary entry points. */
        rc = RTLdrLoadAppPriv(VBOXHOOK_DLL_NAME, &gVBoxDt.hLdrModHook);
        if (RT_SUCCESS(rc))
        {
            rc = RTLdrGetSymbol(gVBoxDt.hLdrModHook, "VBoxHookInstallActiveDesktopTracker",
                                (void **)&gVBoxDt.pfnVBoxHookInstallActiveDesktopTracker);
            if (RT_SUCCESS(rc))
            {
                rc = RTLdrGetSymbol(gVBoxDt.hLdrModHook, "VBoxHookRemoveActiveDesktopTracker",
                                    (void **)&gVBoxDt.pfnVBoxHookRemoveActiveDesktopTracker);
                if (RT_FAILURE(rc))
                    WARN(("VBoxTray: VBoxHookRemoveActiveDesktopTracker not found\n"));
            }
            else
                WARN(("VBoxTray: VBoxHookInstallActiveDesktopTracker not found\n"));
            if (RT_SUCCESS(rc))
            {
                /* Try get the system APIs we need. */
                *(void **)&gVBoxDt.pfnGetThreadDesktop = RTLdrGetSystemSymbol("user32.dll", "GetThreadDesktop");
                if (!gVBoxDt.pfnGetThreadDesktop)
                {
                    WARN(("VBoxTray: GetThreadDesktop not found\n"));
                    rc = VERR_NOT_SUPPORTED;
                }

                *(void **)&gVBoxDt.pfnOpenInputDesktop = RTLdrGetSystemSymbol("user32.dll", "OpenInputDesktop");
                if (!gVBoxDt.pfnOpenInputDesktop)
                {
                    WARN(("VBoxTray: OpenInputDesktop not found\n"));
                    rc = VERR_NOT_SUPPORTED;
                }

                *(void **)&gVBoxDt.pfnCloseDesktop = RTLdrGetSystemSymbol("user32.dll", "CloseDesktop");
                if (!gVBoxDt.pfnCloseDesktop)
                {
                    WARN(("VBoxTray: CloseDesktop not found\n"));
                    rc = VERR_NOT_SUPPORTED;
                }

                if (RT_SUCCESS(rc))
                {
                    BOOL fRc = FALSE;
                    /* For Vista and up we need to change the integrity of the security descriptor, too. */
                    if (gMajorVersion >= 6)
                    {
                        HMODULE hModHook = (HMODULE)RTLdrGetNativeHandle(gVBoxDt.hLdrModHook);
                        Assert((uintptr_t)hModHook != ~(uintptr_t)0);
                        fRc = gVBoxDt.pfnVBoxHookInstallActiveDesktopTracker(hModHook);
                        if (!fRc)
                        {
                            DWORD dwErr = GetLastError();
                            WARN(("VBoxTray: pfnVBoxHookInstallActiveDesktopTracker failed, last error = %08X\n", dwErr));
                        }
                    }

                    if (!fRc)
                    {
                        gVBoxDt.idTimer = SetTimer(ghwndToolWindow, TIMERID_VBOXTRAY_DT_TIMER, 500, (TIMERPROC)NULL);
                        if (!gVBoxDt.idTimer)
                        {
                            DWORD dwErr = GetLastError();
                            WARN(("VBoxTray: SetTimer error %08X\n", dwErr));
                            rc = RTErrConvertFromWin32(dwErr);
                        }
                    }

                    if (RT_SUCCESS(rc))
                    {
                        gVBoxDt.fIsInputDesktop = vboxDtCalculateIsInputDesktop();
                        return VINF_SUCCESS;
                    }
                }
            }

            RTLdrClose(gVBoxDt.hLdrModHook);
        }
        else
        {
            DWORD dwErr = GetLastError();
            WARN(("VBoxTray: CreateEvent for Seamless failed, last error = %08X\n", dwErr));
            rc = RTErrConvertFromWin32(dwErr);
        }

        CloseHandle(gVBoxDt.hNotifyEvent);
    }
    else
    {
        DWORD dwErr = GetLastError();
        WARN(("VBoxTray: CreateEvent for Seamless failed, last error = %08X\n", dwErr));
        rc = RTErrConvertFromWin32(dwErr);
    }


    RT_ZERO(gVBoxDt);
    gVBoxDt.fIsInputDesktop = TRUE;

    return rc;
}

static void vboxDtTerm()
{
    if (!gVBoxDt.hLdrModHook)
        return;

    gVBoxDt.pfnVBoxHookRemoveActiveDesktopTracker();

    RTLdrClose(gVBoxDt.hLdrModHook);
    CloseHandle(gVBoxDt.hNotifyEvent);

    RT_ZERO(gVBoxDt);
}
/* @returns true on "IsInputDesktop" state change */
static BOOL vboxDtHandleEvent()
{
    BOOL fIsInputDesktop = gVBoxDt.fIsInputDesktop;
    gVBoxDt.fIsInputDesktop = vboxDtCalculateIsInputDesktop();
    return !fIsInputDesktop != !gVBoxDt.fIsInputDesktop;
}

static HANDLE vboxDtGetNotifyEvent()
{
    return gVBoxDt.hNotifyEvent;
}

/* @returns true iff the application (VBoxTray) desktop is input */
static BOOL vboxDtIsInputDesktop()
{
    return gVBoxDt.fIsInputDesktop;
}


/* we need to perform Acquire/Release using the file handled we use for rewuesting events from VBoxGuest
 * otherwise Acquisition mechanism will treat us as different client and will not propagate necessary requests
 * */
static int VBoxAcquireGuestCaps(uint32_t fOr, uint32_t fNot, bool fCfg)
{
    DWORD cbReturned = 0;
    VBoxGuestCapsAquire Info;
    Log(("VBoxTray: VBoxAcquireGuestCaps or(0x%x), not(0x%x), cfx(%d)\n", fOr, fNot, fCfg));
    Info.enmFlags = fCfg ? VBOXGUESTCAPSACQUIRE_FLAGS_CONFIG_ACQUIRE_MODE : VBOXGUESTCAPSACQUIRE_FLAGS_NONE;
    Info.rc = VERR_NOT_IMPLEMENTED;
    Info.u32OrMask = fOr;
    Info.u32NotMask = fNot;
    if (!DeviceIoControl(ghVBoxDriver, VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE, &Info, sizeof(Info), &Info, sizeof(Info), &cbReturned, NULL))
    {
        DWORD LastErr = GetLastError();
        WARN(("VBoxTray: DeviceIoControl VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE failed LastErr %d\n", LastErr));
        return RTErrConvertFromWin32(LastErr);
    }

    int rc = Info.rc;
    if (!RT_SUCCESS(rc))
    {
        WARN(("VBoxTray: VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE failed rc %d\n", rc));
        return rc;
    }

    return rc;
}

typedef enum VBOXCAPS_ENTRY_ACSTATE
{
    /* the given cap is released */
    VBOXCAPS_ENTRY_ACSTATE_RELEASED = 0,
    /* the given cap acquisition is in progress */
    VBOXCAPS_ENTRY_ACSTATE_ACQUIRING,
    /* the given cap is acquired */
    VBOXCAPS_ENTRY_ACSTATE_ACQUIRED
} VBOXCAPS_ENTRY_ACSTATE;


struct VBOXCAPS_ENTRY;
struct VBOXCAPS;

typedef DECLCALLBACKPTR(void, PFNVBOXCAPS_ENTRY_ON_ENABLE)(struct VBOXCAPS *pConsole, struct VBOXCAPS_ENTRY *pCap, BOOL fEnabled);

typedef struct VBOXCAPS_ENTRY
{
    uint32_t fCap;
    uint32_t iCap;
    VBOXCAPS_ENTRY_FUNCSTATE enmFuncState;
    VBOXCAPS_ENTRY_ACSTATE enmAcState;
    PFNVBOXCAPS_ENTRY_ON_ENABLE pfnOnEnable;
} VBOXCAPS_ENTRY;


typedef struct VBOXCAPS
{
    UINT_PTR idTimer;
    VBOXCAPS_ENTRY aCaps[VBOXCAPS_ENTRY_IDX_COUNT];
} VBOXCAPS;

static VBOXCAPS gVBoxCaps;

static DECLCALLBACK(void) vboxCapsOnEnableSeamles(struct VBOXCAPS *pConsole, struct VBOXCAPS_ENTRY *pCap, BOOL fEnabled)
{
    if (fEnabled)
    {
        Log(("VBoxTray: vboxCapsOnEnableSeamles: ENABLED\n"));
        Assert(pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
        Assert(pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
        VBoxSeamlessEnable();
    }
    else
    {
        Log(("VBoxTray: vboxCapsOnEnableSeamles: DISABLED\n"));
        Assert(pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_ACQUIRED || pCap->enmFuncState != VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
        VBoxSeamlessDisable();
    }
}

static void vboxCapsEntryAcStateSet(VBOXCAPS_ENTRY *pCap, VBOXCAPS_ENTRY_ACSTATE enmAcState)
{
    VBOXCAPS *pConsole = &gVBoxCaps;

    Log(("VBoxTray: vboxCapsEntryAcStateSet: new state enmAcState(%d); pCap: fCap(%d), iCap(%d), enmFuncState(%d), enmAcState(%d)\n",
            enmAcState, pCap->fCap, pCap->iCap, pCap->enmFuncState, pCap->enmAcState));

    if (pCap->enmAcState == enmAcState)
        return;

    VBOXCAPS_ENTRY_ACSTATE enmOldAcState = pCap->enmAcState;
    pCap->enmAcState = enmAcState;

    if (enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
    {
        if (pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
        {
            if (pCap->pfnOnEnable)
                pCap->pfnOnEnable(pConsole, pCap, TRUE);
        }
    }
    else if (enmOldAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED && pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
    {
        if (pCap->pfnOnEnable)
            pCap->pfnOnEnable(pConsole, pCap, FALSE);
    }
}

static void vboxCapsEntryFuncStateSet(VBOXCAPS_ENTRY *pCap, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState)
{
    VBOXCAPS *pConsole = &gVBoxCaps;

    Log(("VBoxTray: vboxCapsEntryFuncStateSet: new state enmAcState(%d); pCap: fCap(%d), iCap(%d), enmFuncState(%d), enmAcState(%d)\n",
            enmFuncState, pCap->fCap, pCap->iCap, pCap->enmFuncState, pCap->enmAcState));

    if (pCap->enmFuncState == enmFuncState)
        return;

    VBOXCAPS_ENTRY_FUNCSTATE enmOldFuncState = pCap->enmFuncState;

    pCap->enmFuncState = enmFuncState;

    if (enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
    {
        Assert(enmOldFuncState == VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
        if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
        {
            if (pCap->pfnOnEnable)
                pCap->pfnOnEnable(pConsole, pCap, TRUE);
        }
    }
    else if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED && enmOldFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
    {
        if (pCap->pfnOnEnable)
            pCap->pfnOnEnable(pConsole, pCap, FALSE);
    }
}

static void VBoxCapsEntryFuncStateSet(uint32_t iCup, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState)
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCup];
    vboxCapsEntryFuncStateSet(pCap, enmFuncState);
}

static int VBoxCapsInit()
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    memset(pConsole, 0, sizeof (*pConsole));
    pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].fCap = VMMDEV_GUEST_SUPPORTS_SEAMLESS;
    pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].iCap = VBOXCAPS_ENTRY_IDX_SEAMLESS;
    pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].pfnOnEnable = vboxCapsOnEnableSeamles;
    pConsole->aCaps[VBOXCAPS_ENTRY_IDX_GRAPHICS].fCap = VMMDEV_GUEST_SUPPORTS_GRAPHICS;
    pConsole->aCaps[VBOXCAPS_ENTRY_IDX_GRAPHICS].iCap = VBOXCAPS_ENTRY_IDX_GRAPHICS;
    return VINF_SUCCESS;
}

static int VBoxCapsReleaseAll()
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    Log(("VBoxTray: VBoxCapsReleaseAll\n"));
    int rc = VBoxAcquireGuestCaps(0, VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, false);
    if (!RT_SUCCESS(rc))
    {
        WARN(("VBoxTray: vboxCapsEntryReleaseAll VBoxAcquireGuestCaps failed rc %d\n", rc));
        return rc;
    }

    if (pConsole->idTimer)
    {
        Log(("VBoxTray: killing console timer\n"));
        KillTimer(ghwndToolWindow, pConsole->idTimer);
        pConsole->idTimer = 0;
    }

    for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
    {
        vboxCapsEntryAcStateSet(&pConsole->aCaps[i], VBOXCAPS_ENTRY_ACSTATE_RELEASED);
    }

    return rc;
}

static void VBoxCapsTerm()
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    VBoxCapsReleaseAll();
    memset(pConsole, 0, sizeof (*pConsole));
}

static BOOL VBoxCapsEntryIsAcquired(uint32_t iCap)
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    return pConsole->aCaps[iCap].enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED;
}

static BOOL VBoxCapsEntryIsEnabled(uint32_t iCap)
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    return pConsole->aCaps[iCap].enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED
            && pConsole->aCaps[iCap].enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED;
}

static BOOL VBoxCapsCheckTimer(WPARAM wParam)
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    if (wParam != pConsole->idTimer)
        return FALSE;

    uint32_t u32AcquiredCaps = 0;
    BOOL fNeedNewTimer = FALSE;

    for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
    {
        VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[i];
        if (pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_ACQUIRING)
            continue;

        int rc = VBoxAcquireGuestCaps(pCap->fCap, 0, false);
        if (RT_SUCCESS(rc))
        {
            vboxCapsEntryAcStateSet(&pConsole->aCaps[i], VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
            u32AcquiredCaps |= pCap->fCap;
        }
        else
        {
            Assert(rc == VERR_RESOURCE_BUSY);
            fNeedNewTimer = TRUE;
        }
    }

    if (!fNeedNewTimer)
    {
        KillTimer(ghwndToolWindow, pConsole->idTimer);
        /* cleanup timer data */
        pConsole->idTimer = 0;
    }

    return TRUE;
}

static int VBoxCapsEntryRelease(uint32_t iCap)
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCap];
    if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_RELEASED)
    {
        WARN(("VBoxTray: invalid cap[%d] state[%d] on release\n", iCap, pCap->enmAcState));
        return VERR_INVALID_STATE;
    }

    if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
    {
        int rc = VBoxAcquireGuestCaps(0, pCap->fCap, false);
        AssertRC(rc);
    }

    vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_RELEASED);

    return VINF_SUCCESS;
}

static int VBoxCapsEntryAcquire(uint32_t iCap)
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    Assert(VBoxConsoleIsAllowed());
    VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCap];
    Log(("VBoxTray: VBoxCapsEntryAcquire %d\n", iCap));
    if (pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_RELEASED)
    {
        WARN(("VBoxTray: invalid cap[%d] state[%d] on acquire\n", iCap, pCap->enmAcState));
        return VERR_INVALID_STATE;
    }

    vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_ACQUIRING);
    int rc = VBoxAcquireGuestCaps(pCap->fCap, 0, false);
    if (RT_SUCCESS(rc))
    {
        vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
        return VINF_SUCCESS;
    }

    if (rc != VERR_RESOURCE_BUSY)
    {
        WARN(("VBoxTray: vboxCapsEntryReleaseAll VBoxAcquireGuestCaps failed rc %d\n", rc));
        return rc;
    }

    WARN(("VBoxTray: iCap %d is busy!\n", iCap));

    /* the cap was busy, most likely it is still used by other VBoxTray instance running in another session,
     * queue the retry timer */
    if (!pConsole->idTimer)
    {
        pConsole->idTimer = SetTimer(ghwndToolWindow, TIMERID_VBOXTRAY_CAPS_TIMER, 100, (TIMERPROC)NULL);
        if (!pConsole->idTimer)
        {
            DWORD dwErr = GetLastError();
            WARN(("VBoxTray: SetTimer error %08X\n", dwErr));
            return RTErrConvertFromWin32(dwErr);
        }
    }

    return rc;
}

static int VBoxCapsAcquireAllSupported()
{
    VBOXCAPS *pConsole = &gVBoxCaps;
    Log(("VBoxTray: VBoxCapsAcquireAllSupported\n"));
    for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
    {
        if (pConsole->aCaps[i].enmFuncState >= VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED)
        {
            Log(("VBoxTray: VBoxCapsAcquireAllSupported acquiring cap %d, state %d\n", i, pConsole->aCaps[i].enmFuncState));
            VBoxCapsEntryAcquire(i);
        }
        else
        {
            WARN(("VBoxTray: VBoxCapsAcquireAllSupported: WARN: cap %d not supported, state %d\n", i, pConsole->aCaps[i].enmFuncState));
        }
    }
    return VINF_SUCCESS;
}

static BOOL VBoxConsoleIsAllowed()
{
    return vboxDtIsInputDesktop() && vboxStIsActiveConsole();
}

static void VBoxConsoleEnable(BOOL fEnable)
{
    if (fEnable)
        VBoxCapsAcquireAllSupported();
    else
        VBoxCapsReleaseAll();
}

static void VBoxConsoleCapSetSupported(uint32_t iCap, BOOL fSupported)
{
    if (fSupported)
    {
        VBoxCapsEntryFuncStateSet(iCap, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);

        if (VBoxConsoleIsAllowed())
            VBoxCapsEntryAcquire(iCap);
    }
    else
    {
        VBoxCapsEntryFuncStateSet(iCap, VBOXCAPS_ENTRY_FUNCSTATE_UNSUPPORTED);

        VBoxCapsEntryRelease(iCap);
    }
}

void VBoxSeamlessSetSupported(BOOL fSupported)
{
    VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_SEAMLESS, fSupported);
}

static void VBoxGrapicsSetSupported(BOOL fSupported)
{
    VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_GRAPHICS, fSupported);
}