summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VirtualBox/src/globals/VBoxGlobal.cpp
blob: c4e63e2a61df7a132c526e5df0c1574d84ec232b (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
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
/* $Id: VBoxGlobal.cpp 29607 2010-05-18 09:44:38Z vboxsync $ */
/** @file
 *
 * VBox frontends: Qt GUI ("VirtualBox"):
 * VBoxGlobal class implementation
 */

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

#include "VBoxGlobal.h"
#include <VBox/VBoxHDD.h>
#include <VBox/version.h>

#include "VBoxDefs.h"
#include "VBoxSelectorWnd.h"
#include "VBoxConsoleWnd.h"
#include "VBoxProblemReporter.h"
#include "QIHotKeyEdit.h"
#include "QIMessageBox.h"
#include "QIDialogButtonBox.h"

#ifdef VBOX_WITH_NEW_RUNTIME_CORE
# include "UIMachine.h"
# include "UISession.h"
#endif
#ifdef VBOX_WITH_REGISTRATION
# include "UIRegistrationWzd.h"
#endif
#include "VBoxUpdateDlg.h"

#ifdef VBOX_WITH_VIDEOHWACCEL
#include "VBoxFrameBuffer.h"
#endif

/* Qt includes */
#include <QProgressDialog>
#include <QLibraryInfo>
#include <QFileDialog>
#include <QToolTip>
#include <QTranslator>
#include <QDesktopWidget>
#include <QDesktopServices>
#include <QMutex>
#include <QToolButton>
#include <QProcess>
#include <QThread>
#include <QPainter>
#include <QSettings>
#include <QTimer>
#include <QDir>
#include <QHelpEvent>
#include <QLocale>

#include <math.h>

#ifdef Q_WS_X11
# ifndef VBOX_OSE
#  include "VBoxLicenseViewer.h"
# endif /* VBOX_OSE */
# include <QTextBrowser>
# include <QScrollBar>
# include <QX11Info>
# include "VBoxX11Helper.h"
#endif

#ifdef Q_WS_MAC
# include "VBoxUtils-darwin.h"
#endif /* Q_WS_MAC */

#if defined (Q_WS_WIN)
#include "shlobj.h"
#include <QEventLoop>
#endif

#if defined (Q_WS_X11)
#undef BOOL /* typedef CARD8 BOOL in Xmd.h conflicts with #define BOOL PRBool
             * in COMDefs.h. A better fix would be to isolate X11-specific
             * stuff by placing XX* helpers below to a separate source file. */
#include <X11/X.h>
#include <X11/Xmd.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xinerama.h>
#define BOOL PRBool
#endif

#include <VBox/sup.h>
#include <VBox/com/Guid.h>

#include <iprt/asm.h>
#include <iprt/err.h>
#include <iprt/param.h>
#include <iprt/path.h>
#include <iprt/env.h>
#include <iprt/file.h>
#include <iprt/ldr.h>
#include <iprt/system.h>

#ifdef VBOX_GUI_WITH_SYSTRAY
#include <iprt/process.h>

#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
#define HOSTSUFF_EXE ".exe"
#else /* !RT_OS_WINDOWS */
#define HOSTSUFF_EXE ""
#endif /* !RT_OS_WINDOWS */
#endif

#if defined (Q_WS_X11)
#include <iprt/mem.h>
#endif

//#define VBOX_WITH_FULL_DETAILS_REPORT /* hidden for now */

//#warning "port me: check this"
/// @todo bird: Use (U)INT_PTR, (U)LONG_PTR, DWORD_PTR, or (u)intptr_t.
#if defined(Q_OS_WIN64)
typedef __int64 Q_LONG;             /* word up to 64 bit signed */
typedef unsigned __int64 Q_ULONG;   /* word up to 64 bit unsigned */
#else
typedef long Q_LONG;                /* word up to 64 bit signed */
typedef unsigned long Q_ULONG;      /* word up to 64 bit unsigned */
#endif

// VBoxMediaEnumEvent
/////////////////////////////////////////////////////////////////////////////

class VBoxMediaEnumEvent : public QEvent
{
public:

    /** Constructs a regular enum event */
    VBoxMediaEnumEvent (const VBoxMedium &aMedium,
                        VBoxMediaList::iterator &aIterator)
        : QEvent ((QEvent::Type) VBoxDefs::MediaEnumEventType)
        , mMedium (aMedium), mIterator (aIterator), mLast (false)
        {}
    /** Constructs the last enum event */
    VBoxMediaEnumEvent (VBoxMediaList::iterator &aIterator)
        : QEvent ((QEvent::Type) VBoxDefs::MediaEnumEventType)
        , mIterator (aIterator), mLast (true)
        {}

    /** Last enumerated medium (not valid when #last is true) */
    const VBoxMedium mMedium;
    /** Opaque iterator provided by the event sender (guaranteed to be
     *  the same variable for all media in the single enumeration procedure) */
    VBoxMediaList::iterator &mIterator;
    /** Whether this is the last event for the given enumeration or not */
    const bool mLast;
};

// VirtualBox callback class
/////////////////////////////////////////////////////////////////////////////

class VBoxCallback : VBOX_SCRIPTABLE_IMPL(IVirtualBoxCallback)
{
public:

    VBoxCallback (VBoxGlobal &aGlobal)
        : mGlobal (aGlobal)
        , mIsRegDlgOwner (false)
        , mIsUpdDlgOwner (false)
#ifdef VBOX_GUI_WITH_SYSTRAY
        , mIsTrayIconOwner (false)
#endif
    {
#if defined (Q_OS_WIN32)
        refcnt = 0;
#endif
    }

    virtual ~VBoxCallback() {}

    NS_DECL_ISUPPORTS

#if defined (Q_OS_WIN32)
    STDMETHOD_(ULONG, AddRef)()
    {
        return ::InterlockedIncrement (&refcnt);
    }
    STDMETHOD_(ULONG, Release)()
    {
        long cnt = ::InterlockedDecrement (&refcnt);
        if (cnt == 0)
            delete this;
        return cnt;
    }
#endif
    VBOX_SCRIPTABLE_DISPATCH_IMPL(IVirtualBoxCallback)

    // IVirtualBoxCallback methods

    // Note: we need to post custom events to the GUI event queue
    // instead of doing what we need directly from here because on Win32
    // these callback methods are never called on the main GUI thread.
    // Another reason to handle events asynchronously is that internally
    // most callback interface methods are called from under the initiator
    // object's lock, so accessing the initiator object (for example, reading
    // some property) directly from the callback method will definitely cause
    // a deadlock.

    STDMETHOD(OnMachineStateChange) (IN_BSTR id, MachineState_T state)
    {
        postEvent (new VBoxMachineStateChangeEvent (QString::fromUtf16(id),
                                                    (KMachineState) state));
        return S_OK;
    }

    STDMETHOD(OnMachineDataChange) (IN_BSTR id)
    {
        postEvent (new VBoxMachineDataChangeEvent (QString::fromUtf16(id)));
        return S_OK;
    }

    STDMETHOD(OnExtraDataCanChange)(IN_BSTR id,
                                    IN_BSTR key, IN_BSTR value,
                                    BSTR *error, BOOL *allowChange)
    {
        if (!error || !allowChange)
            return E_INVALIDARG;

        if (com::asGuidStr(id).isEmpty())
        {
            /* it's a global extra data key someone wants to change */
            QString sKey = QString::fromUtf16 (key);
            QString sVal = QString::fromUtf16 (value);
            if (sKey.startsWith ("GUI/"))
            {
                if (sKey == VBoxDefs::GUI_RegistrationDlgWinID)
                {
                    if (mIsRegDlgOwner)
                    {
                        if (sVal.isEmpty() ||
                            sVal == QString ("%1")
                                .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
                            *allowChange = TRUE;
                        else
                            *allowChange = FALSE;
                    }
                    else
                        *allowChange = TRUE;
                    return S_OK;
                }

                if (sKey == VBoxDefs::GUI_UpdateDlgWinID)
                {
                    if (mIsUpdDlgOwner)
                    {
                        if (sVal.isEmpty() ||
                            sVal == QString ("%1")
                                .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
                            *allowChange = TRUE;
                        else
                            *allowChange = FALSE;
                    }
                    else
                        *allowChange = TRUE;
                    return S_OK;
                }
#ifdef VBOX_GUI_WITH_SYSTRAY
                if (sKey == VBoxDefs::GUI_TrayIconWinID)
                {
                    if (mIsTrayIconOwner)
                    {
                        if (sVal.isEmpty() ||
                            sVal == QString ("%1")
                                .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
                            *allowChange = TRUE;
                        else
                            *allowChange = FALSE;
                    }
                    else
                        *allowChange = TRUE;
                    return S_OK;
                }
#endif
                /* try to set the global setting to check its syntax */
                VBoxGlobalSettings gs (false /* non-null */);
                if (gs.setPublicProperty (sKey, sVal))
                {
                    /* this is a known GUI property key */
                    if (!gs)
                    {
                        /* disallow the change when there is an error*/
                        *error = SysAllocString ((const OLECHAR *)
                            (gs.lastError().isNull() ? 0 : gs.lastError().utf16()));
                        *allowChange = FALSE;
                    }
                    else
                        *allowChange = TRUE;
                    return S_OK;
                }
            }
        }

        /* not interested in this key -- never disagree */
        *allowChange = TRUE;
        return S_OK;
    }

    STDMETHOD(OnExtraDataChange) (IN_BSTR id,
                                  IN_BSTR key, IN_BSTR value)
    {
        if (com::asGuidStr(id).isEmpty())
        {
            QString sKey = QString::fromUtf16 (key);
            QString sVal = QString::fromUtf16 (value);
            if (sKey.startsWith ("GUI/"))
            {
                if (sKey == VBoxDefs::GUI_RegistrationDlgWinID)
                {
                    if (sVal.isEmpty())
                    {
                        mIsRegDlgOwner = false;
                        QApplication::postEvent (&mGlobal, new VBoxCanShowRegDlgEvent (true));
                    }
                    else if (sVal == QString ("%1")
                             .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
                    {
                        mIsRegDlgOwner = true;
                        QApplication::postEvent (&mGlobal, new VBoxCanShowRegDlgEvent (true));
                    }
                    else
                        QApplication::postEvent (&mGlobal, new VBoxCanShowRegDlgEvent (false));
                }
                if (sKey == VBoxDefs::GUI_UpdateDlgWinID)
                {
                    if (sVal.isEmpty())
                    {
                        mIsUpdDlgOwner = false;
                        QApplication::postEvent (&mGlobal, new VBoxCanShowUpdDlgEvent (true));
                    }
                    else if (sVal == QString ("%1")
                             .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
                    {
                        mIsUpdDlgOwner = true;
                        QApplication::postEvent (&mGlobal, new VBoxCanShowUpdDlgEvent (true));
                    }
                    else
                        QApplication::postEvent (&mGlobal, new VBoxCanShowUpdDlgEvent (false));
                }
                if (sKey == "GUI/LanguageID")
                    QApplication::postEvent (&mGlobal, new VBoxChangeGUILanguageEvent (sVal));
#ifdef VBOX_GUI_WITH_SYSTRAY
                if (sKey == "GUI/MainWindowCount")
                    QApplication::postEvent (&mGlobal, new VBoxMainWindowCountChangeEvent (sVal.toInt()));
                if (sKey == VBoxDefs::GUI_TrayIconWinID)
                {
                    if (sVal.isEmpty())
                    {
                        mIsTrayIconOwner = false;
                        QApplication::postEvent (&mGlobal, new VBoxCanShowTrayIconEvent (true));
                    }
                    else if (sVal == QString ("%1")
                             .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
                    {
                        mIsTrayIconOwner = true;
                        QApplication::postEvent (&mGlobal, new VBoxCanShowTrayIconEvent (true));
                    }
                    else
                        QApplication::postEvent (&mGlobal, new VBoxCanShowTrayIconEvent (false));
                }
                if (sKey == "GUI/TrayIcon/Enabled")
                    QApplication::postEvent (&mGlobal, new VBoxChangeTrayIconEvent ((sVal.toLower() == "true") ? true : false));
#endif
#ifdef Q_WS_MAC
                if (sKey == VBoxDefs::GUI_PresentationModeEnabled)
                {
                    /* Default to true if it is an empty value */
                    QString testStr = sVal.toLower();
                    bool f = (testStr.isEmpty() || testStr == "false");
                    QApplication::postEvent (&mGlobal, new VBoxChangePresentationModeEvent (f));
                }
#endif

                mMutex.lock();
                mGlobal.gset.setPublicProperty (sKey, sVal);
                mMutex.unlock();
                Assert (!!mGlobal.gset);
            }
        }
#ifdef Q_WS_MAC
        else if (mGlobal.isVMConsoleProcess())
        {
            /* Check for the currently running machine */
            if (QString::fromUtf16(id) == mGlobal.vmUuid)
            {
                QString strKey = QString::fromUtf16(key);
                QString strVal = QString::fromUtf16(value);
                // TODO_NEW_CORE: we should cleanup
                // VBoxChangeDockIconUpdateEvent to have no parameters. So it
                // could really be use for both events and the consumer should
                // ask per GetExtraData how the current values are.
                if (   strKey == VBoxDefs::GUI_RealtimeDockIconUpdateEnabled
                    || strKey == VBoxDefs::GUI_RealtimeDockIconUpdateMonitor)
                {
                    /* Default to true if it is an empty value */
                    bool f = strVal.toLower() == "false" ? false : true;
                    QApplication::postEvent(&mGlobal, new VBoxChangeDockIconUpdateEvent(f));
                }
            }
        }
#endif /* Q_WS_MAC */
        return S_OK;
    }

    STDMETHOD(OnMediumRegistered) (IN_BSTR id, DeviceType_T type,
                                   BOOL registered)
    {
        /** @todo */
        Q_UNUSED (id);
        Q_UNUSED (type);
        Q_UNUSED (registered);
        return VBOX_E_DONT_CALL_AGAIN;
    }

    STDMETHOD(OnMachineRegistered) (IN_BSTR id, BOOL registered)
    {
        postEvent (new VBoxMachineRegisteredEvent (QString::fromUtf16(id),
                                                   registered));
        return S_OK;
    }

    STDMETHOD(OnSessionStateChange) (IN_BSTR id, SessionState_T state)
    {
        postEvent (new VBoxSessionStateChangeEvent (QString::fromUtf16(id),
                                                    (KSessionState) state));
        return S_OK;
    }

    STDMETHOD(OnSnapshotTaken) (IN_BSTR aMachineId, IN_BSTR aSnapshotId)
    {
        postEvent (new VBoxSnapshotEvent (QString::fromUtf16(aMachineId),
                                          QString::fromUtf16(aSnapshotId),
                                          VBoxSnapshotEvent::Taken));
        return S_OK;
    }

    STDMETHOD(OnSnapshotDeleted) (IN_BSTR aMachineId, IN_BSTR aSnapshotId)
    {
        postEvent (new VBoxSnapshotEvent (QString::fromUtf16(aMachineId),
                                          QString::fromUtf16(aSnapshotId),
                                          VBoxSnapshotEvent::Deleted));
        return S_OK;
    }

    STDMETHOD(OnSnapshotChange) (IN_BSTR aMachineId, IN_BSTR aSnapshotId)
    {
        postEvent (new VBoxSnapshotEvent (QString::fromUtf16(aMachineId),
                                          QString::fromUtf16(aSnapshotId),
                                          VBoxSnapshotEvent::Changed));
        return S_OK;
    }

    STDMETHOD(OnGuestPropertyChange) (IN_BSTR /* id */,
                                      IN_BSTR /* key */,
                                      IN_BSTR /* value */,
                                      IN_BSTR /* flags */)
    {
        return VBOX_E_DONT_CALL_AGAIN;
    }

private:

    void postEvent (QEvent *e)
    {
        // currently, we don't post events if we are in the VM execution
        // console mode, to save some CPU ticks (so far, there was no need
        // to handle VirtualBox callback events in the execution console mode)
        if (!mGlobal.isVMConsoleProcess())
            QApplication::postEvent (&mGlobal, e);
    }

    VBoxGlobal &mGlobal;

    /** protects #OnExtraDataChange() */
    QMutex mMutex;

    bool mIsRegDlgOwner;
    bool mIsUpdDlgOwner;
#ifdef VBOX_GUI_WITH_SYSTRAY
    bool mIsTrayIconOwner;
#endif

#if defined (Q_OS_WIN32)
private:
    long refcnt;
#endif
};

#if !defined (Q_OS_WIN32)
NS_DECL_CLASSINFO (VBoxCallback)
NS_IMPL_THREADSAFE_ISUPPORTS1_CI (VBoxCallback, IVirtualBoxCallback)
#endif

// VBoxGlobal
////////////////////////////////////////////////////////////////////////////////

static bool sVBoxGlobalInited = false;
static bool sVBoxGlobalInCleanup = false;

/** @internal
 *
 *  Special routine to do VBoxGlobal cleanup when the application is being
 *  terminated. It is called before some essential Qt functionality (for
 *  instance, QThread) becomes unavailable, allowing us to use it from
 *  VBoxGlobal::cleanup() if necessary.
 */
static void vboxGlobalCleanup()
{
    Assert (!sVBoxGlobalInCleanup);
    sVBoxGlobalInCleanup = true;
    vboxGlobal().cleanup();
}

/** @internal
 *
 *  Determines the rendering mode from the argument. Sets the appropriate
 *  default rendering mode if the argumen is NULL.
 */
static VBoxDefs::RenderMode vboxGetRenderMode (const char *aModeStr)
{
    VBoxDefs::RenderMode mode = VBoxDefs::InvalidRenderMode;

#if defined (Q_WS_MAC) && defined (VBOX_GUI_USE_QUARTZ2D)
    mode = VBoxDefs::Quartz2DMode;
# ifdef RT_ARCH_X86
    /* Quartz2DMode doesn't refresh correctly on 32-bit Snow Leopard, use image mode. */
//    char szRelease[80];
//    if (    RT_SUCCESS (RTSystemQueryOSInfo (RTSYSOSINFO_RELEASE, szRelease, sizeof (szRelease)))
//        &&  !strncmp (szRelease, "10.", 3))
//        mode = VBoxDefs::QImageMode;
# endif
#elif (defined (Q_WS_WIN32) || defined (Q_WS_PM) || defined (Q_WS_X11)) && defined (VBOX_GUI_USE_QIMAGE)
    mode = VBoxDefs::QImageMode;
#elif defined (Q_WS_X11) && defined (VBOX_GUI_USE_SDL)
    mode = VBoxDefs::SDLMode;
#elif defined (VBOX_GUI_USE_QIMAGE)
    mode = VBoxDefs::QImageMode;
#else
# error "Cannot determine the default render mode!"
#endif

    if (aModeStr)
    {
        if (0) ;
#if defined (VBOX_GUI_USE_QIMAGE)
        else if (::strcmp (aModeStr, "image") == 0)
            mode = VBoxDefs::QImageMode;
#endif
#if defined (VBOX_GUI_USE_SDL)
        else if (::strcmp (aModeStr, "sdl") == 0)
            mode = VBoxDefs::SDLMode;
#endif
#if defined (VBOX_GUI_USE_DDRAW)
        else if (::strcmp (aModeStr, "ddraw") == 0)
            mode = VBoxDefs::DDRAWMode;
#endif
#if defined (VBOX_GUI_USE_QUARTZ2D)
        else if (::strcmp (aModeStr, "quartz2d") == 0)
            mode = VBoxDefs::Quartz2DMode;
#endif
#if defined (VBOX_GUI_USE_QGLFB)
        else if (::strcmp (aModeStr, "qgl") == 0)
            mode = VBoxDefs::QGLMode;
#endif
//#if defined (VBOX_GUI_USE_QGL)
//        else if (::strcmp (aModeStr, "qgloverlay") == 0)
//            mode = VBoxDefs::QGLOverlayMode;
//#endif

    }

    return mode;
}

/** @class VBoxGlobal
 *
 *  The VBoxGlobal class incapsulates the global VirtualBox data.
 *
 *  There is only one instance of this class per VirtualBox application,
 *  the reference to it is returned by the static instance() method, or by
 *  the global vboxGlobal() function, that is just an inlined shortcut.
 */

VBoxGlobal::VBoxGlobal()
    : mValid (false)
    , mSelectorWnd (NULL), mConsoleWnd (NULL)
#ifdef VBOX_WITH_NEW_RUNTIME_CORE
    , m_pVirtualMachine(0)
#endif
    , mMainWindow (NULL)
#ifdef VBOX_WITH_REGISTRATION
    , mRegDlg (NULL)
#endif
    , mUpdDlg (NULL)
#ifdef VBOX_GUI_WITH_SYSTRAY
    , mIsTrayMenu (false)
    , mIncreasedWindowCounter (false)
#endif
    , mMediaEnumThread (NULL)
    , mIsKWinManaged (false)
    , mVerString ("1.0")
{
}

//
// Public members
/////////////////////////////////////////////////////////////////////////////

/**
 *  Returns a reference to the global VirtualBox data, managed by this class.
 *
 *  The main() function of the VBox GUI must call this function soon after
 *  creating a QApplication instance but before opening any of the main windows
 *  (to let the VBoxGlobal initialization procedure use various Qt facilities),
 *  and continue execution only when the isValid() method of the returned
 *  instancereturns true, i.e. do something like:
 *
 *  @code
 *  if ( !VBoxGlobal::instance().isValid() )
 *      return 1;
 *  @endcode
 *  or
 *  @code
 *  if ( !vboxGlobal().isValid() )
 *      return 1;
 *  @endcode
 *
 *  @note Some VBoxGlobal methods can be used on a partially constructed
 *  VBoxGlobal instance, i.e. from constructors and methods called
 *  from the VBoxGlobal::init() method, which obtain the instance
 *  using this instance() call or the ::vboxGlobal() function. Currently, such
 *  methods are:
 *      #vmStateText, #vmTypeIcon, #vmTypeText, #vmTypeTextList, #vmTypeFromText.
 *
 *  @see ::vboxGlobal
 */
VBoxGlobal &VBoxGlobal::instance()
{
    static VBoxGlobal vboxGlobal_instance;

    if (!sVBoxGlobalInited)
    {
        /* check that a QApplication instance is created */
        if (qApp)
        {
            sVBoxGlobalInited = true;
            vboxGlobal_instance.init();
            /* add our cleanup handler to the list of Qt post routines */
            qAddPostRoutine (vboxGlobalCleanup);
        }
        else
            AssertMsgFailed (("Must construct a QApplication first!"));
    }
    return vboxGlobal_instance;
}

VBoxGlobal::~VBoxGlobal()
{
    qDeleteAll (mOsTypeIcons);
    qDeleteAll (mVMStateIcons);
    qDeleteAll (mVMStateColors);
}

/* static */
QString VBoxGlobal::qtRTVersionString()
{
    return QString::fromLatin1 (qVersion());
}

/* static */
uint VBoxGlobal::qtRTVersion()
{
    QString rt_ver_str = VBoxGlobal::qtRTVersionString();
    return (rt_ver_str.section ('.', 0, 0).toInt() << 16) +
           (rt_ver_str.section ('.', 1, 1).toInt() << 8) +
           rt_ver_str.section ('.', 2, 2).toInt();
}

/* static */
QString VBoxGlobal::qtCTVersionString()
{
    return QString::fromLatin1 (QT_VERSION_STR);
}

/* static */
uint VBoxGlobal::qtCTVersion()
{
    QString ct_ver_str = VBoxGlobal::qtCTVersionString();
    return (ct_ver_str.section ('.', 0, 0).toInt() << 16) +
           (ct_ver_str.section ('.', 1, 1).toInt() << 8) +
           ct_ver_str.section ('.', 2, 2).toInt();
}

/**
 *  Sets the new global settings and saves them to the VirtualBox server.
 */
bool VBoxGlobal::setSettings (const VBoxGlobalSettings &gs)
{
    gs.save (mVBox);

    if (!mVBox.isOk())
    {
        vboxProblem().cannotSaveGlobalConfig (mVBox);
        return false;
    }

    /* We don't assign gs to our gset member here, because VBoxCallback
     * will update gset as necessary when new settings are successfullly
     * sent to the VirtualBox server by gs.save(). */

    return true;
}

/**
 *  Returns a reference to the main VBox VM Selector window.
 *  The reference is valid until application termination.
 *
 *  There is only one such a window per VirtualBox application.
 */
VBoxSelectorWnd &VBoxGlobal::selectorWnd()
{
#if defined (VBOX_GUI_SEPARATE_VM_PROCESS)
    AssertMsg (!vboxGlobal().isVMConsoleProcess(),
               ("Must NOT be a VM console process"));
#endif

    Assert (mValid);

    if (!mSelectorWnd)
    {
        /*
         *  We pass the address of mSelectorWnd to the constructor to let it be
         *  initialized right after the constructor is called. It is necessary
         *  to avoid recursion, since this method may be (and will be) called
         *  from the below constructor or from constructors/methods it calls.
         */
        VBoxSelectorWnd *w = new VBoxSelectorWnd (&mSelectorWnd, 0);
        Assert (w == mSelectorWnd);
        NOREF(w);
    }

    return *mSelectorWnd;
}


QWidget *VBoxGlobal::vmWindow()
{
    if (isVMConsoleProcess())
    {
#ifdef VBOX_WITH_NEW_RUNTIME_CORE
        if (m_pVirtualMachine)
            return m_pVirtualMachine->mainWindow();
        else
#endif /* VBOX_WITH_NEW_RUNTIME_CORE */
            return &consoleWnd();
    }
    return NULL;
}

/**
 *  Returns a reference to the main VBox VM Console window.
 *  The reference is valid until application termination.
 *
 *  There is only one such a window per VirtualBox application.
 */
VBoxConsoleWnd &VBoxGlobal::consoleWnd()
{
#if defined (VBOX_GUI_SEPARATE_VM_PROCESS)
    AssertMsg (vboxGlobal().isVMConsoleProcess(),
               ("Must be a VM console process"));
#endif

    Assert (mValid);

    if (!mConsoleWnd)
    {
        /*
         *  We pass the address of mConsoleWnd to the constructor to let it be
         *  initialized right after the constructor is called. It is necessary
         *  to avoid recursion, since this method may be (and will be) called
         *  from the below constructor or from constructors/methods it calls.
         */
        VBoxConsoleWnd *w = new VBoxConsoleWnd (&mConsoleWnd, 0);
        Assert (w == mConsoleWnd);
        NOREF(w);
    }

    return *mConsoleWnd;
}

#ifdef VBOX_WITH_NEW_RUNTIME_CORE
bool VBoxGlobal::createVirtualMachine(const CSession &session)
{
    if (!m_pVirtualMachine && !session.isNull())
    {
        UIMachine *pVirtualMachine = new UIMachine(&m_pVirtualMachine, session);
        Assert(pVirtualMachine == m_pVirtualMachine);
        NOREF(pVirtualMachine);
        return true;
    }
    return false;
}

UIMachine* VBoxGlobal::virtualMachine()
{
    return m_pVirtualMachine;
}
#endif

bool VBoxGlobal::brandingIsActive (bool aForce /* = false*/)
{
    if (aForce)
        return true;

    if (mBrandingConfig.isEmpty())
    {
        mBrandingConfig = QDir(QApplication::applicationDirPath()).absolutePath();
        mBrandingConfig += "/custom/custom.ini";
    }
    return QFile::exists (mBrandingConfig);
}

/**
  * Gets a value from the custom .ini file
  */
QString VBoxGlobal::brandingGetKey (QString aKey)
{
    QSettings s(mBrandingConfig, QSettings::IniFormat);
    return s.value(QString("%1").arg(aKey)).toString();
}

#ifdef VBOX_GUI_WITH_SYSTRAY

/**
 *  Returns true if the current instance a systray menu only (started with
 *  "-systray" parameter).
 */
bool VBoxGlobal::isTrayMenu() const
{
    return mIsTrayMenu;
}

void VBoxGlobal::setTrayMenu(bool aIsTrayMenu)
{
    mIsTrayMenu = aIsTrayMenu;
}

/**
 *  Spawns a new selector window (process).
 */
void VBoxGlobal::trayIconShowSelector()
{
    /* Get the path to the executable. */
    char path [RTPATH_MAX];
    RTPathAppPrivateArch (path, RTPATH_MAX);
    size_t sz = strlen (path);
    path [sz++] = RTPATH_DELIMITER;
    path [sz] = 0;
    char *cmd = path + sz;
    sz = RTPATH_MAX - sz;

    int rc = 0;
    RTPROCESS pid = NIL_RTPROCESS;
    RTENV env = RTENV_DEFAULT;

    const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
    Assert (sz >= sizeof (VirtualBox_exe));
    strcpy (cmd, VirtualBox_exe);
    const char * args[] = {path, 0 };
# ifdef RT_OS_WINDOWS
    rc = RTProcCreate (path, args, env, 0, &pid);
# else
    rc = RTProcCreate (path, args, env, RTPROC_FLAGS_DAEMONIZE_DEPRECATED, &pid);
# endif
    if (RT_FAILURE (rc))
        LogRel(("Systray: Failed to start new selector window! Path=%s, rc=%Rrc\n", path, rc));
}

/**
 *  Tries to install the tray icon using the current instance (singleton).
 *  Returns true if this instance is the tray icon, false if not.
 */
bool VBoxGlobal::trayIconInstall()
{
    int rc = 0;
    QString strTrayWinID = mVBox.GetExtraData (VBoxDefs::GUI_TrayIconWinID);
    if (false == strTrayWinID.isEmpty())
    {
        /* Check if current tray icon is alive by writing some bogus value. */
        mVBox.SetExtraData (VBoxDefs::GUI_TrayIconWinID, "0");
        if (mVBox.isOk())
        {
            /* Current tray icon died - clean up. */
            mVBox.SetExtraData (VBoxDefs::GUI_TrayIconWinID, NULL);
            strTrayWinID.clear();
        }
    }

    /* Is there already a tray icon or is tray icon not active? */
    if (   (mIsTrayMenu == false)
        && (vboxGlobal().settings().trayIconEnabled())
        && (QSystemTrayIcon::isSystemTrayAvailable())
        && (strTrayWinID.isEmpty()))
    {
        /* Get the path to the executable. */
        char path [RTPATH_MAX];
        RTPathAppPrivateArch (path, RTPATH_MAX);
        size_t sz = strlen (path);
        path [sz++] = RTPATH_DELIMITER;
        path [sz] = 0;
        char *cmd = path + sz;
        sz = RTPATH_MAX - sz;

        RTPROCESS pid = NIL_RTPROCESS;
        RTENV env = RTENV_DEFAULT;

        const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
        Assert (sz >= sizeof (VirtualBox_exe));
        strcpy (cmd, VirtualBox_exe);
        const char * args[] = {path, "-systray", 0 };
# ifdef RT_OS_WINDOWS /** @todo drop this once the RTProcCreate bug has been fixed */
        rc = RTProcCreate (path, args, env, 0, &pid);
# else
        rc = RTProcCreate (path, args, env, RTPROC_FLAGS_DAEMONIZE_DEPRECATED, &pid);
# endif

        if (RT_FAILURE (rc))
        {
            LogRel(("Systray: Failed to start systray window! Path=%s, rc=%Rrc\n", path, rc));
            return false;
        }
    }

    if (mIsTrayMenu)
    {
        // Use this selector for displaying the tray icon
        mVBox.SetExtraData (VBoxDefs::GUI_TrayIconWinID,
                            QString ("%1").arg ((qulonglong) vboxGlobal().mainWindow()->winId()));

        /* The first process which can grab this "mutex" will win ->
         * It will be the tray icon menu then. */
        if (mVBox.isOk())
        {
            emit trayIconShow (*(new VBoxShowTrayIconEvent (true)));
            return true;
        }
    }

    return false;
}

#endif

#ifdef Q_WS_X11
QList<QRect> XGetDesktopList()
{
    /* Prepare empty resulting list: */
    QList<QRect> result;

    /* Get current display: */
    Display* pDisplay = QX11Info::display();

    /* If thats Xinerama desktop: */
    if (XineramaIsActive(pDisplay))
    {
        /* Reading Xinerama data: */
        int iScreens = 0;
        XineramaScreenInfo *pScreensData = XineramaQueryScreens(pDisplay, &iScreens);

        /* Fill resulting list: */
        for (int i = 0; i < iScreens; ++ i)
            result << QRect(pScreensData[i].x_org, pScreensData[i].y_org,
                            pScreensData[i].width, pScreensData[i].height);

        /* Free screens data: */
        XFree(pScreensData);
    }

    /* Return resulting list: */
    return result;
}

QList<Window> XGetWindowIDList()
{
    /* Get current display: */
    Display *pDisplay = QX11Info::display();

    /* Get virtual desktop window: */
    Window window = QX11Info::appRootWindow();

    /* Get 'client list' atom: */
    Atom propNameAtom = XInternAtom(pDisplay, "_NET_CLIENT_LIST", True /* only if exists */);

    /* Prepare empty resulting list: */
    QList<Window> result;

    /* If atom does not exists return empty list: */
    if (propNameAtom == None)
        return result;

    /* Get atom value: */
    Atom realAtomType = None;
    int iRealFormat = 0;
    unsigned long uItemsCount = 0;
    unsigned long uBytesAfter = 0;
    unsigned char *pData = 0;
    int rc = XGetWindowProperty(pDisplay, window, propNameAtom,
                                0, 0x7fffffff /*LONG_MAX*/, False /* delete */,
                                XA_WINDOW, &realAtomType, &iRealFormat,
                                &uItemsCount, &uBytesAfter, &pData);

    /* If get property is failed return empty list: */
    if (rc != Success)
        return result;

    /* Fill resulting list with win ids: */
    Window *pWindowData = reinterpret_cast<Window*>(pData);
    for (ulong i = 0; i < uItemsCount; ++ i)
        result << pWindowData[i];

    /* Releasing resources: */
    XFree(pData);

    /* Return resulting list: */
    return result;
}

QList<ulong> XGetStrut(Window window)
{
    /* Get current display: */
    Display *pDisplay = QX11Info::display();

    /* Get 'strut' atom: */
    Atom propNameAtom = XInternAtom(pDisplay, "_NET_WM_STRUT_PARTIAL", True /* only if exists */);

    /* Prepare empty resulting list: */
    QList<ulong> result;

    /* If atom does not exists return empty list: */
    if (propNameAtom == None)
        return result;

    /* Get atom value: */
    Atom realAtomType = None;
    int iRealFormat = 0;
    ulong uItemsCount = 0;
    ulong uBytesAfter = 0;
    unsigned char *pData = 0;
    int rc = XGetWindowProperty(pDisplay, window, propNameAtom,
                                0, LONG_MAX, False /* delete */,
                                XA_CARDINAL, &realAtomType, &iRealFormat,
                                &uItemsCount, &uBytesAfter, &pData);

    /* If get property is failed return empty list: */
    if (rc != Success)
        return result;

    /* Fill resulting list with strut shifts: */
    ulong *pStrutsData = reinterpret_cast<ulong*>(pData);
    for (ulong i = 0; i < uItemsCount; ++ i)
        result << pStrutsData[i];

    /* Releasing resources: */
    XFree(pData);

    /* Return resulting list: */
    return result;
}
#endif /* ifdef Q_WS_X11 */

const QRect VBoxGlobal::availableGeometry(int iScreen) const
{
    /* Prepare empty result: */
    QRect result;

#ifdef Q_WS_X11

    /* Get current display: */
    Display* pDisplay = QX11Info::display();

    /* Get current application desktop: */
    QDesktopWidget *pDesktopWidget = QApplication::desktop();

    /* If thats virtual desktop: */
    if (pDesktopWidget->isVirtualDesktop())
    {
        /* If thats Xinerama desktop: */
        if (XineramaIsActive(pDisplay))
        {
            /* Get desktops list: */
            QList<QRect> desktops = XGetDesktopList();

            /* Combine to get full virtual region: */
            QRegion virtualRegion;
            foreach (QRect desktop, desktops)
                virtualRegion += desktop;
            virtualRegion = virtualRegion.boundingRect();

            /* Remember initial virtual desktop: */
            QRect virtualDesktop = virtualRegion.boundingRect();
            //AssertMsgFailed(("LOG... Virtual desktop is: %dx%dx%dx%d\n", virtualDesktop.x(), virtualDesktop.y(),
            //                                                             virtualDesktop.width(), virtualDesktop.height()));

            /* Set available geometry to screen geometry initially: */
            result = desktops[iScreen];

            /* Feat available geometry of virtual desktop to respect all the struts: */
            QList<Window> list = XGetWindowIDList();
            for (int i = 0; i < list.size(); ++ i)
            {
                /* Get window: */
                Window wid = list[i];
                QList<ulong> struts = XGetStrut(wid);

                /* If window has strut: */
                if (struts.size())
                {
                    ulong uLeftShift = struts[0];
                    ulong uLeftFromY = struts[4];
                    ulong uLeftToY = struts[5];

                    ulong uRightShift = struts[1];
                    ulong uRightFromY = struts[6];
                    ulong uRightToY = struts[7];

                    ulong uTopShift = struts[2];
                    ulong uTopFromX = struts[8];
                    ulong uTopToX = struts[9];

                    ulong uBottomShift = struts[3];
                    ulong uBottomFromX = struts[10];
                    ulong uBottomToX = struts[11];

                    if (uLeftShift)
                    {
                        QRect sr(QPoint(0, uLeftFromY),
                                 QSize(uLeftShift, uLeftToY - uLeftFromY + 1));

                        //AssertMsgFailed(("LOG... Subtract left strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
                        virtualRegion -= sr;
                    }

                    if (uRightShift)
                    {
                        QRect sr(QPoint(virtualDesktop.x() + virtualDesktop.width() - uRightShift, uRightFromY),
                                 QSize(virtualDesktop.x() + virtualDesktop.width(), uRightToY - uRightFromY + 1));

                        //AssertMsgFailed(("LOG... Subtract right strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
                        virtualRegion -= sr;
                    }

                    if (uTopShift)
                    {
                        QRect sr(QPoint(uTopFromX, 0),
                                 QSize(uTopToX - uTopFromX + 1, uTopShift));

                        //AssertMsgFailed(("LOG... Subtract top strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
                        virtualRegion -= sr;
                    }

                    if (uBottomShift)
                    {
                        QRect sr(QPoint(uBottomFromX, virtualDesktop.y() + virtualDesktop.height() - uBottomShift),
                                 QSize(uBottomToX - uBottomFromX + 1, uBottomShift));

                        //AssertMsgFailed(("LOG... Subtract bottom strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
                        virtualRegion -= sr;
                    }
                }
            }

            /* Get final available geometry: */
            result = (virtualRegion & result).boundingRect();
        }
    }

    /* If result is still NULL: */
    if (result.isNull())
    {
        /* Use QT default functionality: */
        result = pDesktopWidget->availableGeometry(iScreen);
    }

    //AssertMsgFailed(("LOG... Final geometry: %dx%dx%dx%d\n", result.x(), result.y(), result.width(), result.height()));

#else /* ifdef Q_WS_X11 */

    result = QApplication::desktop()->availableGeometry(iScreen);

#endif /* ifndef Q_WS_X11 */

    return result;
}

/**
 *  Returns the list of few guest OS types, queried from
 *  IVirtualBox corresponding to every family id.
 */
QList <CGuestOSType> VBoxGlobal::vmGuestOSFamilyList() const
{
    QList <CGuestOSType> result;
    for (int i = 0 ; i < mFamilyIDs.size(); ++ i)
        result << mTypes [i][0];
    return result;
}

/**
 *  Returns the list of all guest OS types, queried from
 *  IVirtualBox corresponding to passed family id.
 */
QList <CGuestOSType> VBoxGlobal::vmGuestOSTypeList (const QString &aFamilyId) const
{
    AssertMsg (mFamilyIDs.contains (aFamilyId), ("Family ID incorrect: '%s'.", aFamilyId.toLatin1().constData()));
    return mFamilyIDs.contains (aFamilyId) ?
           mTypes [mFamilyIDs.indexOf (aFamilyId)] : QList <CGuestOSType>();
}

/**
 *  Returns the icon corresponding to the given guest OS type id.
 */
QPixmap VBoxGlobal::vmGuestOSTypeIcon (const QString &aTypeId) const
{
    static const QPixmap none;
    QPixmap *p = mOsTypeIcons.value (aTypeId);
    AssertMsg (p, ("Icon for type '%s' must be defined.", aTypeId.toLatin1().constData()));
    return p ? *p : none;
}

/**
 *  Returns the guest OS type object corresponding to the given type id of list
 *  containing OS types related to OS family determined by family id attribute.
 *  If the index is invalid a null object is returned.
 */
CGuestOSType VBoxGlobal::vmGuestOSType (const QString &aTypeId,
             const QString &aFamilyId /* = QString::null */) const
{
    QList <CGuestOSType> list;
    if (mFamilyIDs.contains (aFamilyId))
    {
        list = mTypes [mFamilyIDs.indexOf (aFamilyId)];
    }
    else
    {
        for (int i = 0; i < mFamilyIDs.size(); ++ i)
            list += mTypes [i];
    }
    for (int j = 0; j < list.size(); ++ j)
        if (!list [j].GetId().compare (aTypeId))
            return list [j];
    AssertMsgFailed (("Type ID incorrect: '%s'.", aTypeId.toLatin1().constData()));
    return CGuestOSType();
}

/**
 *  Returns the description corresponding to the given guest OS type id.
 */
QString VBoxGlobal::vmGuestOSTypeDescription (const QString &aTypeId) const
{
    for (int i = 0; i < mFamilyIDs.size(); ++ i)
    {
        QList <CGuestOSType> list (mTypes [i]);
        for ( int j = 0; j < list.size(); ++ j)
            if (!list [j].GetId().compare (aTypeId))
                return list [j].GetDescription();
    }
    return QString::null;
}

/**
 * Returns a string representation of the given channel number on the given storage bus.
 * Complementary to #toStorageChannel (KStorageBus, const QString &) const.
 */
QString VBoxGlobal::toString (KStorageBus aBus, LONG aChannel) const
{
    QString channel;

    switch (aBus)
    {
        case KStorageBus_IDE:
        {
            if (aChannel == 0 || aChannel == 1)
            {
                channel = mStorageBusChannels [aChannel];
                break;
            }
            AssertMsgFailed (("Invalid IDE channel %d\n", aChannel));
            break;
        }
        case KStorageBus_SATA:
        case KStorageBus_SCSI:
        {
            channel = mStorageBusChannels [2].arg (aChannel);
            break;
        }
        case KStorageBus_Floppy:
        {
            AssertMsgFailed (("Floppy have no channels, only devices\n"));
            break;
        }
        default:
        {
            AssertMsgFailed (("Invalid bus type %d\n", aBus));
            break;
        }
    }

    Assert (!channel.isNull());
    return channel;
}

/**
 * Returns a channel number on the given storage bus corresponding to the given string representation.
 * Complementary to #toString (KStorageBus, LONG) const.
 */
LONG VBoxGlobal::toStorageChannel (KStorageBus aBus, const QString &aChannel) const
{
    LONG channel = 0;

    switch (aBus)
    {
        case KStorageBus_IDE:
        {
            QLongStringHash::const_iterator it = qFind (mStorageBusChannels.begin(), mStorageBusChannels.end(), aChannel);
            AssertMsgBreak (it != mStorageBusChannels.end(), ("No value for {%s}\n", aChannel.toLatin1().constData()));
            channel = it.key();
            break;
        }
        case KStorageBus_SATA:
        case KStorageBus_SCSI:
        {
            QString tpl = mStorageBusChannels [2].arg ("");
            if (aChannel.startsWith (tpl))
            {
                channel = aChannel.right (aChannel.length() - tpl.length()).toLong();
                break;
            }
            AssertMsgFailed (("Invalid channel {%s}\n", aChannel.toLatin1().constData()));
            break;
        }
        case KStorageBus_Floppy:
        {
            channel = 0;
            break;
        }
        default:
        {
            AssertMsgFailed (("Invalid bus type %d\n", aBus));
            break;
        }
    }

    return channel;
}

/**
 * Returns a string representation of the given device number of the given channel on the given storage bus.
 * Complementary to #toStorageDevice (KStorageBus, LONG, const QString &) const.
 */
QString VBoxGlobal::toString (KStorageBus aBus, LONG aChannel, LONG aDevice) const
{
    NOREF (aChannel);

    QString device;

    switch (aBus)
    {
        case KStorageBus_IDE:
        {
            if (aDevice == 0 || aDevice == 1)
            {
                device = mStorageBusDevices [aDevice];
                break;
            }
            AssertMsgFailed (("Invalid device %d\n", aDevice));
            break;
        }
        case KStorageBus_SATA:
        case KStorageBus_SCSI:
        {
            AssertMsgFailed (("SATA & SCSI have no devices, only channels\n"));
            break;
        }
        case KStorageBus_Floppy:
        {
            AssertMsgBreak (aChannel == 0, ("Invalid channel %d\n", aChannel));
            device = mStorageBusDevices [2].arg (aDevice);
            break;
        }
        default:
        {
            AssertMsgFailed (("Invalid bus type %d\n", aBus));
            break;
        }
    }

    Assert (!device.isNull());
    return device;
}

/**
 * Returns a device number of the given channel on the given storage bus corresponding to the given string representation.
 * Complementary to #toString (KStorageBus, LONG, LONG) const.
 */
LONG VBoxGlobal::toStorageDevice (KStorageBus aBus, LONG aChannel, const QString &aDevice) const
{
    NOREF (aChannel);

    LONG device = 0;

    switch (aBus)
    {
        case KStorageBus_IDE:
        {
            QLongStringHash::const_iterator it = qFind (mStorageBusDevices.begin(), mStorageBusDevices.end(), aDevice);
            AssertMsgBreak (it != mStorageBusDevices.end(), ("No value for {%s}", aDevice.toLatin1().constData()));
            device = it.key();
            break;
        }
        case KStorageBus_SATA:
        case KStorageBus_SCSI:
        {
            device = 0;
            break;
        }
        case KStorageBus_Floppy:
        {
            AssertMsgBreak (aChannel == 0, ("Invalid channel %d\n", aChannel));
            QString tpl = mStorageBusDevices [2].arg ("");
            if (aDevice.startsWith (tpl))
            {
                device = aDevice.right (aDevice.length() - tpl.length()).toLong();
                break;
            }
            AssertMsgFailed (("Invalid device {%s}\n", aDevice.toLatin1().constData()));
            break;
        }
        default:
        {
            AssertMsgFailed (("Invalid bus type %d\n", aBus));
            break;
        }
    }

    return device;
}

/**
 * Returns a full string representation of the given device of the given channel on the given storage bus.
 * This method does not uses any separate string tags related to bus, channel, device, it has own
 * separately translated string tags allowing to translate a full slot name into human readable format
 * to be consistent with i18n.
 * Complementary to #toStorageSlot (const QString &) const.
 */
QString VBoxGlobal::toString (StorageSlot aSlot) const
{
    switch (aSlot.bus)
    {
        case KStorageBus_IDE:
        case KStorageBus_SATA:
        case KStorageBus_SCSI:
        case KStorageBus_SAS:
        case KStorageBus_Floppy:
            break;

        default:
        {
            AssertMsgFailed (("Invalid bus type %d\n", aSlot.bus));
            break;
        }
    }

    int maxPort = virtualBox().GetSystemProperties().GetMaxPortCountForStorageBus (aSlot.bus);
    int maxDevice = virtualBox().GetSystemProperties().GetMaxDevicesPerPortForStorageBus (aSlot.bus);
    if (aSlot.port < 0 || aSlot.port > maxPort)
        AssertMsgFailed (("Invalid port %d\n", aSlot.port));
    if (aSlot.device < 0 || aSlot.device > maxDevice)
        AssertMsgFailed (("Invalid device %d\n", aSlot.device));

    QString result;
    switch (aSlot.bus)
    {
        case KStorageBus_IDE:
        {
            result = mSlotTemplates [aSlot.port * maxDevice + aSlot.device];
            break;
        }
        case KStorageBus_SATA:
        {
            result = mSlotTemplates [4].arg (aSlot.port);
            break;
        }
        case KStorageBus_SCSI:
        {
            result = mSlotTemplates [5].arg (aSlot.port);
            break;
        }
        case KStorageBus_SAS:
        {
            /* TODO: change this index to 6 after 3.2 */
            result = mSlotTemplates [5].arg (aSlot.port);
            break;
        }
        case KStorageBus_Floppy:
        {
            result = mSlotTemplates [7].arg (aSlot.device);
            break;
        }
        default:
        {
            AssertMsgFailed (("Invalid bus type %d\n", aSlot.bus));
            break;
        }
    }
    return result;
}

/**
 * Returns a StorageSlot based on the given device of the given channel on the given storage bus.
 * Complementary to #toFullString (StorageSlot) const.
 */
StorageSlot VBoxGlobal::toStorageSlot (const QString &aSlot) const
{
    int index = -1;
    QRegExp regExp;
    for (int i = 0; i < mSlotTemplates.size(); ++ i)
    {
        regExp = QRegExp (i >= 0 && i <= 3 ? mSlotTemplates [i] : mSlotTemplates [i].arg ("(\\d+)"));
        if (regExp.indexIn (aSlot) != -1)
        {
            index = i;
            break;
        }
    }

    StorageSlot result;
    switch (index)
    {
        case 0:
        case 1:
        case 2:
        case 3:
        {
            result.bus = KStorageBus_IDE;
            int maxPort = virtualBox().GetSystemProperties().GetMaxPortCountForStorageBus (result.bus);
            result.port = index / maxPort;
            result.device = index % maxPort;
            break;
        }
        case 4:
        {
            result.bus = KStorageBus_SATA;
            int maxPort = virtualBox().GetSystemProperties().GetMaxPortCountForStorageBus (result.bus);
            result.port = regExp.cap (1).toInt();
            if (result.port < 0 || result.port > maxPort)
                AssertMsgFailed (("Invalid port %d\n", result.port));
            break;
        }
        case 5:
        {
            result.bus = KStorageBus_SCSI;
            int maxPort = virtualBox().GetSystemProperties().GetMaxPortCountForStorageBus (result.bus);
            result.port = regExp.cap (1).toInt();
            if (result.port < 0 || result.port > maxPort)
                AssertMsgFailed (("Invalid port %d\n", result.port));
            break;
        }
        case 6:
        {
            result.bus = KStorageBus_SAS;
            int maxPort = virtualBox().GetSystemProperties().GetMaxPortCountForStorageBus (result.bus);
            result.port = regExp.cap (1).toInt();
            if (result.port < 0 || result.port > maxPort)
                AssertMsgFailed (("Invalid port %d\n", result.port));
            break;
        }
        case 7:
        {
            result.bus = KStorageBus_Floppy;
            int maxDevice = virtualBox().GetSystemProperties().GetMaxDevicesPerPortForStorageBus (result.bus);
            result.device = regExp.cap (1).toInt();
            if (result.device < 0 || result.device > maxDevice)
                AssertMsgFailed (("Invalid device %d\n", result.device));
            break;
        }
        default:
            break;
    }
    return result;
}

/**
 * Returns the list of all device types (VirtualBox::DeviceType COM enum).
 */
QStringList VBoxGlobal::deviceTypeStrings() const
{
    static QStringList list;
    if (list.empty())
        for (QULongStringHash::const_iterator it = mDeviceTypes.begin();
             it != mDeviceTypes.end(); ++ it)
            list += it.value();
    return list;
}

struct PortConfig
{
    const char *name;
    const ulong IRQ;
    const ulong IOBase;
};

static const PortConfig kComKnownPorts[] =
{
    { "COM1", 4, 0x3F8 },
    { "COM2", 3, 0x2F8 },
    { "COM3", 4, 0x3E8 },
    { "COM4", 3, 0x2E8 },
    /* must not contain an element with IRQ=0 and IOBase=0 used to cause
     * toCOMPortName() to return the "User-defined" string for these values. */
};

static const PortConfig kLptKnownPorts[] =
{
    { "LPT1", 7, 0x3BC },
    { "LPT2", 5, 0x378 },
    { "LPT3", 5, 0x278 },
    /* must not contain an element with IRQ=0 and IOBase=0 used to cause
     * toLPTPortName() to return the "User-defined" string for these values. */
};

/**
 *  Returns the list of the standard COM port names (i.e. "COMx").
 */
QStringList VBoxGlobal::COMPortNames() const
{
    QStringList list;
    for (size_t i = 0; i < RT_ELEMENTS (kComKnownPorts); ++ i)
        list << kComKnownPorts [i].name;

    return list;
}

/**
 *  Returns the list of the standard LPT port names (i.e. "LPTx").
 */
QStringList VBoxGlobal::LPTPortNames() const
{
    QStringList list;
    for (size_t i = 0; i < RT_ELEMENTS (kLptKnownPorts); ++ i)
        list << kLptKnownPorts [i].name;

    return list;
}

/**
 *  Returns the name of the standard COM port corresponding to the given
 *  parameters, or "User-defined" (which is also returned when both
 *  @a aIRQ and @a aIOBase are 0).
 */
QString VBoxGlobal::toCOMPortName (ulong aIRQ, ulong aIOBase) const
{
    for (size_t i = 0; i < RT_ELEMENTS (kComKnownPorts); ++ i)
        if (kComKnownPorts [i].IRQ == aIRQ &&
            kComKnownPorts [i].IOBase == aIOBase)
            return kComKnownPorts [i].name;

    return mUserDefinedPortName;
}

/**
 *  Returns the name of the standard LPT port corresponding to the given
 *  parameters, or "User-defined" (which is also returned when both
 *  @a aIRQ and @a aIOBase are 0).
 */
QString VBoxGlobal::toLPTPortName (ulong aIRQ, ulong aIOBase) const
{
    for (size_t i = 0; i < RT_ELEMENTS (kLptKnownPorts); ++ i)
        if (kLptKnownPorts [i].IRQ == aIRQ &&
            kLptKnownPorts [i].IOBase == aIOBase)
            return kLptKnownPorts [i].name;

    return mUserDefinedPortName;
}

/**
 *  Returns port parameters corresponding to the given standard COM name.
 *  Returns @c true on success, or @c false if the given port name is not one
 *  of the standard names (i.e. "COMx").
 */
bool VBoxGlobal::toCOMPortNumbers (const QString &aName, ulong &aIRQ,
                                   ulong &aIOBase) const
{
    for (size_t i = 0; i < RT_ELEMENTS (kComKnownPorts); ++ i)
        if (strcmp (kComKnownPorts [i].name, aName.toUtf8().data()) == 0)
        {
            aIRQ = kComKnownPorts [i].IRQ;
            aIOBase = kComKnownPorts [i].IOBase;
            return true;
        }

    return false;
}

/**
 *  Returns port parameters corresponding to the given standard LPT name.
 *  Returns @c true on success, or @c false if the given port name is not one
 *  of the standard names (i.e. "LPTx").
 */
bool VBoxGlobal::toLPTPortNumbers (const QString &aName, ulong &aIRQ,
                                   ulong &aIOBase) const
{
    for (size_t i = 0; i < RT_ELEMENTS (kLptKnownPorts); ++ i)
        if (strcmp (kLptKnownPorts [i].name, aName.toUtf8().data()) == 0)
        {
            aIRQ = kLptKnownPorts [i].IRQ;
            aIOBase = kLptKnownPorts [i].IOBase;
            return true;
        }

    return false;
}

/**
 * Searches for the given hard disk in the list of known media descriptors and
 * calls VBoxMedium::details() on the found desriptor.
 *
 * If the requeststed hard disk is not found (for example, it's a new hard disk
 * for a new VM created outside our UI), then media enumeration is requested and
 * the search is repeated. We assume that the secont attempt always succeeds and
 * assert otherwise.
 *
 * @note Technically, the second attempt may fail if, for example, the new hard
 *       passed to this method disk gets removed before #startEnumeratingMedia()
 *       succeeds. This (unexpected object uninitialization) is a generic
 *       problem though and needs to be addressed using exceptions (see also the
 *       @todo in VBoxMedium::details()).
 */
QString VBoxGlobal::details (const CMedium &aMedium, bool aPredictDiff)
{
    CMedium cmedium (aMedium);
    VBoxMedium medium;

    if (!findMedium (cmedium, medium))
    {
        /* Medium may be new and not already in the media list, request refresh */
        startEnumeratingMedia();
        if (!findMedium (cmedium, medium))
            /* Medium might be deleted already, return null string */
            return QString();
    }

    return medium.detailsHTML (true /* aNoDiffs */, aPredictDiff);
}

/**
 *  Returns the details of the given USB device as a single-line string.
 */
QString VBoxGlobal::details (const CUSBDevice &aDevice) const
{
    QString sDetails;
    if (aDevice.isNull())
        sDetails = tr("Unknown device", "USB device details");
    else
    {
        QString m = aDevice.GetManufacturer().trimmed();
        QString p = aDevice.GetProduct().trimmed();

        if (m.isEmpty() && p.isEmpty())
        {
            sDetails =
                tr ("Unknown device %1:%2", "USB device details")
                .arg (QString().sprintf ("%04hX", aDevice.GetVendorId()))
                .arg (QString().sprintf ("%04hX", aDevice.GetProductId()));
        }
        else
        {
            if (p.toUpper().startsWith (m.toUpper()))
                sDetails = p;
            else
                sDetails = m + " " + p;
        }
        ushort r = aDevice.GetRevision();
        if (r != 0)
            sDetails += QString().sprintf (" [%04hX]", r);
    }

    return sDetails.trimmed();
}

/**
 *  Returns the multi-line description of the given USB device.
 */
QString VBoxGlobal::toolTip (const CUSBDevice &aDevice) const
{
    QString tip =
        tr ("<nobr>Vendor ID: %1</nobr><br>"
            "<nobr>Product ID: %2</nobr><br>"
            "<nobr>Revision: %3</nobr>", "USB device tooltip")
        .arg (QString().sprintf ("%04hX", aDevice.GetVendorId()))
        .arg (QString().sprintf ("%04hX", aDevice.GetProductId()))
        .arg (QString().sprintf ("%04hX", aDevice.GetRevision()));

    QString ser = aDevice.GetSerialNumber();
    if (!ser.isEmpty())
        tip += QString (tr ("<br><nobr>Serial No. %1</nobr>", "USB device tooltip"))
                        .arg (ser);

    /* add the state field if it's a host USB device */
    CHostUSBDevice hostDev (aDevice);
    if (!hostDev.isNull())
    {
        tip += QString (tr ("<br><nobr>State: %1</nobr>", "USB device tooltip"))
                        .arg (vboxGlobal().toString (hostDev.GetState()));
    }

    return tip;
}

/**
 *  Returns the multi-line description of the given USB filter
 */
QString VBoxGlobal::toolTip (const CUSBDeviceFilter &aFilter) const
{
    QString tip;

    QString vendorId = aFilter.GetVendorId();
    if (!vendorId.isEmpty())
        tip += tr ("<nobr>Vendor ID: %1</nobr>", "USB filter tooltip")
                   .arg (vendorId);

    QString productId = aFilter.GetProductId();
    if (!productId.isEmpty())
        tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Product ID: %2</nobr>", "USB filter tooltip")
                                                .arg (productId);

    QString revision = aFilter.GetRevision();
    if (!revision.isEmpty())
        tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Revision: %3</nobr>", "USB filter tooltip")
                                                .arg (revision);

    QString product = aFilter.GetProduct();
    if (!product.isEmpty())
        tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Product: %4</nobr>", "USB filter tooltip")
                                                .arg (product);

    QString manufacturer = aFilter.GetManufacturer();
    if (!manufacturer.isEmpty())
        tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Manufacturer: %5</nobr>", "USB filter tooltip")
                                                .arg (manufacturer);

    QString serial = aFilter.GetSerialNumber();
    if (!serial.isEmpty())
        tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Serial No.: %1</nobr>", "USB filter tooltip")
                                                .arg (serial);

    QString port = aFilter.GetPort();
    if (!port.isEmpty())
        tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Port: %1</nobr>", "USB filter tooltip")
                                                .arg (port);

    /* add the state field if it's a host USB device */
    CHostUSBDevice hostDev (aFilter);
    if (!hostDev.isNull())
    {
        tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>State: %1</nobr>", "USB filter tooltip")
                                                .arg (vboxGlobal().toString (hostDev.GetState()));
    }

    return tip;
}

/**
 * Returns a details report on a given VM represented as a HTML table.
 *
 * @param aMachine      Machine to create a report for.
 * @param aWithLinks    @c true if section titles should be hypertext links.
 */
QString VBoxGlobal::detailsReport (const CMachine &aMachine, bool aWithLinks)
{
    /* Details templates */
    static const char *sTableTpl =
        "<table border=0 cellspacing=1 cellpadding=0>%1</table>";
    static const char *sSectionHrefTpl =
        "<tr><td width=22 rowspan=%1 align=left><img src='%2'></td>"
            "<td colspan=3><b><a href='%3'><nobr>%4</nobr></a></b></td></tr>"
            "%5"
        "<tr><td colspan=3><font size=1>&nbsp;</font></td></tr>";
    static const char *sSectionBoldTpl =
        "<tr><td width=22 rowspan=%1 align=left><img src='%2'></td>"
            "<td colspan=3><!-- %3 --><b><nobr>%4</nobr></b></td></tr>"
            "%5"
        "<tr><td colspan=3><font size=1>&nbsp;</font></td></tr>";
    static const char *sSectionItemTpl1 =
        "<tr><td width=40%><nobr><i>%1</i></nobr></td><td/><td/></tr>";
    static const char *sSectionItemTpl2 =
        "<tr><td width=40%><nobr>%1:</nobr></td><td/><td>%2</td></tr>";
    static const char *sSectionItemTpl3 =
        "<tr><td width=40%><nobr>%1</nobr></td><td/><td/></tr>";

    const QString &sectionTpl = aWithLinks ? sSectionHrefTpl : sSectionBoldTpl;

    /* Compose details report */
    QString report;

    /* General */
    {
        QString item = QString (sSectionItemTpl2).arg (tr ("Name", "details report"),
                                                       aMachine.GetName())
                     + QString (sSectionItemTpl2).arg (tr ("OS Type", "details report"),
                                                       vmGuestOSTypeDescription (aMachine.GetOSTypeId()));

        report += sectionTpl
                  .arg (2 + 2) /* rows */
                  .arg (":/machine_16px.png", /* icon */
                        "#general", /* link */
                        tr ("General", "details report"), /* title */
                        item); /* items */
    }

    /* System */
    {
        /* BIOS Settings holder */
        CBIOSSettings biosSettings = aMachine.GetBIOSSettings();

        /* System details row count: */
        int iRowCount = 2; /* Memory & CPU details rows initially. */

        /* Boot order */
        QString bootOrder;
        for (ulong i = 1; i <= mVBox.GetSystemProperties().GetMaxBootPosition(); ++ i)
        {
            KDeviceType device = aMachine.GetBootOrder (i);
            if (device == KDeviceType_Null)
                continue;
            if (!bootOrder.isEmpty())
                bootOrder += ", ";
            bootOrder += toString (device);
        }
        if (bootOrder.isEmpty())
            bootOrder = toString (KDeviceType_Null);

        iRowCount += 1; /* Boot-order row. */

#ifdef VBOX_WITH_FULL_DETAILS_REPORT
        /* ACPI */
        QString acpi = biosSettings.GetACPIEnabled()
            ? tr ("Enabled", "details report (ACPI)")
            : tr ("Disabled", "details report (ACPI)");

        /* IO APIC */
        QString ioapic = biosSettings.GetIOAPICEnabled()
            ? tr ("Enabled", "details report (IO APIC)")
            : tr ("Disabled", "details report (IO APIC)");

        /* PAE/NX */
        QString pae = aMachine.GetCpuProperty(KCpuPropertyType_PAE)
            ? tr ("Enabled", "details report (PAE/NX)")
            : tr ("Disabled", "details report (PAE/NX)");

        iRowCount += 3; /* Full report rows. */
#endif /* VBOX_WITH_FULL_DETAILS_REPORT */

        /* VT-x/AMD-V */
        QString virt = aMachine.GetHWVirtExProperty(KHWVirtExPropertyType_Enabled)
            ? tr ("Enabled", "details report (VT-x/AMD-V)")
            : tr ("Disabled", "details report (VT-x/AMD-V)");

        /* Nested Paging */
        QString nested = aMachine.GetHWVirtExProperty(KHWVirtExPropertyType_NestedPaging)
            ? tr ("Enabled", "details report (Nested Paging)")
            : tr ("Disabled", "details report (Nested Paging)");

        /* VT-x/AMD-V availability: */
        bool fVTxAMDVSupported = virtualBox().GetHost().GetProcessorFeature(KProcessorFeature_HWVirtEx);

        if (fVTxAMDVSupported)
            iRowCount += 2; /* VT-x/AMD-V items. */

        QString item = QString (sSectionItemTpl2).arg (tr ("Base Memory", "details report"),
                                                       tr ("<nobr>%1 MB</nobr>", "details report"))
                       .arg (aMachine.GetMemorySize())
                     + QString (sSectionItemTpl2).arg (tr ("Processor(s)", "details report"),
                                                       tr ("<nobr>%1</nobr>", "details report"))
                       .arg (aMachine.GetCPUCount())
                     + QString (sSectionItemTpl2).arg (tr ("Boot Order", "details report"), bootOrder)
#ifdef VBOX_WITH_FULL_DETAILS_REPORT
                     + QString (sSectionItemTpl2).arg (tr ("ACPI", "details report"), acpi)
                     + QString (sSectionItemTpl2).arg (tr ("IO APIC", "details report"), ioapic)
                     + QString (sSectionItemTpl2).arg (tr ("PAE/NX", "details report"), pae)
#endif /* VBOX_WITH_FULL_DETAILS_REPORT */
                     ;

        if (fVTxAMDVSupported)
                item += QString (sSectionItemTpl2).arg (tr ("VT-x/AMD-V", "details report"), virt)
                     +  QString (sSectionItemTpl2).arg (tr ("Nested Paging", "details report"), nested);

        report += sectionTpl
                  .arg (2 + iRowCount) /* rows */
                  .arg (":/chipset_16px.png", /* icon */
                        "#system", /* link */
                        tr ("System", "details report"), /* title */
                        item); /* items */
    }

    /* Display */
    {
        /* Rows including section header and footer */
        int rows = 2;

        /* Video tab */
        QString item = QString(sSectionItemTpl2)
                       .arg(tr ("Video Memory", "details report"),
                             tr ("<nobr>%1 MB</nobr>", "details report"))
                       .arg(aMachine.GetVRAMSize());
        ++rows;

        int cGuestScreens = aMachine.GetMonitorCount();
        if (cGuestScreens > 1)
        {
            item += QString(sSectionItemTpl2)
                    .arg(tr("Screens", "details report"))
                    .arg(cGuestScreens);
            ++rows;
        }

        QString acc3d = aMachine.GetAccelerate3DEnabled()
            ? tr ("Enabled", "details report (3D Acceleration)")
            : tr ("Disabled", "details report (3D Acceleration)");

        item += QString(sSectionItemTpl2)
                .arg(tr("3D Acceleration", "details report"), acc3d);
        ++rows;

#ifdef VBOX_WITH_VIDEOHWACCEL
        QString acc2dVideo = aMachine.GetAccelerate2DVideoEnabled()
            ? tr ("Enabled", "details report (2D Video Acceleration)")
            : tr ("Disabled", "details report (2D Video Acceleration)");

        item += QString (sSectionItemTpl2)
                .arg (tr ("2D Video Acceleration", "details report"), acc2dVideo);
        ++ rows;
#endif

        /* VRDP tab */
        CVRDPServer srv = aMachine.GetVRDPServer();
        if (!srv.isNull())
        {
            if (srv.GetEnabled())
                item += QString (sSectionItemTpl2)
                        .arg (tr ("Remote Display Server Port", "details report (VRDP Server)"))
                        .arg (srv.GetPorts());
            else
                item += QString (sSectionItemTpl2)
                        .arg (tr ("Remote Display Server", "details report (VRDP Server)"))
                        .arg (tr ("Disabled", "details report (VRDP Server)"));
            ++ rows;
        }

        report += sectionTpl
            .arg (rows) /* rows */
            .arg (":/vrdp_16px.png", /* icon */
                  "#display", /* link */
                  tr ("Display", "details report"), /* title */
                  item); /* items */
    }

    /* Storage */
    {
        /* Rows including section header and footer */
        int rows = 2;

        QString item;

        /* Iterate over the all machine controllers: */
        CStorageControllerVector controllers = aMachine.GetStorageControllers();
        for (int i = 0; i < controllers.size(); ++i)
        {
            /* Get current controller: */
            const CStorageController &controller = controllers[i];
            /* Add controller information: */
            item += QString(sSectionItemTpl3).arg(controller.GetName());
            ++ rows;

            /* Populate sorted map with attachments information: */
            QMap<StorageSlot,QString> attachmentsMap;
            CMediumAttachmentVector attachments = aMachine.GetMediumAttachmentsOfController(controller.GetName());
            for (int j = 0; j < attachments.size(); ++j)
            {
                /* Get current attachment: */
                const CMediumAttachment &attachment = attachments[j];
                /* Prepare current storage slot: */
                StorageSlot attachmentSlot(controller.GetBus(), attachment.GetPort(), attachment.GetDevice());
                /* Append 'device slot name' with 'device type name' for CD/DVD devices only: */
                QString strDeviceType = attachment.GetType() == KDeviceType_DVD ? tr("(CD/DVD)") : QString();
                if (!strDeviceType.isNull())
                    strDeviceType.prepend(' ');
                /* Prepare current medium object: */
                const CMedium &medium = attachment.GetMedium();
                /* Prepare information about current medium & attachment: */
                QString strAttachmentInfo = !attachment.isOk() ? QString() :
                                            QString(sSectionItemTpl2)
                                            .arg(QString("&nbsp;&nbsp;") +
                                                 toString(StorageSlot(controller.GetBus(),
                                                                      attachment.GetPort(),
                                                                      attachment.GetDevice())) + strDeviceType)
                                            .arg(details(medium, false));
                /* Insert that attachment into map: */
                if (!strAttachmentInfo.isNull())
                    attachmentsMap.insert(attachmentSlot, strAttachmentInfo);
            }

            /* Iterate over the sorted map with attachments information: */
            QMapIterator<StorageSlot,QString> it(attachmentsMap);
            while (it.hasNext())
            {
                /* Add controller information: */
                it.next();
                item += it.value();
                ++rows;
            }
        }

        if (item.isNull())
        {
            item = QString (sSectionItemTpl1)
                   .arg (tr ("Not Attached", "details report (Storage)"));
            ++ rows;
        }

        report += sectionTpl
            .arg (rows) /* rows */
            .arg (":/attachment_16px.png", /* icon */
                  "#storage", /* link */
                  tr ("Storage", "details report"), /* title */
                  item); /* items */
    }

    /* Audio */
    {
        QString item;

        CAudioAdapter audio = aMachine.GetAudioAdapter();
        int rows = audio.GetEnabled() ? 3 : 2;
        if (audio.GetEnabled())
            item = QString (sSectionItemTpl2)
                   .arg (tr ("Host Driver", "details report (audio)"),
                         toString (audio.GetAudioDriver())) +
                   QString (sSectionItemTpl2)
                   .arg (tr ("Controller", "details report (audio)"),
                         toString (audio.GetAudioController()));
        else
            item = QString (sSectionItemTpl1)
                   .arg (tr ("Disabled", "details report (audio)"));

        report += sectionTpl
            .arg (rows + 1) /* rows */
            .arg (":/sound_16px.png", /* icon */
                  "#audio", /* link */
                  tr ("Audio", "details report"), /* title */
                  item); /* items */
    }

    /* Network */
    {
        QString item;

        ulong count = mVBox.GetSystemProperties().GetNetworkAdapterCount();
        int rows = 2; /* including section header and footer */
        for (ulong slot = 0; slot < count; slot ++)
        {
            CNetworkAdapter adapter = aMachine.GetNetworkAdapter (slot);
            if (adapter.GetEnabled())
            {
                KNetworkAttachmentType type = adapter.GetAttachmentType();
                QString attType = toString (adapter.GetAdapterType())
                                  .replace (QRegExp ("\\s\\(.+\\)"), " (%1)");
                /* don't use the adapter type string for types that have
                 * an additional symbolic network/interface name field, use
                 * this name instead */
                if (type == KNetworkAttachmentType_Bridged)
                    attType = attType.arg (tr ("Bridged adapter, %1",
                        "details report (network)").arg (adapter.GetHostInterface()));
                else if (type == KNetworkAttachmentType_Internal)
                    attType = attType.arg (tr ("Internal network, '%1'",
                        "details report (network)").arg (adapter.GetInternalNetwork()));
                else if (type == KNetworkAttachmentType_HostOnly)
                    attType = attType.arg (tr ("Host-only adapter, '%1'",
                        "details report (network)").arg (adapter.GetHostInterface()));
#ifdef VBOX_WITH_VDE
                else if (type == KNetworkAttachmentType_VDE)
                    attType = attType.arg (tr ("VDE network, '%1'",
                        "details report (network)").arg (adapter.GetVDENetwork()));
#endif
                else
                    attType = attType.arg (vboxGlobal().toString (type));

                item += QString (sSectionItemTpl2)
                        .arg (tr ("Adapter %1", "details report (network)")
                              .arg (adapter.GetSlot() + 1))
                        .arg (attType);
                ++ rows;
            }
        }
        if (item.isNull())
        {
            item = QString (sSectionItemTpl1)
                   .arg (tr ("Disabled", "details report (network)"));
            ++ rows;
        }

        report += sectionTpl
            .arg (rows) /* rows */
            .arg (":/nw_16px.png", /* icon */
                  "#network", /* link */
                  tr ("Network", "details report"), /* title */
                  item); /* items */
    }

    /* Serial Ports */
    {
        QString item;

        ulong count = mVBox.GetSystemProperties().GetSerialPortCount();
        int rows = 2; /* including section header and footer */
        for (ulong slot = 0; slot < count; slot ++)
        {
            CSerialPort port = aMachine.GetSerialPort (slot);
            if (port.GetEnabled())
            {
                KPortMode mode = port.GetHostMode();
                QString data =
                    toCOMPortName (port.GetIRQ(), port.GetIOBase()) + ", ";
                if (mode == KPortMode_HostPipe ||
                    mode == KPortMode_HostDevice ||
                    mode == KPortMode_RawFile)
                    data += QString ("%1 (<nobr>%2</nobr>)")
                            .arg (vboxGlobal().toString (mode))
                            .arg (QDir::toNativeSeparators (port.GetPath()));
                else
                    data += toString (mode);

                item += QString (sSectionItemTpl2)
                        .arg (tr ("Port %1", "details report (serial ports)")
                              .arg (port.GetSlot() + 1))
                        .arg (data);
                ++ rows;
            }
        }
        if (item.isNull())
        {
            item = QString (sSectionItemTpl1)
                   .arg (tr ("Disabled", "details report (serial ports)"));
            ++ rows;
        }

        report += sectionTpl
            .arg (rows) /* rows */
            .arg (":/serial_port_16px.png", /* icon */
                  "#serialPorts", /* link */
                  tr ("Serial Ports", "details report"), /* title */
                  item); /* items */
    }

    /* Parallel Ports */
    {
        QString item;

        ulong count = mVBox.GetSystemProperties().GetParallelPortCount();
        int rows = 2; /* including section header and footer */
        for (ulong slot = 0; slot < count; slot ++)
        {
            CParallelPort port = aMachine.GetParallelPort (slot);
            if (port.GetEnabled())
            {
                QString data =
                    toLPTPortName (port.GetIRQ(), port.GetIOBase()) +
                    QString (" (<nobr>%1</nobr>)")
                    .arg (QDir::toNativeSeparators (port.GetPath()));

                item += QString (sSectionItemTpl2)
                        .arg (tr ("Port %1", "details report (parallel ports)")
                              .arg (port.GetSlot() + 1))
                        .arg (data);
                ++ rows;
            }
        }
        if (item.isNull())
        {
            item = QString (sSectionItemTpl1)
                   .arg (tr ("Disabled", "details report (parallel ports)"));
            ++ rows;
        }

        /* Temporary disabled */
        QString dummy = sectionTpl /* report += sectionTpl */
            .arg (rows) /* rows */
            .arg (":/parallel_port_16px.png", /* icon */
                  "#parallelPorts", /* link */
                  tr ("Parallel Ports", "details report"), /* title */
                  item); /* items */
    }

    /* USB */
    {
        QString item;

        CUSBController ctl = aMachine.GetUSBController();
        if (   !ctl.isNull()
            && ctl.GetProxyAvailable())
        {
            /* the USB controller may be unavailable (i.e. in VirtualBox OSE) */

            if (ctl.GetEnabled())
            {
                CUSBDeviceFilterVector coll = ctl.GetDeviceFilters();
                uint active = 0;
                for (int i = 0; i < coll.size(); ++i)
                    if (coll[i].GetActive())
                        active ++;

                item = QString (sSectionItemTpl2)
                       .arg (tr ("Device Filters", "details report (USB)"),
                             tr ("%1 (%2 active)", "details report (USB)")
                                 .arg (coll.size()).arg (active));
            }
            else
                item = QString (sSectionItemTpl1)
                       .arg (tr ("Disabled", "details report (USB)"));

            report += sectionTpl
                .arg (2 + 1) /* rows */
                .arg (":/usb_16px.png", /* icon */
                      "#usb", /* link */
                      tr ("USB", "details report"), /* title */
                      item); /* items */
        }
    }

    /* Shared Folders */
    {
        QString item;

        ulong count = aMachine.GetSharedFolders().size();
        if (count > 0)
        {
            item = QString (sSectionItemTpl2)
                   .arg (tr ("Shared Folders", "details report (shared folders)"))
                   .arg (count);
        }
        else
            item = QString (sSectionItemTpl1)
                   .arg (tr ("None", "details report (shared folders)"));

        report += sectionTpl
            .arg (2 + 1) /* rows */
            .arg (":/shared_folder_16px.png", /* icon */
                  "#sfolders", /* link */
                  tr ("Shared Folders", "details report"), /* title */
                  item); /* items */
    }

    return QString (sTableTpl). arg (report);
}

QString VBoxGlobal::platformInfo()
{
    QString platform;

#if defined (Q_OS_WIN)
    platform = "win";
#elif defined (Q_OS_LINUX)
    platform = "linux";
#elif defined (Q_OS_MACX)
    platform = "macosx";
#elif defined (Q_OS_OS2)
    platform = "os2";
#elif defined (Q_OS_FREEBSD)
    platform = "freebsd";
#elif defined (Q_OS_SOLARIS)
    platform = "solaris";
#else
    platform = "unknown";
#endif

    /* The format is <system>.<bitness> */
    platform += QString (".%1").arg (ARCH_BITS);

    /* Add more system information */
#if defined (Q_OS_WIN)
    OSVERSIONINFO versionInfo;
    ZeroMemory (&versionInfo, sizeof (OSVERSIONINFO));
    versionInfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
    GetVersionEx (&versionInfo);
    int major = versionInfo.dwMajorVersion;
    int minor = versionInfo.dwMinorVersion;
    int build = versionInfo.dwBuildNumber;
    QString sp = QString::fromUtf16 ((ushort*)versionInfo.szCSDVersion);

    QString distrib;
    if (major == 6)
        distrib = QString ("Windows Vista %1");
    else if (major == 5)
    {
        if (minor == 2)
            distrib = QString ("Windows Server 2003 %1");
        else if (minor == 1)
            distrib = QString ("Windows XP %1");
        else if (minor == 0)
            distrib = QString ("Windows 2000 %1");
        else
            distrib = QString ("Unknown %1");
    }
    else if (major == 4)
    {
        if (minor == 90)
            distrib = QString ("Windows Me %1");
        else if (minor == 10)
            distrib = QString ("Windows 98 %1");
        else if (minor == 0)
            distrib = QString ("Windows 95 %1");
        else
            distrib = QString ("Unknown %1");
    }
    else /** @todo Windows Server 2008 == vista? Probably not... */
        distrib = QString ("Unknown %1");
    distrib = distrib.arg (sp);
    QString version = QString ("%1.%2").arg (major).arg (minor);
    QString kernel = QString ("%1").arg (build);
    platform += QString (" [Distribution: %1 | Version: %2 | Build: %3]")
        .arg (distrib).arg (version).arg (kernel);
#elif defined (Q_OS_LINUX)
    /* Get script path */
    char szAppPrivPath [RTPATH_MAX];
    int rc = RTPathAppPrivateNoArch (szAppPrivPath, sizeof (szAppPrivPath)); NOREF(rc);
    AssertRC (rc);
    /* Run script */
    QByteArray result =
        Process::singleShot (QString (szAppPrivPath) + "/VBoxSysInfo.sh");
    if (!result.isNull())
        platform += QString (" [%1]").arg (QString (result).trimmed());
#else
    /* Use RTSystemQueryOSInfo. */
    char szTmp[256];
    QStringList components;
    int vrc = RTSystemQueryOSInfo (RTSYSOSINFO_PRODUCT, szTmp, sizeof (szTmp));
    if ((RT_SUCCESS (vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
        components << QString ("Product: %1").arg (szTmp);
    vrc = RTSystemQueryOSInfo (RTSYSOSINFO_RELEASE, szTmp, sizeof (szTmp));
    if ((RT_SUCCESS (vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
        components << QString ("Release: %1").arg (szTmp);
    vrc = RTSystemQueryOSInfo (RTSYSOSINFO_VERSION, szTmp, sizeof (szTmp));
    if ((RT_SUCCESS (vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
        components << QString ("Version: %1").arg (szTmp);
    vrc = RTSystemQueryOSInfo (RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof (szTmp));
    if ((RT_SUCCESS (vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
        components << QString ("SP: %1").arg (szTmp);
    if (!components.isEmpty())
        platform += QString (" [%1]").arg (components.join (" | "));
#endif

    return platform;
}

#if defined(Q_WS_X11) && !defined(VBOX_OSE)
double VBoxGlobal::findLicenseFile (const QStringList &aFilesList, QRegExp aPattern, QString &aLicenseFile) const
{
    double maxVersionNumber = 0;
    aLicenseFile = "";
    for (int index = 0; index < aFilesList.count(); ++ index)
    {
        aPattern.indexIn (aFilesList [index]);
        QString version = aPattern.cap (1);
        if (maxVersionNumber < version.toDouble())
        {
            maxVersionNumber = version.toDouble();
            aLicenseFile = aFilesList [index];
        }
    }
    return maxVersionNumber;
}

bool VBoxGlobal::showVirtualBoxLicense()
{
    /* get the apps doc path */
    int size = 256;
    char *buffer = (char*) RTMemTmpAlloc (size);
    RTPathAppDocs (buffer, size);
    QString path (buffer);
    RTMemTmpFree (buffer);
    QDir docDir (path);
    docDir.setFilter (QDir::Files);
    docDir.setNameFilters (QStringList ("License-*.html"));

    /* Make sure that the language is in two letter code.
     * Note: if languageId() returns an empty string lang.name() will
     * return "C" which is an valid language code. */
    QLocale lang (VBoxGlobal::languageId());

    QStringList filesList = docDir.entryList();
    QString licenseFile;
    /* First try to find a localized version of the license file. */
    double versionNumber = findLicenseFile (filesList, QRegExp (QString ("License-([\\d\\.]+)-%1.html").arg (lang.name())), licenseFile);
    /* If there wasn't a localized version of the currently selected language,
     * search for the generic one. */
    if (versionNumber == 0)
        versionNumber = findLicenseFile (filesList, QRegExp ("License-([\\d\\.]+).html"), licenseFile);
    /* Check the version again. */
    if (!versionNumber)
    {
        vboxProblem().cannotFindLicenseFiles (path);
        return false;
    }

    /* compose the latest license file full path */
    QString latestVersion = QString::number (versionNumber);
    QString latestFilePath = docDir.absoluteFilePath (licenseFile);

    /* check for the agreed license version */
    QString licenseAgreed = virtualBox().GetExtraData (VBoxDefs::GUI_LicenseKey);
    if (licenseAgreed == latestVersion)
        return true;

    VBoxLicenseViewer licenseDialog (latestFilePath);
    bool result = licenseDialog.exec() == QDialog::Accepted;
    if (result)
        virtualBox().SetExtraData (VBoxDefs::GUI_LicenseKey, latestVersion);
    return result;
}
#endif /* defined(Q_WS_X11) && !defined(VBOX_OSE) */

/**
 *  Opens a direct session for a machine with the given ID.
 *  This method does user-friendly error handling (display error messages, etc.).
 *  and returns a null CSession object in case of any error.
 *  If this method succeeds, don't forget to close the returned session when
 *  it is no more necessary.
 *
 *  @param aId          Machine ID.
 *  @param aExisting    @c true to open an existing session with the machine
 *                      which is already running, @c false to open a new direct
 *                      session.
 */
CSession VBoxGlobal::openSession (const QString &aId, bool aExisting /* = false */)
{
    CSession session;
    session.createInstance (CLSID_Session);
    if (session.isNull())
    {
        vboxProblem().cannotOpenSession (session);
        return session;
    }

    if (aExisting)
        mVBox.OpenExistingSession (session, aId);
    else
    {
        mVBox.OpenSession (session, aId);
        CMachine machine = session.GetMachine ();
        /* Make sure that the language is in two letter code.
         * Note: if languageId() returns an empty string lang.name() will
         * return "C" which is an valid language code. */
        QLocale lang (VBoxGlobal::languageId());
        machine.SetGuestPropertyValue ("/VirtualBox/HostInfo/GUI/LanguageID", lang.name());
    }

    if (!mVBox.isOk())
    {
        CMachine machine = CVirtualBox (mVBox).GetMachine (aId);
        vboxProblem().cannotOpenSession (mVBox, machine);
        session.detach();
    }

    return session;
}

/**
 *  Starts a machine with the given ID.
 */
bool VBoxGlobal::startMachine(const QString &strId)
{
    AssertReturn(mValid, false);

    CSession session = vboxGlobal().openSession(strId);
    if (session.isNull())
        return false;

#ifdef VBOX_WITH_NEW_RUNTIME_CORE
# ifndef VBOX_FORCE_NEW_RUNTIME_CORE_ALWAYS
    if (session.GetMachine().GetMonitorCount() > 1)
# endif /* VBOX_FORCE_NEW_RUNTIME_CORE_ALWAYS */
        return createVirtualMachine(session);
# ifndef VBOX_FORCE_NEW_RUNTIME_CORE_ALWAYS
    else
# endif /* VBOX_FORCE_NEW_RUNTIME_CORE_ALWAYS */
#endif /* VBOX_WITH_NEW_RUNTIME_CORE */
        return consoleWnd().openView(session);
}

/**
 * Appends the NULL medium to the media list.
 * For using with VBoxGlobal::startEnumeratingMedia() only.
 */
static void addNullMediumToList (VBoxMediaList &aList, VBoxMediaList::iterator aWhere)
{
    VBoxMedium medium;
    aList.insert (aWhere, medium);
}

/**
 * Appends the given list of mediums to the media list.
 * For using with VBoxGlobal::startEnumeratingMedia() only.
 */
static void addMediumsToList (const CMediumVector &aVector,
                              VBoxMediaList &aList,
                              VBoxMediaList::iterator aWhere,
                              VBoxDefs::MediumType aType,
                              VBoxMedium *aParent = 0)
{
    VBoxMediaList::iterator first = aWhere;

    for (CMediumVector::ConstIterator it = aVector.begin(); it != aVector.end(); ++ it)
    {
        CMedium cmedium (*it);
        VBoxMedium medium (cmedium, aType, aParent);

        /* Search for a proper alphabetic position */
        VBoxMediaList::iterator jt = first;
        for (; jt != aWhere; ++ jt)
            if ((*jt).name().localeAwareCompare (medium.name()) > 0)
                break;

        aList.insert (jt, medium);

        /* Adjust the first item if inserted before it */
        if (jt == first)
            -- first;
    }
}

/**
 * Appends the given list of hard disks and all their children to the media list.
 * For using with VBoxGlobal::startEnumeratingMedia() only.
 */
static void addHardDisksToList (const CMediumVector &aVector,
                                VBoxMediaList &aList,
                                VBoxMediaList::iterator aWhere,
                                VBoxMedium *aParent = 0)
{
    VBoxMediaList::iterator first = aWhere;

    /* First pass: Add siblings sorted */
    for (CMediumVector::ConstIterator it = aVector.begin(); it != aVector.end(); ++ it)
    {
        CMedium cmedium (*it);
        VBoxMedium medium (cmedium, VBoxDefs::MediumType_HardDisk, aParent);

        /* Search for a proper alphabetic position */
        VBoxMediaList::iterator jt = first;
        for (; jt != aWhere; ++ jt)
            if ((*jt).name().localeAwareCompare (medium.name()) > 0)
                break;

        aList.insert (jt, medium);

        /* Adjust the first item if inserted before it */
        if (jt == first)
            -- first;
    }

    /* Second pass: Add children */
    for (VBoxMediaList::iterator it = first; it != aWhere;)
    {
        CMediumVector children = (*it).medium().GetChildren();
        VBoxMedium *parent = &(*it);

        ++ it; /* go to the next sibling before inserting children */
        addHardDisksToList (children, aList, it, parent);
    }
}

/**
 * Starts a thread that asynchronously enumerates all currently registered
 * media.
 *
 * Before the enumeration is started, the current media list (a list returned by
 * #currentMediaList()) is populated with all registered media and the
 * #mediumEnumStarted() signal is emitted. The enumeration thread then walks this
 * list, checks for media acessiblity and emits #mediumEnumerated() signals of
 * each checked medium. When all media are checked, the enumeration thread is
 * stopped and the #mediumEnumFinished() signal is emitted.
 *
 * If the enumeration is already in progress, no new thread is started.
 *
 * The media list returned by #currentMediaList() is always sorted
 * alphabetically by the location attribute and comes in the following order:
 * <ol>
 *  <li>All hard disks. If a hard disk has children, these children
 *      (alphabetically sorted) immediately follow their parent and terefore
 *      appear before its next sibling hard disk.</li>
 *  <li>All CD/DVD images.</li>
 *  <li>All Floppy images.</li>
 * </ol>
 *
 * Note that #mediumEnumerated() signals are emitted in the same order as
 * described above.
 *
 * @sa #currentMediaList()
 * @sa #isMediaEnumerationStarted()
 */
void VBoxGlobal::startEnumeratingMedia()
{
    AssertReturnVoid (mValid);

    /* check if already started but not yet finished */
    if (mMediaEnumThread != NULL)
        return;

    /* ignore the request during application termination */
    if (sVBoxGlobalInCleanup)
        return;

    /* composes a list of all currently known media & their children */
    mMediaList.clear();
    addNullMediumToList (mMediaList, mMediaList.end());
    addHardDisksToList (mVBox.GetHardDisks(), mMediaList, mMediaList.end());
    addMediumsToList (mVBox.GetHost().GetDVDDrives(), mMediaList, mMediaList.end(), VBoxDefs::MediumType_DVD);
    addMediumsToList (mVBox.GetDVDImages(), mMediaList, mMediaList.end(), VBoxDefs::MediumType_DVD);
    addMediumsToList (mVBox.GetHost().GetFloppyDrives(), mMediaList, mMediaList.end(), VBoxDefs::MediumType_Floppy);
    addMediumsToList (mVBox.GetFloppyImages(), mMediaList, mMediaList.end(), VBoxDefs::MediumType_Floppy);

    /* enumeration thread class */
    class MediaEnumThread : public QThread
    {
    public:

        MediaEnumThread (VBoxMediaList &aList)
            : mVector (aList.size())
            , mSavedIt (aList.begin())
        {
            int i = 0;
            for (VBoxMediaList::const_iterator it = aList.begin();
                 it != aList.end(); ++ it)
                mVector [i ++] = *it;
        }

        virtual void run()
        {
            LogFlow (("MediaEnumThread started.\n"));
            COMBase::InitializeCOM();

            CVirtualBox mVBox = vboxGlobal().virtualBox();
            QObject *self = &vboxGlobal();

            /* Enumerate the list */
            for (int i = 0; i < mVector.size() && !sVBoxGlobalInCleanup; ++ i)
            {
                mVector [i].blockAndQueryState();
                QApplication::
                    postEvent (self,
                               new VBoxMediaEnumEvent (mVector [i], mSavedIt));
            }

            /* Post the end-of-enumeration event */
            if (!sVBoxGlobalInCleanup)
                QApplication::postEvent (self, new VBoxMediaEnumEvent (mSavedIt));

            COMBase::CleanupCOM();
            LogFlow (("MediaEnumThread finished.\n"));
        }

    private:

        QVector <VBoxMedium> mVector;
        VBoxMediaList::iterator mSavedIt;
    };

    mMediaEnumThread = new MediaEnumThread (mMediaList);
    AssertReturnVoid (mMediaEnumThread);

    /* emit mediumEnumStarted() after we set mMediaEnumThread to != NULL
     * to cause isMediaEnumerationStarted() to return TRUE from slots */
    emit mediumEnumStarted();

    mMediaEnumThread->start();
}

/**
 * Adds a new medium to the current media list and emits the #mediumAdded()
 * signal.
 *
 * @sa #currentMediaList()
 */
void VBoxGlobal::addMedium (const VBoxMedium &aMedium)
{
    /* Note that we maitain the same order here as #startEnumeratingMedia() */

    VBoxMediaList::iterator it = mMediaList.begin();

    if (aMedium.type() == VBoxDefs::MediumType_HardDisk)
    {
        VBoxMediaList::iterator itParent = mMediaList.end();

        for (; it != mMediaList.end(); ++ it)
        {
            /* skip null medium that come first */
            if ((*it).isNull()) continue;

            if ((*it).type() != VBoxDefs::MediumType_HardDisk)
                break;

            if (aMedium.parent() != NULL && itParent == mMediaList.end())
            {
                if (&*it == aMedium.parent())
                    itParent = it;
            }
            else
            {
                /* break if met a parent's sibling (will insert before it) */
                if (aMedium.parent() != NULL &&
                    (*it).parent() == (*itParent).parent())
                    break;

                /* compare to aMedium's siblings */
                if ((*it).parent() == aMedium.parent() &&
                    (*it).name().localeAwareCompare (aMedium.name()) > 0)
                    break;
            }
        }

        AssertReturnVoid (aMedium.parent() == NULL || itParent != mMediaList.end());
    }
    else
    {
        for (; it != mMediaList.end(); ++ it)
        {
            /* skip null medium that come first */
            if ((*it).isNull()) continue;

            /* skip HardDisks that come first */
            if ((*it).type() == VBoxDefs::MediumType_HardDisk)
                continue;

            /* skip DVD when inserting Floppy */
            if (aMedium.type() == VBoxDefs::MediumType_Floppy &&
                (*it).type() == VBoxDefs::MediumType_DVD)
                continue;

            if ((*it).name().localeAwareCompare (aMedium.name()) > 0 ||
                (aMedium.type() == VBoxDefs::MediumType_DVD &&
                 (*it).type() == VBoxDefs::MediumType_Floppy))
                break;
        }
    }

    it = mMediaList.insert (it, aMedium);

    emit mediumAdded (*it);
}

/**
 * Updates the medium in the current media list and emits the #mediumUpdated()
 * signal.
 *
 * @sa #currentMediaList()
 */
void VBoxGlobal::updateMedium (const VBoxMedium &aMedium)
{
    VBoxMediaList::Iterator it;
    for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
        if ((*it).id() == aMedium.id())
            break;

    AssertReturnVoid (it != mMediaList.end());

    if (&*it != &aMedium)
        *it = aMedium;

    emit mediumUpdated (*it);
}

/**
 * Removes the medium from the current media list and emits the #mediumRemoved()
 * signal.
 *
 * @sa #currentMediaList()
 */
void VBoxGlobal::removeMedium (VBoxDefs::MediumType aType, const QString &aId)
{
    VBoxMediaList::Iterator it;
    for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
        if ((*it).id() == aId)
            break;

    AssertReturnVoid (it != mMediaList.end());

#if DEBUG
    /* sanity: must be no children */
    {
        VBoxMediaList::Iterator jt = it;
        ++ jt;
        AssertReturnVoid (jt == mMediaList.end() || (*jt).parent() != &*it);
    }
#endif

    VBoxMedium *pParent = (*it).parent();

    /* remove the medium from the list to keep it in sync with the server "for
     * free" when the medium is deleted from one of our UIs */
    mMediaList.erase (it);

    emit mediumRemoved (aType, aId);

    /* also emit the parent update signal because some attributes like
     * isReadOnly() may have been changed after child removal */
    if (pParent != NULL)
    {
        pParent->refresh();
        emit mediumUpdated (*pParent);
    }
}

/**
 *  Searches for a VBoxMedum object representing the given COM medium object.
 *
 *  @return true if found and false otherwise.
 */
bool VBoxGlobal::findMedium (const CMedium &aObj, VBoxMedium &aMedium) const
{
    for (VBoxMediaList::ConstIterator it = mMediaList.begin(); it != mMediaList.end(); ++ it)
    {
        if (((*it).medium().isNull() && aObj.isNull()) ||
            (!(*it).medium().isNull() && !aObj.isNull() && (*it).medium().GetId() == aObj.GetId()))
        {
            aMedium = (*it);
            return true;
        }
    }
    return false;
}

/**
 *  Searches for a VBoxMedum object with the given medium id attribute.
 *
 *  @return VBoxMedum if found which is invalid otherwise.
 */
VBoxMedium VBoxGlobal::findMedium (const QString &aMediumId) const
{
    for (VBoxMediaList::ConstIterator it = mMediaList.begin(); it != mMediaList.end(); ++ it)
        if ((*it).id() == aMediumId)
            return *it;
    return VBoxMedium();
}

#ifdef VBOX_GUI_WITH_SYSTRAY
/**
 *  Returns the number of current running Fe/Qt4 main windows.
 *
 *  @return Number of running main windows.
 */
int VBoxGlobal::mainWindowCount ()
{
    return mVBox.GetExtraData (VBoxDefs::GUI_MainWindowCount).toInt();
}
#endif

/**
 *  Native language name of the currently installed translation.
 *  Returns "English" if no translation is installed
 *  or if the translation file is invalid.
 */
QString VBoxGlobal::languageName() const
{

    return qApp->translate ("@@@", "English",
                            "Native language name");
}

/**
 *  Native language country name of the currently installed translation.
 *  Returns "--" if no translation is installed or if the translation file is
 *  invalid, or if the language is independent on the country.
 */
QString VBoxGlobal::languageCountry() const
{
    return qApp->translate ("@@@", "--",
                            "Native language country name "
                            "(empty if this language is for all countries)");
}

/**
 *  Language name of the currently installed translation, in English.
 *  Returns "English" if no translation is installed
 *  or if the translation file is invalid.
 */
QString VBoxGlobal::languageNameEnglish() const
{

    return qApp->translate ("@@@", "English",
                            "Language name, in English");
}

/**
 *  Language country name of the currently installed translation, in English.
 *  Returns "--" if no translation is installed or if the translation file is
 *  invalid, or if the language is independent on the country.
 */
QString VBoxGlobal::languageCountryEnglish() const
{
    return qApp->translate ("@@@", "--",
                            "Language country name, in English "
                            "(empty if native country name is empty)");
}

/**
 *  Comma-separated list of authors of the currently installed translation.
 *  Returns "Oracle Corporation" if no translation is installed or if the
 *  translation file is invalid, or if the translation is supplied by Sun
 *  Microsystems, inc.
 */
QString VBoxGlobal::languageTranslators() const
{
    return qApp->translate ("@@@", "Oracle Corporation",
                            "Comma-separated list of translators");
}

/**
 *  Changes the language of all global string constants according to the
 *  currently installed translations tables.
 */
void VBoxGlobal::retranslateUi()
{
    mMachineStates [KMachineState_PoweredOff] = tr ("Powered Off", "MachineState");
    mMachineStates [KMachineState_Saved] =      tr ("Saved", "MachineState");
    mMachineStates [KMachineState_Teleported] = tr ("Teleported", "MachineState");
    mMachineStates [KMachineState_Aborted] =    tr ("Aborted", "MachineState");
    mMachineStates [KMachineState_Running] =    tr ("Running", "MachineState");
    mMachineStates [KMachineState_Paused] =     tr ("Paused", "MachineState");
    mMachineStates [KMachineState_Stuck] =      tr ("Guru Meditation", "MachineState");
    mMachineStates [KMachineState_Teleporting] = tr ("Teleporting", "MachineState");
    mMachineStates [KMachineState_LiveSnapshotting] = tr ("Taking Live Snapshot", "MachineState");
    mMachineStates [KMachineState_Starting] =   tr ("Starting", "MachineState");
    mMachineStates [KMachineState_Stopping] =   tr ("Stopping", "MachineState");
    mMachineStates [KMachineState_Saving] =     tr ("Saving", "MachineState");
    mMachineStates [KMachineState_Restoring] =  tr ("Restoring", "MachineState");
    mMachineStates [KMachineState_TeleportingPausedVM] = tr ("Teleporting Paused VM", "MachineState");
    mMachineStates [KMachineState_TeleportingIn] = tr ("Teleporting", "MachineState");
    mMachineStates [KMachineState_RestoringSnapshot] = tr ("Restoring Snapshot", "MachineState");
    mMachineStates [KMachineState_DeletingSnapshot] = tr ("Deleting Snapshot", "MachineState");
    mMachineStates [KMachineState_DeletingSnapshotOnline] = tr ("Deleting Snapshot", "MachineState");
    mMachineStates [KMachineState_DeletingSnapshotPaused] = tr ("Deleting Snapshot", "MachineState");
    mMachineStates [KMachineState_SettingUp] =  tr ("Setting Up", "MachineState");

    mSessionStates [KSessionState_Closed] =     tr ("Closed", "SessionState");
    mSessionStates [KSessionState_Open] =       tr ("Open", "SessionState");
    mSessionStates [KSessionState_Spawning] =   tr ("Spawning", "SessionState");
    mSessionStates [KSessionState_Closing] =    tr ("Closing", "SessionState");

    mDeviceTypes [KDeviceType_Null] =           tr ("None", "DeviceType");
    mDeviceTypes [KDeviceType_Floppy] =         tr ("Floppy", "DeviceType");
    mDeviceTypes [KDeviceType_DVD] =            tr ("CD/DVD-ROM", "DeviceType");
    mDeviceTypes [KDeviceType_HardDisk] =       tr ("Hard Disk", "DeviceType");
    mDeviceTypes [KDeviceType_Network] =        tr ("Network", "DeviceType");
    mDeviceTypes [KDeviceType_USB] =            tr ("USB", "DeviceType");
    mDeviceTypes [KDeviceType_SharedFolder] =   tr ("Shared Folder", "DeviceType");

    mStorageBuses [KStorageBus_IDE] =       tr ("IDE", "StorageBus");
    mStorageBuses [KStorageBus_SATA] =      tr ("SATA", "StorageBus");
    mStorageBuses [KStorageBus_SCSI] =      tr ("SCSI", "StorageBus");
    mStorageBuses [KStorageBus_Floppy] =    tr ("Floppy", "StorageBus");
    mStorageBuses [KStorageBus_SAS] =      tr ("SAS", "StorageBus");

    mStorageBusChannels [0] = tr ("Primary", "StorageBusChannel");
    mStorageBusChannels [1] = tr ("Secondary", "StorageBusChannel");
    mStorageBusChannels [2] = tr ("Port %1", "StorageBusChannel");

    mStorageBusDevices [0] = tr ("Master", "StorageBusDevice");
    mStorageBusDevices [1] = tr ("Slave", "StorageBusDevice");
    mStorageBusDevices [2] = tr ("Device %1", "StorageBusDevice");

    mSlotTemplates [0] = tr ("IDE Primary Master", "New Storage UI : Slot Name");
    mSlotTemplates [1] = tr ("IDE Primary Slave", "New Storage UI : Slot Name");
    mSlotTemplates [2] = tr ("IDE Secondary Master", "New Storage UI : Slot Name");
    mSlotTemplates [3] = tr ("IDE Secondary Slave", "New Storage UI : Slot Name");
    mSlotTemplates [4] = tr ("SATA Port %1", "New Storage UI : Slot Name");
    mSlotTemplates [5] = tr ("SCSI Port %1", "New Storage UI : Slot Name");
    mSlotTemplates [6] = tr ("SAS Port %1", "New Storage UI : Slot Name");
    mSlotTemplates [7] = tr ("Floppy Device %1", "New Storage UI : Slot Name");

    mDiskTypes [KMediumType_Normal] =           tr ("Normal", "DiskType");
    mDiskTypes [KMediumType_Immutable] =        tr ("Immutable", "DiskType");
    mDiskTypes [KMediumType_Writethrough] =     tr ("Writethrough", "DiskType");
    mDiskTypes [KMediumType_Shareable] =        tr ("Shareable", "DiskType");
    mDiskTypes_Differencing =                   tr ("Differencing", "DiskType");

    mVRDPAuthTypes [KVRDPAuthType_Null] =       tr ("Null", "VRDPAuthType");
    mVRDPAuthTypes [KVRDPAuthType_External] =   tr ("External", "VRDPAuthType");
    mVRDPAuthTypes [KVRDPAuthType_Guest] =      tr ("Guest", "VRDPAuthType");

    mPortModeTypes [KPortMode_Disconnected] =   tr ("Disconnected", "PortMode");
    mPortModeTypes [KPortMode_HostPipe] =       tr ("Host Pipe", "PortMode");
    mPortModeTypes [KPortMode_HostDevice] =     tr ("Host Device", "PortMode");
    mPortModeTypes [KPortMode_RawFile] =        tr ("Raw File", "PortMode");

    mUSBFilterActionTypes [KUSBDeviceFilterAction_Ignore] =
        tr ("Ignore", "USBFilterActionType");
    mUSBFilterActionTypes [KUSBDeviceFilterAction_Hold] =
        tr ("Hold", "USBFilterActionType");

    mAudioDriverTypes [KAudioDriverType_Null] =
        tr ("Null Audio Driver", "AudioDriverType");
    mAudioDriverTypes [KAudioDriverType_WinMM] =
        tr ("Windows Multimedia", "AudioDriverType");
    mAudioDriverTypes [KAudioDriverType_SolAudio] =
        tr ("Solaris Audio", "AudioDriverType");
    mAudioDriverTypes [KAudioDriverType_OSS] =
        tr ("OSS Audio Driver", "AudioDriverType");
    mAudioDriverTypes [KAudioDriverType_ALSA] =
        tr ("ALSA Audio Driver", "AudioDriverType");
    mAudioDriverTypes [KAudioDriverType_DirectSound] =
        tr ("Windows DirectSound", "AudioDriverType");
    mAudioDriverTypes [KAudioDriverType_CoreAudio] =
        tr ("CoreAudio", "AudioDriverType");
    mAudioDriverTypes [KAudioDriverType_Pulse] =
        tr ("PulseAudio", "AudioDriverType");

    mAudioControllerTypes [KAudioControllerType_AC97] =
        tr ("ICH AC97", "AudioControllerType");
    mAudioControllerTypes [KAudioControllerType_SB16] =
        tr ("SoundBlaster 16", "AudioControllerType");

    mNetworkAdapterTypes [KNetworkAdapterType_Am79C970A] =
        tr ("PCnet-PCI II (Am79C970A)", "NetworkAdapterType");
    mNetworkAdapterTypes [KNetworkAdapterType_Am79C973] =
        tr ("PCnet-FAST III (Am79C973)", "NetworkAdapterType");
    mNetworkAdapterTypes [KNetworkAdapterType_I82540EM] =
        tr ("Intel PRO/1000 MT Desktop (82540EM)", "NetworkAdapterType");
    mNetworkAdapterTypes [KNetworkAdapterType_I82543GC] =
        tr ("Intel PRO/1000 T Server (82543GC)", "NetworkAdapterType");
    mNetworkAdapterTypes [KNetworkAdapterType_I82545EM] =
        tr ("Intel PRO/1000 MT Server (82545EM)", "NetworkAdapterType");
#ifdef VBOX_WITH_VIRTIO
    mNetworkAdapterTypes [KNetworkAdapterType_Virtio] =
        tr ("Paravirtualized Network (virtio-net)", "NetworkAdapterType");
#endif /* VBOX_WITH_VIRTIO */

    mNetworkAttachmentTypes [KNetworkAttachmentType_Null] =
        tr ("Not attached", "NetworkAttachmentType");
    mNetworkAttachmentTypes [KNetworkAttachmentType_NAT] =
        tr ("NAT", "NetworkAttachmentType");
    mNetworkAttachmentTypes [KNetworkAttachmentType_Bridged] =
        tr ("Bridged Adapter", "NetworkAttachmentType");
    mNetworkAttachmentTypes [KNetworkAttachmentType_Internal] =
        tr ("Internal Network", "NetworkAttachmentType");
    mNetworkAttachmentTypes [KNetworkAttachmentType_HostOnly] =
        tr ("Host-only Adapter", "NetworkAttachmentType");
#ifdef VBOX_WITH_VDE
    mNetworkAttachmentTypes [KNetworkAttachmentType_VDE] =
        tr ("VDE Adapter", "NetworkAttachmentType");
#endif

    mClipboardTypes [KClipboardMode_Disabled] =
        tr ("Disabled", "ClipboardType");
    mClipboardTypes [KClipboardMode_HostToGuest] =
        tr ("Host To Guest", "ClipboardType");
    mClipboardTypes [KClipboardMode_GuestToHost] =
        tr ("Guest To Host", "ClipboardType");
    mClipboardTypes [KClipboardMode_Bidirectional] =
        tr ("Bidirectional", "ClipboardType");

    mStorageControllerTypes [KStorageControllerType_PIIX3] =
        tr ("PIIX3", "StorageControllerType");
    mStorageControllerTypes [KStorageControllerType_PIIX4] =
        tr ("PIIX4", "StorageControllerType");
    mStorageControllerTypes [KStorageControllerType_ICH6] =
        tr ("ICH6", "StorageControllerType");
    mStorageControllerTypes [KStorageControllerType_IntelAhci] =
        tr ("AHCI", "StorageControllerType");
    mStorageControllerTypes [KStorageControllerType_LsiLogic] =
        tr ("Lsilogic", "StorageControllerType");
    mStorageControllerTypes [KStorageControllerType_BusLogic] =
        tr ("BusLogic", "StorageControllerType");
    mStorageControllerTypes [KStorageControllerType_I82078] =
        tr ("I82078", "StorageControllerType");
    mStorageControllerTypes [KStorageControllerType_LsiLogicSas] =
        tr ("LsiLogic SAS", "StorageControllerType");

    mUSBDeviceStates [KUSBDeviceState_NotSupported] =
        tr ("Not supported", "USBDeviceState");
    mUSBDeviceStates [KUSBDeviceState_Unavailable] =
        tr ("Unavailable", "USBDeviceState");
    mUSBDeviceStates [KUSBDeviceState_Busy] =
        tr ("Busy", "USBDeviceState");
    mUSBDeviceStates [KUSBDeviceState_Available] =
        tr ("Available", "USBDeviceState");
    mUSBDeviceStates [KUSBDeviceState_Held] =
        tr ("Held", "USBDeviceState");
    mUSBDeviceStates [KUSBDeviceState_Captured] =
        tr ("Captured", "USBDeviceState");

    mUserDefinedPortName = tr ("User-defined", "serial port");

    mWarningIcon = standardIcon (QStyle::SP_MessageBoxWarning, 0).pixmap (16, 16);
    Assert (!mWarningIcon.isNull());

    mErrorIcon = standardIcon (QStyle::SP_MessageBoxCritical, 0).pixmap (16, 16);
    Assert (!mErrorIcon.isNull());

    /* refresh media properties since they contain some translations too  */
    for (VBoxMediaList::iterator it = mMediaList.begin();
         it != mMediaList.end(); ++ it)
        it->refresh();

#if defined (Q_WS_PM) || defined (Q_WS_X11)
    /* As PM and X11 do not (to my knowledge) have functionality for providing
     * human readable key names, we keep a table of them, which must be
     * updated when the language is changed. */
    QIHotKeyEdit::retranslateUi();
#endif
}

// public static stuff
////////////////////////////////////////////////////////////////////////////////

/* static */
bool VBoxGlobal::isDOSType (const QString &aOSTypeId)
{
    if (aOSTypeId.left (3) == "dos" ||
        aOSTypeId.left (3) == "win" ||
        aOSTypeId.left (3) == "os2")
        return true;

    return false;
}

const char *gVBoxLangSubDir = "/nls";
const char *gVBoxLangFileBase = "VirtualBox_";
const char *gVBoxLangFileExt = ".qm";
const char *gVBoxLangIDRegExp = "(([a-z]{2})(?:_([A-Z]{2}))?)|(C)";
const char *gVBoxBuiltInLangName   = "C";

class VBoxTranslator : public QTranslator
{
public:

    VBoxTranslator (QObject *aParent = 0)
        : QTranslator (aParent) {}

    bool loadFile (const QString &aFileName)
    {
        QFile file (aFileName);
        if (!file.open (QIODevice::ReadOnly))
            return false;
        mData = file.readAll();
        return load ((uchar*) mData.data(), mData.size());
    }

private:

    QByteArray mData;
};

static VBoxTranslator *sTranslator = 0;
static QString sLoadedLangId = gVBoxBuiltInLangName;

/**
 *  Returns the loaded (active) language ID.
 *  Note that it may not match with VBoxGlobalSettings::languageId() if the
 *  specified language cannot be loaded.
 *  If the built-in language is active, this method returns "C".
 *
 *  @note "C" is treated as the built-in language for simplicity -- the C
 *  locale is used in unix environments as a fallback when the requested
 *  locale is invalid. This way we don't need to process both the "built_in"
 *  language and the "C" language (which is a valid environment setting)
 *  separately.
 */
/* static */
QString VBoxGlobal::languageId()
{
    return sLoadedLangId;
}

/**
 *  Loads the language by language ID.
 *
 *  @param aLangId Language ID in in form of xx_YY. QString::null means the
 *                 system default language.
 */
/* static */
void VBoxGlobal::loadLanguage (const QString &aLangId)
{
    QString langId = aLangId.isEmpty() ?
        VBoxGlobal::systemLanguageId() : aLangId;
    QString languageFileName;
    QString selectedLangId = gVBoxBuiltInLangName;

    /* If C is selected we change it temporary to en. This makes sure any extra
     * "en" translation file will be loaded. This is necessary for loading the
     * plural forms of some of our translations. */
    bool fResetToC = false;
    if (langId == "C")
    {
        langId = "en";
        fResetToC = true;
    }

    char szNlsPath[RTPATH_MAX];
    int rc;

    rc = RTPathAppPrivateNoArch(szNlsPath, sizeof(szNlsPath));
    AssertRC (rc);

    QString nlsPath = QString(szNlsPath) + gVBoxLangSubDir;
    QDir nlsDir (nlsPath);

    Assert (!langId.isEmpty());
    if (!langId.isEmpty() && langId != gVBoxBuiltInLangName)
    {
        QRegExp regExp (gVBoxLangIDRegExp);
        int pos = regExp.indexIn (langId);
        /* the language ID should match the regexp completely */
        AssertReturnVoid (pos == 0);

        QString lang = regExp.cap (2);

        if (nlsDir.exists (gVBoxLangFileBase + langId + gVBoxLangFileExt))
        {
            languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + langId +
                                                        gVBoxLangFileExt);
            selectedLangId = langId;
        }
        else if (nlsDir.exists (gVBoxLangFileBase + lang + gVBoxLangFileExt))
        {
            languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + lang +
                                                        gVBoxLangFileExt);
            selectedLangId = lang;
        }
        else
        {
            /* Never complain when the default language is requested.  In any
             * case, if no explicit language file exists, we will simply
             * fall-back to English (built-in). */
            if (!aLangId.isNull() && langId != "en")
                vboxProblem().cannotFindLanguage (langId, nlsPath);
            /* selectedLangId remains built-in here */
            AssertReturnVoid (selectedLangId == gVBoxBuiltInLangName);
        }
    }

    /* delete the old translator if there is one */
    if (sTranslator)
    {
        /* QTranslator destructor will call qApp->removeTranslator() for
         * us. It will also delete all its child translations we attach to it
         * below, so we don't have to care about them specially. */
        delete sTranslator;
    }

    /* load new language files */
    sTranslator = new VBoxTranslator (qApp);
    Assert (sTranslator);
    bool loadOk = true;
    if (sTranslator)
    {
        if (selectedLangId != gVBoxBuiltInLangName)
        {
            Assert (!languageFileName.isNull());
            loadOk = sTranslator->loadFile (languageFileName);
        }
        /* we install the translator in any case: on failure, this will
         * activate an empty translator that will give us English
         * (built-in) */
        qApp->installTranslator (sTranslator);
    }
    else
        loadOk = false;

    if (loadOk)
        sLoadedLangId = selectedLangId;
    else
    {
        vboxProblem().cannotLoadLanguage (languageFileName);
        sLoadedLangId = gVBoxBuiltInLangName;
    }

    /* Try to load the corresponding Qt translation */
    if (sLoadedLangId != gVBoxBuiltInLangName)
    {
#ifdef Q_OS_UNIX
        /* We use system installations of Qt on Linux systems, so first, try
         * to load the Qt translation from the system location. */
        languageFileName = QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" +
                           sLoadedLangId + gVBoxLangFileExt;
        QTranslator *qtSysTr = new QTranslator (sTranslator);
        Assert (qtSysTr);
        if (qtSysTr && qtSysTr->load (languageFileName))
            qApp->installTranslator (qtSysTr);
        /* Note that the Qt translation supplied by Sun is always loaded
         * afterwards to make sure it will take precedence over the system
         * translation (it may contain more decent variants of translation
         * that better correspond to VirtualBox UI). We need to load both
         * because a newer version of Qt may be installed on the user computer
         * and the Sun version may not fully support it. We don't do it on
         * Win32 because we supply a Qt library there and therefore the
         * Sun translation is always the best one. */
#endif
        languageFileName =  nlsDir.absoluteFilePath (QString ("qt_") +
                                                     sLoadedLangId +
                                                     gVBoxLangFileExt);
        QTranslator *qtTr = new QTranslator (sTranslator);
        Assert (qtTr);
        if (qtTr && (loadOk = qtTr->load (languageFileName)))
            qApp->installTranslator (qtTr);
        /* The below message doesn't fit 100% (because it's an additional
         * language and the main one won't be reset to built-in on failure)
         * but the load failure is so rare here that it's not worth a separate
         * message (but still, having something is better than having none) */
        if (!loadOk && !aLangId.isNull())
            vboxProblem().cannotLoadLanguage (languageFileName);
    }
    if (fResetToC)
        sLoadedLangId = "C";
}

QString VBoxGlobal::helpFile() const
{
#if defined (Q_WS_WIN32)
    const QString name = "VirtualBox";
    const QString suffix = "chm";
#elif defined (Q_WS_MAC)
    const QString name = "UserManual";
    const QString suffix = "pdf";
#elif defined (Q_WS_X11)
# if defined VBOX_OSE
    const QString name = "UserManual";
    const QString suffix = "pdf";
# else
    const QString name = "VirtualBox";
    const QString suffix = "chm";
# endif
#endif
    /* Where are the docs located? */
    char szDocsPath[RTPATH_MAX];
    int rc = RTPathAppDocs (szDocsPath, sizeof (szDocsPath));
    AssertRC (rc);
    /* Make sure that the language is in two letter code.
     * Note: if languageId() returns an empty string lang.name() will
     * return "C" which is an valid language code. */
    QLocale lang (VBoxGlobal::languageId());

    /* Construct the path and the filename */
    QString manual = QString ("%1/%2_%3.%4").arg (szDocsPath)
                                            .arg (name)
                                            .arg (lang.name())
                                            .arg (suffix);
    /* Check if a help file with that name exists */
    QFileInfo fi (manual);
    if (fi.exists())
        return manual;

    /* Fall back to the standard */
    manual = QString ("%1/%2.%4").arg (szDocsPath)
                                 .arg (name)
                                 .arg (suffix);
    return manual;
}

QIcon VBoxGlobal::iconSet (const QPixmap &aNormal,
                           const QPixmap &aDisabled,
                           const QPixmap &aActive)
{
    QIcon iconSet;

    Assert (aNormal);
        iconSet.addPixmap (aNormal, QIcon::Normal);

    if (!aDisabled.isNull())
        iconSet.addPixmap (aDisabled, QIcon::Disabled);

    if (!aActive.isNull())
        iconSet.addPixmap (aActive, QIcon::Active);

    return iconSet;
}

/* static */
QIcon VBoxGlobal::iconSet (const char *aNormal,
                           const char *aDisabled /* = NULL */,
                           const char *aActive /* = NULL */)
{
    QIcon iconSet;

    Assert (aNormal != NULL);
    iconSet.addFile (aNormal, QSize(),
                     QIcon::Normal);
    if (aDisabled != NULL)
        iconSet.addFile (aDisabled, QSize(),
                         QIcon::Disabled);
    if (aActive != NULL)
        iconSet.addFile (aActive, QSize(),
                         QIcon::Active);
    return iconSet;
}

/* static */
QIcon VBoxGlobal::iconSetOnOff (const char *aNormal, const char *aNormalOff,
                                const char *aDisabled /* = NULL */,
                                const char *aDisabledOff /* = NULL */,
                                const char *aActive /* = NULL */,
                                const char *aActiveOff /* = NULL */)
{
    QIcon iconSet;

    Assert (aNormal != NULL);
    iconSet.addFile (aNormal, QSize(), QIcon::Normal, QIcon::On);
    if (aNormalOff != NULL)
        iconSet.addFile (aNormalOff, QSize(), QIcon::Normal, QIcon::Off);

    if (aDisabled != NULL)
        iconSet.addFile (aDisabled, QSize(), QIcon::Disabled, QIcon::On);
    if (aDisabledOff != NULL)
        iconSet.addFile (aDisabledOff, QSize(), QIcon::Disabled, QIcon::Off);

    if (aActive != NULL)
        iconSet.addFile (aActive, QSize(), QIcon::Active, QIcon::On);
    if (aActiveOff != NULL)
        iconSet.addFile (aActive, QSize(), QIcon::Active, QIcon::Off);

    return iconSet;
}

/* static */
QIcon VBoxGlobal::iconSetFull (const QSize &aNormalSize, const QSize &aSmallSize,
                               const char *aNormal, const char *aSmallNormal,
                               const char *aDisabled /* = NULL */,
                               const char *aSmallDisabled /* = NULL */,
                               const char *aActive /* = NULL */,
                               const char *aSmallActive /* = NULL */)
{
    QIcon iconSet;

    Assert (aNormal != NULL);
    Assert (aSmallNormal != NULL);
    iconSet.addFile (aNormal, aNormalSize, QIcon::Normal);
    iconSet.addFile (aSmallNormal, aSmallSize, QIcon::Normal);

    if (aSmallDisabled != NULL)
    {
        iconSet.addFile (aDisabled, aNormalSize, QIcon::Disabled);
        iconSet.addFile (aSmallDisabled, aSmallSize, QIcon::Disabled);
    }

    if (aSmallActive != NULL)
    {
        iconSet.addFile (aActive, aNormalSize, QIcon::Active);
        iconSet.addFile (aSmallActive, aSmallSize, QIcon::Active);
    }

    return iconSet;
}

QIcon VBoxGlobal::standardIcon (QStyle::StandardPixmap aStandard, QWidget *aWidget /* = NULL */)
{
    QStyle *style = aWidget ? aWidget->style(): QApplication::style();
    if (!style)
        return QIcon();
#ifdef Q_WS_MAC
    /* At least in Qt 4.3.4/4.4 RC1 SP_MessageBoxWarning is the application
     * icon. So change this to the critical icon. (Maybe this would be
     * fixed in a later Qt version) */
    if (aStandard == QStyle::SP_MessageBoxWarning)
        return style->standardIcon (QStyle::SP_MessageBoxCritical, 0, aWidget);
#endif /* Q_WS_MAC */
    return style->standardIcon (aStandard, 0, aWidget);
}

/**
 *  Replacement for QToolButton::setTextLabel() that handles the shortcut
 *  letter (if it is present in the argument string) as if it were a setText()
 *  call: the shortcut letter is used to automatically assign an "Alt+<letter>"
 *  accelerator key sequence to the given tool button.
 *
 *  @note This method preserves the icon set if it was assigned before. Only
 *  the text label and the accelerator are changed.
 *
 *  @param aToolButton  Tool button to set the text label on.
 *  @param aTextLabel   Text label to set.
 */
/* static */
void VBoxGlobal::setTextLabel (QToolButton *aToolButton,
                               const QString &aTextLabel)
{
    AssertReturnVoid (aToolButton != NULL);

    /* remember the icon set as setText() will kill it */
    QIcon iset = aToolButton->icon();
    /* re-use the setText() method to detect and set the accelerator */
    aToolButton->setText (aTextLabel);
    QKeySequence accel = aToolButton->shortcut();
    aToolButton->setText (aTextLabel);
    aToolButton->setIcon (iset);
    /* set the accel last as setIconSet() would kill it */
    aToolButton->setShortcut (accel);
}

/**
 *  Performs direct and flipped search of position for \a aRectangle to make sure
 *  it is fully contained inside \a aBoundRegion region by moving & resizing
 *  \a aRectangle if necessary. Selects the minimum shifted result between direct
 *  and flipped variants.
 */
/* static */
QRect VBoxGlobal::normalizeGeometry (const QRect &aRectangle, const QRegion &aBoundRegion,
                                     bool aCanResize /* = true */)
{
    /* Direct search for normalized rectangle */
    QRect var1 (getNormalized (aRectangle, aBoundRegion, aCanResize));

    /* Flipped search for normalized rectangle */
    QRect var2 (flip (getNormalized (flip (aRectangle).boundingRect(),
                                     flip (aBoundRegion), aCanResize)).boundingRect());

    /* Calculate shift from starting position for both variants */
    double length1 = sqrt (pow ((double) (var1.x() - aRectangle.x()), (double) 2) +
                           pow ((double) (var1.y() - aRectangle.y()), (double) 2));
    double length2 = sqrt (pow ((double) (var2.x() - aRectangle.x()), (double) 2) +
                           pow ((double) (var2.y() - aRectangle.y()), (double) 2));

    /* Return minimum shifted variant */
    return length1 > length2 ? var2 : var1;
}

/**
 *  Ensures that the given rectangle \a aRectangle is fully contained within the
 *  region \a aBoundRegion by moving \a aRectangle if necessary. If \a aRectangle is
 *  larger than \a aBoundRegion, top left corner of \a aRectangle is aligned with the
 *  top left corner of maximum available rectangle and, if \a aCanResize is true,
 *  \a aRectangle is shrinked to become fully visible.
 */
/* static */
QRect VBoxGlobal::getNormalized (const QRect &aRectangle, const QRegion &aBoundRegion,
                                 bool /* aCanResize = true */)
{
    /* Storing available horizontal sub-rectangles & vertical shifts */
    int windowVertical = aRectangle.center().y();
    QVector <QRect> rectanglesVector (aBoundRegion.rects());
    QList <QRect> rectanglesList;
    QList <int> shiftsList;
    foreach (QRect currentItem, rectanglesVector)
    {
        int currentDelta = qAbs (windowVertical - currentItem.center().y());
        int shift2Top = currentItem.top() - aRectangle.top();
        int shift2Bot = currentItem.bottom() - aRectangle.bottom();

        int itemPosition = 0;
        foreach (QRect item, rectanglesList)
        {
            int delta = qAbs (windowVertical - item.center().y());
            if (delta > currentDelta) break; else ++ itemPosition;
        }
        rectanglesList.insert (itemPosition, currentItem);

        int shift2TopPos = 0;
        foreach (int shift, shiftsList)
            if (qAbs (shift) > qAbs (shift2Top)) break; else ++ shift2TopPos;
        shiftsList.insert (shift2TopPos, shift2Top);

        int shift2BotPos = 0;
        foreach (int shift, shiftsList)
            if (qAbs (shift) > qAbs (shift2Bot)) break; else ++ shift2BotPos;
        shiftsList.insert (shift2BotPos, shift2Bot);
    }

    /* Trying to find the appropriate place for window */
    QRect result;
    for (int i = -1; i < shiftsList.size(); ++ i)
    {
        /* Move to appropriate vertical */
        QRect rectangle (aRectangle);
        if (i >= 0) rectangle.translate (0, shiftsList [i]);

        /* Search horizontal shift */
        int maxShift = 0;
        foreach (QRect item, rectanglesList)
        {
            QRect trectangle (rectangle.translated (item.left() - rectangle.left(), 0));
            if (!item.intersects (trectangle))
                continue;

            if (rectangle.left() < item.left())
            {
                int shift = item.left() - rectangle.left();
                maxShift = qAbs (shift) > qAbs (maxShift) ? shift : maxShift;
            }
            else if (rectangle.right() > item.right())
            {
                int shift = item.right() - rectangle.right();
                maxShift = qAbs (shift) > qAbs (maxShift) ? shift : maxShift;
            }
        }

        /* Shift across the horizontal direction */
        rectangle.translate (maxShift, 0);

        /* Check the translated rectangle to feat the rules */
        if (aBoundRegion.united (rectangle) == aBoundRegion)
            result = rectangle;

        if (!result.isNull()) break;
    }

    if (result.isNull())
    {
        /* Resize window to feat desirable size
         * using max of available rectangles */
        QRect maxRectangle;
        quint64 maxSquare = 0;
        foreach (QRect item, rectanglesList)
        {
            quint64 square = item.width() * item.height();
            if (square > maxSquare)
            {
                maxSquare = square;
                maxRectangle = item;
            }
        }

        result = aRectangle;
        result.moveTo (maxRectangle.x(), maxRectangle.y());
        if (maxRectangle.right() < result.right())
            result.setRight (maxRectangle.right());
        if (maxRectangle.bottom() < result.bottom())
            result.setBottom (maxRectangle.bottom());
    }

    return result;
}

/**
 *  Returns the flipped (transposed) region.
 */
/* static */
QRegion VBoxGlobal::flip (const QRegion &aRegion)
{
    QRegion result;
    QVector <QRect> rectangles (aRegion.rects());
    foreach (QRect rectangle, rectangles)
        result += QRect (rectangle.y(), rectangle.x(),
                         rectangle.height(), rectangle.width());
    return result;
}

/**
 *  Aligns the center of \a aWidget with the center of \a aRelative.
 *
 *  If necessary, \a aWidget's position is adjusted to make it fully visible
 *  within the available desktop area. If \a aWidget is bigger then this area,
 *  it will also be resized unless \a aCanResize is false or there is an
 *  inappropriate minimum size limit (in which case the top left corner will be
 *  simply aligned with the top left corner of the available desktop area).
 *
 *  \a aWidget must be a top-level widget. \a aRelative may be any widget, but
 *  if it's not top-level itself, its top-level widget will be used for
 *  calculations. \a aRelative can also be NULL, in which case \a aWidget will
 *  be centered relative to the available desktop area.
 */
/* static */
void VBoxGlobal::centerWidget (QWidget *aWidget, QWidget *aRelative,
                               bool aCanResize /* = true */)
{
    AssertReturnVoid (aWidget);
    AssertReturnVoid (aWidget->isTopLevel());

    QRect deskGeo, parentGeo;
    QWidget *w = aRelative;
    if (w)
    {
        w = w->window();
        deskGeo = QApplication::desktop()->availableGeometry (w);
        parentGeo = w->frameGeometry();
        /* On X11/Gnome, geo/frameGeo.x() and y() are always 0 for top level
         * widgets with parents, what a shame. Use mapToGlobal() to workaround. */
        QPoint d = w->mapToGlobal (QPoint (0, 0));
        d.rx() -= w->geometry().x() - w->x();
        d.ry() -= w->geometry().y() - w->y();
        parentGeo.moveTopLeft (d);
    }
    else
    {
        deskGeo = QApplication::desktop()->availableGeometry();
        parentGeo = deskGeo;
    }

    /* On X11, there is no way to determine frame geometry (including WM
     * decorations) before the widget is shown for the first time. Stupidly
     * enumerate other top level widgets to find the thickest frame. The code
     * is based on the idea taken from QDialog::adjustPositionInternal(). */

    int extraw = 0, extrah = 0;

    QWidgetList list = QApplication::topLevelWidgets();
    QListIterator<QWidget*> it (list);
    while ((extraw == 0 || extrah == 0) && it.hasNext())
    {
        int framew, frameh;
        QWidget *current = it.next();
        if (!current->isVisible())
            continue;

        framew = current->frameGeometry().width() - current->width();
        frameh = current->frameGeometry().height() - current->height();

        extraw = qMax (extraw, framew);
        extrah = qMax (extrah, frameh);
    }

    /// @todo (r=dmik) not sure if we really need this
#if 0
    /* sanity check for decoration frames. With embedding, we
     * might get extraordinary values */
    if (extraw == 0 || extrah == 0 || extraw > 20 || extrah > 50)
    {
        extrah = 50;
        extraw = 20;
    }
#endif

    /* On non-X11 platforms, the following would be enough instead of the
     * above workaround: */
    // QRect geo = frameGeometry();
    QRect geo = QRect (0, 0, aWidget->width() + extraw,
                             aWidget->height() + extrah);

    geo.moveCenter (QPoint (parentGeo.x() + (parentGeo.width() - 1) / 2,
                            parentGeo.y() + (parentGeo.height() - 1) / 2));

    /* ensure the widget is within the available desktop area */
    QRect newGeo = normalizeGeometry (geo, deskGeo, aCanResize);
#ifdef Q_WS_MAC
    /* No idea why, but Qt doesn't respect if there is a unified toolbar on the
     * ::move call. So manually add the height of the toolbar before setting
     * the position. */
    if (w)
        newGeo.translate (0, ::darwinWindowToolBarHeight (aWidget));
#endif /* Q_WS_MAC */

    aWidget->move (newGeo.topLeft());

    if (aCanResize &&
        (geo.width() != newGeo.width() || geo.height() != newGeo.height()))
        aWidget->resize (newGeo.width() - extraw, newGeo.height() - extrah);
}

/**
 *  Returns the decimal separator for the current locale.
 */
/* static */
QChar VBoxGlobal::decimalSep()
{
    return QLocale::system().decimalPoint();
}

/**
 *  Returns the regexp string that defines the format of the human-readable
 *  size representation, <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
 *
 *  This regexp will capture 5 groups of text:
 *  - cap(1): integer number in case when no decimal point is present
 *            (if empty, it means that decimal point is present)
 *  - cap(2): size suffix in case when no decimal point is present (may be empty)
 *  - cap(3): integer number in case when decimal point is present (may be empty)
 *  - cap(4): fraction number (hundredth) in case when decimal point is present
 *  - cap(5): size suffix in case when decimal point is present (note that
 *            B cannot appear there)
 */
/* static */
QString VBoxGlobal::sizeRegexp()
{
    QString regexp =
        tr ("^(?:(?:(\\d+)(?:\\s?(B|KB|MB|GB|TB|PB))?)|(?:(\\d*)%1(\\d{1,2})(?:\\s?(KB|MB|GB|TB|PB))))$", "regexp for matching ####[.##] B|KB|MB|GB|TB|PB, %1=decimal point")
            .arg (decimalSep());
    return regexp;
}

/**
 *  Parses the given size string that should be in form of
 *  <tt>####[.##] B|KB|MB|GB|TB|PB</tt> and returns
 *  the size value in bytes. Zero is returned on error.
 */
/* static */
quint64 VBoxGlobal::parseSize (const QString &aText)
{
    QRegExp regexp (sizeRegexp());
    int pos = regexp.indexIn (aText);
    if (pos != -1)
    {
        QString intgS = regexp.cap (1);
        QString hundS;
        QString suff = regexp.cap (2);
        if (intgS.isEmpty())
        {
            intgS = regexp.cap (3);
            hundS = regexp.cap (4);
            suff = regexp.cap (5);
        }

        quint64 denom = 0;
        if (suff.isEmpty() || suff == tr ("B", "size suffix Bytes"))
            denom = 1;
        else if (suff == tr ("KB", "size suffix KBytes=1024 Bytes"))
            denom = _1K;
        else if (suff == tr ("MB", "size suffix MBytes=1024 KBytes"))
            denom = _1M;
        else if (suff == tr ("GB", "size suffix GBytes=1024 MBytes"))
            denom = _1G;
        else if (suff == tr ("TB", "size suffix TBytes=1024 GBytes"))
            denom = _1T;
        else if (suff == tr ("PB", "size suffix PBytes=1024 TBytes"))
            denom = _1P;

        quint64 intg = intgS.toULongLong();
        if (denom == 1)
            return intg;

        quint64 hund = hundS.leftJustified (2, '0').toULongLong();
        hund = hund * denom / 100;
        intg = intg * denom + hund;
        return intg;
    }
    else
        return 0;
}

/**
 * Formats the given @a aSize value in bytes to a human readable string
 * in form of <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
 *
 * The @a aMode and @a aDecimal parameters are used for rounding the resulting
 * number when converting the size value to KB, MB, etc gives a fractional part:
 * <ul>
 * <li>When \a aMode is FormatSize_Round, the result is rounded to the
 *     closest number containing \a aDecimal decimal digits.
 * </li>
 * <li>When \a aMode is FormatSize_RoundDown, the result is rounded to the
 *     largest number with \a aDecimal decimal digits that is not greater than
 *     the result. This guarantees that converting the resulting string back to
 *     the integer value in bytes will not produce a value greater that the
 *     initial size parameter.
 * </li>
 * <li>When \a aMode is FormatSize_RoundUp, the result is rounded to the
 *     smallest number with \a aDecimal decimal digits that is not less than the
 *     result. This guarantees that converting the resulting string back to the
 *     integer value in bytes will not produce a value less that the initial
 *     size parameter.
 * </li>
 * </ul>
 *
 * @param aSize     Size value in bytes.
 * @param aMode     Conversion mode.
 * @param aDecimal  Number of decimal digits in result.
 * @return          Human-readable size string.
 */
/* static */
QString VBoxGlobal::formatSize (quint64 aSize, uint aDecimal /* = 2 */,
                                VBoxDefs::FormatSize aMode /* = FormatSize_Round */)
{
    static QString Suffixes [7];
    Suffixes[0] = tr ("B", "size suffix Bytes");
    Suffixes[1] = tr ("KB", "size suffix KBytes=1024 Bytes");
    Suffixes[2] = tr ("MB", "size suffix MBytes=1024 KBytes");
    Suffixes[3] = tr ("GB", "size suffix GBytes=1024 MBytes");
    Suffixes[4] = tr ("TB", "size suffix TBytes=1024 GBytes");
    Suffixes[5] = tr ("PB", "size suffix PBytes=1024 TBytes");
    Suffixes[6] = (const char *)NULL;
    AssertCompile(6 < RT_ELEMENTS (Suffixes));

    quint64 denom = 0;
    int suffix = 0;

    if (aSize < _1K)
    {
        denom = 1;
        suffix = 0;
    }
    else if (aSize < _1M)
    {
        denom = _1K;
        suffix = 1;
    }
    else if (aSize < _1G)
    {
        denom = _1M;
        suffix = 2;
    }
    else if (aSize < _1T)
    {
        denom = _1G;
        suffix = 3;
    }
    else if (aSize < _1P)
    {
        denom = _1T;
        suffix = 4;
    }
    else
    {
        denom = _1P;
        suffix = 5;
    }

    quint64 intg = aSize / denom;
    quint64 decm = aSize % denom;
    quint64 mult = 1;
    for (uint i = 0; i < aDecimal; ++ i) mult *= 10;

    QString number;
    if (denom > 1)
    {
        if (decm)
        {
            decm *= mult;
            /* not greater */
            if (aMode == VBoxDefs::FormatSize_RoundDown)
                decm = decm / denom;
            /* not less */
            else if (aMode == VBoxDefs::FormatSize_RoundUp)
                decm = (decm + denom - 1) / denom;
            /* nearest */
            else decm = (decm + denom / 2) / denom;
        }
        /* check for the fractional part overflow due to rounding */
        if (decm == mult)
        {
            decm = 0;
            ++ intg;
            /* check if we've got 1024 XB after rounding and scale down if so */
            if (intg == 1024 && Suffixes [suffix + 1] != NULL)
            {
                intg /= 1024;
                ++ suffix;
            }
        }
        number = QString::number (intg);
        if (aDecimal) number += QString ("%1%2").arg (decimalSep())
            .arg (QString::number (decm).rightJustified (aDecimal, '0'));
    }
    else
    {
        number = QString::number (intg);
    }

    return QString ("%1 %2").arg (number).arg (Suffixes [suffix]);
}

/**
 *  Returns the required video memory in bytes for the current desktop
 *  resolution at maximum possible screen depth in bpp.
 */
/* static */
quint64 VBoxGlobal::requiredVideoMemory (CMachine *aMachine /* = 0 */, int cMonitors /* = 1 */)
{
    QSize desktopRes = QApplication::desktop()->screenGeometry().size();
    QDesktopWidget *pDW = QApplication::desktop();
    /* We create a list of the size of all available host monitors. This list
     * is sorted by value and by starting with the biggest one, we calculate
     * the memory requirements for every guest screen. This is of course not
     * correct, but as we can't predict on which host screens the user will
     * open the guest windows, this is the best assumption we can do, cause it
     * is the worst case. */
    QVector<int> screenSize(qMax(cMonitors, pDW->numScreens()), 0);
    for (int i = 0; i < pDW->numScreens(); ++i)
    {
        QRect r = pDW->screenGeometry(i);
        screenSize[i] = r.width() * r.height();
    }
    /* Now sort the vector */
    qSort(screenSize.begin(), screenSize.end(), qGreater<int>());
    /* For the case that there are more guest screens configured then host
     * screens available, replace all zeros with the greatest value in the
     * vector. */
    for (int i = 0; i < screenSize.size(); ++i)
        if (screenSize.at(i) == 0)
            screenSize.replace(i, screenSize.at(0));

    quint64 needBits = 0;
    for (int i = 0; i < cMonitors; ++i)
    {
        /* Calculate summary required memory amount in bits */
        needBits += (screenSize.at(i) * /* with x height */
                     32 + /* we will take the maximum possible bpp for now */
                     8 * _1M) + /* current cache per screen - may be changed in future */
                    8 * 4096; /* adapter info */
    }
    /* Translate value into megabytes with rounding to highest side */
    quint64 needMBytes = needBits % (8 * _1M) ? needBits / (8 * _1M) + 1 :
                         needBits / (8 * _1M) /* convert to megabytes */;

    if (aMachine && !aMachine->isNull())
    {
       QString typeId = aMachine->GetOSTypeId();
       if (typeId.startsWith("Windows"))
       {
           /* Windows guests need offscreen VRAM too for graphics acceleration features. */
           needMBytes *= 2;
       }
    }

    return needMBytes * _1M;
}

/**
 * Puts soft hyphens after every path component in the given file name.
 *
 * @param aFileName File name (must be a full path name).
 */
/* static */
QString VBoxGlobal::locationForHTML (const QString &aFileName)
{
/// @todo (dmik) remove?
//    QString result = QDir::toNativeSeparators (fn);
//#ifdef Q_OS_LINUX
//    result.replace ('/', "/<font color=red>&shy;</font>");
//#else
//    result.replace ('\\', "\\<font color=red>&shy;</font>");
//#endif
//    return result;
    QFileInfo fi (aFileName);
    return fi.fileName();
}

/**
 *  Reformats the input string @a aStr so that:
 *  - strings in single quotes will be put inside <nobr> and marked
 *    with blue color;
 *  - UUIDs be put inside <nobr> and marked
 *    with green color;
 *  - replaces new line chars with </p><p> constructs to form paragraphs
 *    (note that <p> and </p> are not appended to the beginnign and to the
 *     end of the string respectively, to allow the result be appended
 *     or prepended to the existing paragraph).
 *
 *  If @a aToolTip is true, colouring is not applied, only the <nobr> tag
 *  is added. Also, new line chars are replaced with <br> instead of <p>.
 */
/* static */
QString VBoxGlobal::highlight (const QString &aStr, bool aToolTip /* = false */)
{
    QString strFont;
    QString uuidFont;
    QString endFont;
    if (!aToolTip)
    {
        strFont = "<font color=#0000CC>";
        uuidFont = "<font color=#008000>";
        endFont = "</font>";
    }

    QString text = aStr;

    /* replace special entities, '&' -- first! */
    text.replace ('&', "&amp;");
    text.replace ('<', "&lt;");
    text.replace ('>', "&gt;");
    text.replace ('\"', "&quot;");

    /* mark strings in single quotes with color */
    QRegExp rx = QRegExp ("((?:^|\\s)[(]?)'([^']*)'(?=[:.-!);]?(?:\\s|$))");
    rx.setMinimal (true);
    text.replace (rx,
        QString ("\\1%1<nobr>'\\2'</nobr>%2").arg (strFont).arg (endFont));

    /* mark UUIDs with color */
    text.replace (QRegExp (
        "((?:^|\\s)[(]?)"
        "(\\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\})"
        "(?=[:.-!);]?(?:\\s|$))"),
        QString ("\\1%1<nobr>\\2</nobr>%2").arg (uuidFont).arg (endFont));

    /* split to paragraphs at \n chars */
    if (!aToolTip)
        text.replace ('\n', "</p><p>");
    else
        text.replace ('\n', "<br>");

    return text;
}

/* static */
QString VBoxGlobal::replaceHtmlEntities(QString strText)
{
    return strText
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('\"', "&quot;");
}

/**
 *  Reformats the input string @a aStr so that:
 *  - strings in single quotes will be put inside <nobr> and marked
 *    with bold style;
 *  - UUIDs be put inside <nobr> and marked
 *    with italic style;
 *  - replaces new line chars with </p><p> constructs to form paragraphs
 *    (note that <p> and </p> are not appended to the beginnign and to the
 *     end of the string respectively, to allow the result be appended
 *     or prepended to the existing paragraph).
 */
/* static */
QString VBoxGlobal::emphasize (const QString &aStr)
{
    QString strEmphStart ("<b>");
    QString strEmphEnd ("</b>");
    QString uuidEmphStart ("<i>");
    QString uuidEmphEnd ("</i>");

    QString text = aStr;

    /* replace special entities, '&' -- first! */
    text.replace ('&', "&amp;");
    text.replace ('<', "&lt;");
    text.replace ('>', "&gt;");
    text.replace ('\"', "&quot;");

    /* mark strings in single quotes with bold style */
    QRegExp rx = QRegExp ("((?:^|\\s)[(]?)'([^']*)'(?=[:.-!);]?(?:\\s|$))");
    rx.setMinimal (true);
    text.replace (rx,
        QString ("\\1%1<nobr>'\\2'</nobr>%2").arg (strEmphStart).arg (strEmphEnd));

    /* mark UUIDs with italic style */
    text.replace (QRegExp (
        "((?:^|\\s)[(]?)"
        "(\\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\})"
        "(?=[:.-!);]?(?:\\s|$))"),
        QString ("\\1%1<nobr>\\2</nobr>%2").arg (uuidEmphStart).arg (uuidEmphEnd));

    /* split to paragraphs at \n chars */
    text.replace ('\n', "</p><p>");

    return text;
}

/**
 *  This does exactly the same as QLocale::system().name() but corrects its
 *  wrong behavior on Linux systems (LC_NUMERIC for some strange reason takes
 *  precedence over any other locale setting in the QLocale::system()
 *  implementation). This implementation first looks at LC_ALL (as defined by
 *  SUS), then looks at LC_MESSAGES which is designed to define a language for
 *  program messages in case if it differs from the language for other locale
 *  categories. Then it looks for LANG and finally falls back to
 *  QLocale::system().name().
 *
 *  The order of precedence is well defined here:
 *  http://opengroup.org/onlinepubs/007908799/xbd/envvar.html
 *
 *  @note This method will return "C" when the requested locale is invalid or
 *  when the "C" locale is set explicitly.
 */
/* static */
QString VBoxGlobal::systemLanguageId()
{
#if defined (Q_WS_MAC)
    /* QLocale return the right id only if the user select the format of the
     * language also. So we use our own implementation */
    return ::darwinSystemLanguage();
#elif defined (Q_OS_UNIX)
    const char *s = RTEnvGet ("LC_ALL");
    if (s == 0)
        s = RTEnvGet ("LC_MESSAGES");
    if (s == 0)
        s = RTEnvGet ("LANG");
    if (s != 0)
        return QLocale (s).name();
#endif
    return  QLocale::system().name();
}

#if defined (Q_WS_X11)

static char *XXGetProperty (Display *aDpy, Window aWnd,
                            Atom aPropType, const char *aPropName)
{
    Atom propNameAtom = XInternAtom (aDpy, aPropName,
                                     True /* only_if_exists */);
    if (propNameAtom == None)
        return NULL;

    Atom actTypeAtom = None;
    int actFmt = 0;
    unsigned long nItems = 0;
    unsigned long nBytesAfter = 0;
    unsigned char *propVal = NULL;
    int rc = XGetWindowProperty (aDpy, aWnd, propNameAtom,
                                 0, LONG_MAX, False /* delete */,
                                 aPropType, &actTypeAtom, &actFmt,
                                 &nItems, &nBytesAfter, &propVal);
    if (rc != Success)
        return NULL;

    return reinterpret_cast <char *> (propVal);
}

static Bool XXSendClientMessage (Display *aDpy, Window aWnd, const char *aMsg,
                                 unsigned long aData0 = 0, unsigned long aData1 = 0,
                                 unsigned long aData2 = 0, unsigned long aData3 = 0,
                                 unsigned long aData4 = 0)
{
    Atom msgAtom = XInternAtom (aDpy, aMsg, True /* only_if_exists */);
    if (msgAtom == None)
        return False;

    XEvent ev;

    ev.xclient.type = ClientMessage;
    ev.xclient.serial = 0;
    ev.xclient.send_event = True;
    ev.xclient.display = aDpy;
    ev.xclient.window = aWnd;
    ev.xclient.message_type = msgAtom;

    /* always send as 32 bit for now */
    ev.xclient.format = 32;
    ev.xclient.data.l [0] = aData0;
    ev.xclient.data.l [1] = aData1;
    ev.xclient.data.l [2] = aData2;
    ev.xclient.data.l [3] = aData3;
    ev.xclient.data.l [4] = aData4;

    return XSendEvent (aDpy, DefaultRootWindow (aDpy), False,
                       SubstructureRedirectMask, &ev) != 0;
}

#endif

/**
 * Activates the specified window. If necessary, the window will be
 * de-iconified activation.
 *
 * @note On X11, it is implied that @a aWid represents a window of the same
 * display the application was started on.
 *
 * @param aWId              Window ID to activate.
 * @param aSwitchDesktop    @c true to switch to the window's desktop before
 *                          activation.
 *
 * @return @c true on success and @c false otherwise.
 */
/* static */
bool VBoxGlobal::activateWindow (WId aWId, bool aSwitchDesktop /* = true */)
{
    bool result = true;

#if defined (Q_WS_WIN32)

    if (IsIconic (aWId))
        result &= !!ShowWindow (aWId, SW_RESTORE);
    else if (!IsWindowVisible (aWId))
        result &= !!ShowWindow (aWId, SW_SHOW);

    result &= !!SetForegroundWindow (aWId);

#elif defined (Q_WS_X11)

    Display *dpy = QX11Info::display();

    if (aSwitchDesktop)
    {
        /* try to find the desktop ID using the NetWM property */
        CARD32 *desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
                                                    "_NET_WM_DESKTOP");
        if (desktop == NULL)
            /* if the NetWM propery is not supported try to find the desktop
             * ID using the GNOME WM property */
            desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
                                                "_WIN_WORKSPACE");

        if (desktop != NULL)
        {
            Bool ok = XXSendClientMessage (dpy, DefaultRootWindow (dpy),
                                           "_NET_CURRENT_DESKTOP",
                                           *desktop);
            if (!ok)
            {
                LogWarningFunc (("Couldn't switch to desktop=%08X\n",
                                 desktop));
                result = false;
            }
            XFree (desktop);
        }
        else
        {
            LogWarningFunc (("Couldn't find a desktop ID for aWId=%08X\n",
                             aWId));
            result = false;
        }
    }

    Bool ok = XXSendClientMessage (dpy, aWId, "_NET_ACTIVE_WINDOW");
    result &= !!ok;

    XRaiseWindow (dpy, aWId);

#else

    NOREF (aWId);
    NOREF (aSwitchDesktop);
    AssertFailed();
    result = false;

#endif

    if (!result)
        LogWarningFunc (("Couldn't activate aWId=%08X\n", aWId));

    return result;
}

/**
 *  Removes the acceletartor mark (the ampersand symbol) from the given string
 *  and returns the result. The string is supposed to be a menu item's text
 *  that may (or may not) contain the accelerator mark.
 *
 *  In order to support accelerators used in non-alphabet languages
 *  (e.g. Japanese) that has a form of "(&<L>)" (where <L> is a latin letter),
 *  this method first searches for this pattern and, if found, removes it as a
 *  whole. If such a pattern is not found, then the '&' character is simply
 *  removed from the string.
 *
 *  @note This function removes only the first occurense of the accelerator
 *  mark.
 *
 *  @param aText Menu item's text to remove the acceletaror mark from.
 *
 *  @return The resulting string.
 */
/* static */
QString VBoxGlobal::removeAccelMark (const QString &aText)
{
    QString result = aText;

    QRegExp accel ("\\(&[a-zA-Z]\\)");
    int pos = accel.indexIn (result);
    if (pos >= 0)
        result.remove (pos, accel.cap().length());
    else
    {
        pos = result.indexOf ('&');
        if (pos >= 0)
            result.remove (pos, 1);
    }

    return result;
}

/* static */
QString VBoxGlobal::insertKeyToActionText (const QString &aText, const QString &aKey)
{
#ifdef Q_WS_MAC
    QString key ("%1 (Host+%2)");
#else
    QString key ("%1 \tHost+%2");
#endif
    return key.arg (aText).arg (QKeySequence (aKey).toString (QKeySequence::NativeText));
}

/* static */
QString VBoxGlobal::extractKeyFromActionText (const QString &aText)
{
    QString key;
#ifdef Q_WS_MAC
    QRegExp re (".* \\(Host\\+(.+)\\)");
#else
    QRegExp re (".* \\t\\Host\\+(.+)");
#endif
    if (re.exactMatch (aText))
        key = re.cap (1);
    return key;
}

/**
 * Joins two pixmaps horizontally with 2px space between them and returns the
 * result.
 *
 * @param aPM1 Left pixmap.
 * @param aPM2 Right pixmap.
 */
/* static */
QPixmap VBoxGlobal::joinPixmaps (const QPixmap &aPM1, const QPixmap &aPM2)
{
    if (aPM1.isNull())
        return aPM2;
    if (aPM2.isNull())
        return aPM1;

    QPixmap result (aPM1.width() + aPM2.width() + 2,
                    qMax (aPM1.height(), aPM2.height()));
    result.fill (Qt::transparent);

    QPainter painter (&result);
    painter.drawPixmap (0, 0, aPM1);
    painter.drawPixmap (aPM1.width() + 2, result.height() - aPM2.height(), aPM2);
    painter.end();

    return result;
}

/**
 *  Searches for a widget that with @a aName (if it is not NULL) which inherits
 *  @a aClassName (if it is not NULL) and among children of @a aParent. If @a
 *  aParent is NULL, all top-level widgets are searched. If @a aRecursive is
 *  true, child widgets are recursively searched as well.
 */
/* static */
QWidget *VBoxGlobal::findWidget (QWidget *aParent, const char *aName,
                                 const char *aClassName /* = NULL */,
                                 bool aRecursive /* = false */)
{
    if (aParent == NULL)
    {
        QWidgetList list = QApplication::topLevelWidgets();
        foreach(QWidget *w, list)
        {
            if ((!aName || strcmp (w->objectName().toAscii().constData(), aName) == 0) &&
                (!aClassName || strcmp (w->metaObject()->className(), aClassName) == 0))
                return w;
            if (aRecursive)
            {
                w = findWidget (w, aName, aClassName, aRecursive);
                if (w)
                    return w;
            }
        }
        return NULL;
    }

    /* Find the first children of aParent with the appropriate properties.
     * Please note that this call is recursivly. */
    QList<QWidget *> list = qFindChildren<QWidget *> (aParent, aName);
    foreach(QWidget *child, list)
    {
        if (!aClassName || strcmp (child->metaObject()->className(), aClassName) == 0)
            return child;
    }
    return NULL;
}

/**
 * Figures out which hard disk formats are currently supported by VirtualBox.
 * Returned is a list of pairs with the form
 *   <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
 */
/* static */
QList <QPair <QString, QString> > VBoxGlobal::HDDBackends()
{
    CSystemProperties systemProperties = vboxGlobal().virtualBox().GetSystemProperties();
    QVector<CMediumFormat> mediumFormats = systemProperties.GetMediumFormats();
    QList< QPair<QString, QString> > backendPropList;
    for (int i = 0; i < mediumFormats.size(); ++ i)
    {
        /* File extensions */
        QVector <QString> fileExtensions = mediumFormats [i].GetFileExtensions();
        QStringList f;
        for (int a = 0; a < fileExtensions.size(); ++ a)
            f << QString ("*.%1").arg (fileExtensions [a]);
        /* Create a pair out of the backend description and all suffix's. */
        if (!f.isEmpty())
            backendPropList << QPair<QString, QString> (mediumFormats [i].GetName(), f.join(" "));
    }
    return backendPropList;
}

/* static */
QString VBoxGlobal::documentsPath()
{
    QString path;
#if QT_VERSION < 0x040400
    path = QDir::homePath();
#else
    path = QDesktopServices::storageLocation (QDesktopServices::DocumentsLocation);
#endif

    /* Make sure the path exists */
    QDir dir (path);
    if (dir.exists())
        return QDir::cleanPath (dir.canonicalPath());
    else
    {
        dir.setPath (QDir::homePath() + "/Documents");
        if (dir.exists())
            return QDir::cleanPath (dir.canonicalPath());
        else
            return QDir::homePath();
    }
}

#ifdef VBOX_WITH_VIDEOHWACCEL
/* static */
bool VBoxGlobal::isAcceleration2DVideoAvailable()
{
    return VBoxQGLOverlay::isAcceleration2DVideoAvailable();
}

/** additional video memory required for the best 2D support performance
 *  total amount of VRAM required is thus calculated as requiredVideoMemory + required2DOffscreenVideoMemory  */
/* static */
quint64 VBoxGlobal::required2DOffscreenVideoMemory()
{
    return VBoxQGLOverlay::required2DOffscreenVideoMemory();
}

#endif

// Public slots
////////////////////////////////////////////////////////////////////////////////

/**
 * Opens the specified URL using OS/Desktop capabilities.
 *
 * @param aURL URL to open
 *
 * @return true on success and false otherwise
 */
bool VBoxGlobal::openURL (const QString &aURL)
{
    /* Service event */
    class ServiceEvent : public QEvent
    {
        public:

            ServiceEvent (bool aResult) : QEvent (QEvent::User), mResult (aResult) {}

            bool result() const { return mResult; }

        private:

            bool mResult;
    };

    /* Service-Client object */
    class ServiceClient : public QEventLoop
    {
        public:

            ServiceClient() : mResult (false) {}

            bool result() const { return mResult; }

        private:

            bool event (QEvent *aEvent)
            {
                if (aEvent->type() == QEvent::User)
                {
                    ServiceEvent *pEvent = static_cast <ServiceEvent*> (aEvent);
                    mResult = pEvent->result();
                    pEvent->accept();
                    quit();
                    return true;
                }
                return false;
            }

            bool mResult;
    };

    /* Service-Server object */
    class ServiceServer : public QThread
    {
        public:

            ServiceServer (ServiceClient &aClient, const QString &sURL)
                : mClient (aClient), mURL (sURL) {}

        private:

            void run()
            {
                QApplication::postEvent (&mClient, new ServiceEvent (QDesktopServices::openUrl (mURL)));
            }

            ServiceClient &mClient;
            const QString &mURL;
    };

    ServiceClient client;
    ServiceServer server (client, aURL);
    server.start();
    client.exec();
    server.wait();

    bool result = client.result();

    if (!result)
        vboxProblem().cannotOpenURL (aURL);

    return result;
}

/**
 * Shows the VirtualBox registration dialog.
 *
 * @note that this method is not part of VBoxProblemReporter (like e.g.
 *       VBoxProblemReporter::showHelpAboutDialog()) because it is tied to
 *       VBoxCallback::OnExtraDataChange() handling performed by VBoxGlobal.
 *
 * @param aForce
 */
void VBoxGlobal::showRegistrationDialog (bool aForce)
{
    NOREF(aForce);
#ifdef VBOX_WITH_REGISTRATION
    if (!aForce && !UIRegistrationWzd::hasToBeShown())
        return;

    if (mRegDlg)
    {
        /* Show the already opened registration dialog */
        mRegDlg->setWindowState (mRegDlg->windowState() & ~Qt::WindowMinimized);
        mRegDlg->raise();
        mRegDlg->activateWindow();
    }
    else
    {
        /* Store the ID of the main window to ensure that only one
         * registration dialog is shown at a time. Due to manipulations with
         * OnExtraDataCanChange() and OnExtraDataChange() signals, this extra
         * data item acts like an inter-process mutex, so the first process
         * that attempts to set it will win, the rest will get a failure from
         * the SetExtraData() call. */
        mVBox.SetExtraData (VBoxDefs::GUI_RegistrationDlgWinID,
                            QString ("%1").arg ((qulonglong) mMainWindow->winId()));

        if (mVBox.isOk())
        {
            /* We've got the "mutex", create a new registration dialog */
            UIRegistrationWzd *dlg = new UIRegistrationWzd (&mRegDlg);
            dlg->setAttribute (Qt::WA_DeleteOnClose);
            Assert (dlg == mRegDlg);
            mRegDlg->show();
        }
    }
#endif
}

/**
 * Shows the VirtualBox version check & update dialog.
 *
 * @note that this method is not part of VBoxProblemReporter (like e.g.
 *       VBoxProblemReporter::showHelpAboutDialog()) because it is tied to
 *       VBoxCallback::OnExtraDataChange() handling performed by VBoxGlobal.
 *
 * @param aForce
 */
void VBoxGlobal::showUpdateDialog (bool aForce)
{
    /* Silently check in one day after current time-stamp */
    QTimer::singleShot (24 /* hours */   * 60   /* minutes */ *
                        60 /* seconds */ * 1000 /* milliseconds */,
                        this, SLOT (perDayNewVersionNotifier()));

    bool isNecessary = VBoxUpdateDlg::isNecessary();

    if (!aForce && !isNecessary)
        return;

    if (mUpdDlg)
    {
        if (!mUpdDlg->isHidden())
        {
            mUpdDlg->setWindowState (mUpdDlg->windowState() & ~Qt::WindowMinimized);
            mUpdDlg->raise();
            mUpdDlg->activateWindow();
        }
    }
    else
    {
        /* Store the ID of the main window to ensure that only one
         * update dialog is shown at a time. Due to manipulations with
         * OnExtraDataCanChange() and OnExtraDataChange() signals, this extra
         * data item acts like an inter-process mutex, so the first process
         * that attempts to set it will win, the rest will get a failure from
         * the SetExtraData() call. */
        mVBox.SetExtraData (VBoxDefs::GUI_UpdateDlgWinID,
                            QString ("%1").arg ((qulonglong) mMainWindow->winId()));

        if (mVBox.isOk())
        {
            /* We've got the "mutex", create a new update dialog */
            VBoxUpdateDlg *dlg = new VBoxUpdateDlg (&mUpdDlg, aForce, 0);
            dlg->setAttribute (Qt::WA_DeleteOnClose);
            Assert (dlg == mUpdDlg);

            /* Update dialog always in background mode for now.
             * if (!aForce && isAutomatic) */
            mUpdDlg->search();
            /* else mUpdDlg->show(); */
        }
    }
}

void VBoxGlobal::perDayNewVersionNotifier()
{
    showUpdateDialog (false /* force show? */);
}

// Protected members
////////////////////////////////////////////////////////////////////////////////

bool VBoxGlobal::event (QEvent *e)
{
    switch (e->type())
    {
        case VBoxDefs::AsyncEventType:
        {
            VBoxAsyncEvent *ev = (VBoxAsyncEvent *) e;
            ev->handle();
            return true;
        }

        case VBoxDefs::MediaEnumEventType:
        {
            VBoxMediaEnumEvent *ev = (VBoxMediaEnumEvent*) e;

            if (!ev->mLast)
            {
                if (ev->mMedium.state() == KMediumState_Inaccessible &&
                    !ev->mMedium.result().isOk())
                    vboxProblem().cannotGetMediaAccessibility (ev->mMedium);
                Assert (ev->mIterator != mMediaList.end());
                *(ev->mIterator) = ev->mMedium;
                emit mediumEnumerated (*ev->mIterator);
                ++ ev->mIterator;
            }
            else
            {
                /* the thread has posted the last message, wait for termination */
                mMediaEnumThread->wait();
                delete mMediaEnumThread;
                mMediaEnumThread = 0;
                emit mediumEnumFinished (mMediaList);
            }

            return true;
        }

        /* VirtualBox callback events */

        case VBoxDefs::MachineStateChangeEventType:
        {
            emit machineStateChanged (*(VBoxMachineStateChangeEvent *) e);
            return true;
        }
        case VBoxDefs::MachineDataChangeEventType:
        {
            emit machineDataChanged (*(VBoxMachineDataChangeEvent *) e);
            return true;
        }
        case VBoxDefs::MachineRegisteredEventType:
        {
            emit machineRegistered (*(VBoxMachineRegisteredEvent *) e);
            return true;
        }
        case VBoxDefs::SessionStateChangeEventType:
        {
            emit sessionStateChanged (*(VBoxSessionStateChangeEvent *) e);
            return true;
        }
        case VBoxDefs::SnapshotEventType:
        {
            emit snapshotChanged (*(VBoxSnapshotEvent *) e);
            return true;
        }
        case VBoxDefs::CanShowRegDlgEventType:
        {
            emit canShowRegDlg (((VBoxCanShowRegDlgEvent *) e)->mCanShow);
            return true;
        }
        case VBoxDefs::CanShowUpdDlgEventType:
        {
            emit canShowUpdDlg (((VBoxCanShowUpdDlgEvent *) e)->mCanShow);
            return true;
        }
        case VBoxDefs::ChangeGUILanguageEventType:
        {
            loadLanguage (static_cast<VBoxChangeGUILanguageEvent*> (e)->mLangId);
            return true;
        }
#ifdef VBOX_GUI_WITH_SYSTRAY
        case VBoxDefs::MainWindowCountChangeEventType:

            emit mainWindowCountChanged (*(VBoxMainWindowCountChangeEvent *) e);
            return true;

        case VBoxDefs::CanShowTrayIconEventType:
        {
            emit trayIconCanShow (*(VBoxCanShowTrayIconEvent *) e);
            return true;
        }
        case VBoxDefs::ShowTrayIconEventType:
        {
            emit trayIconShow (*(VBoxShowTrayIconEvent *) e);
            return true;
        }
        case VBoxDefs::TrayIconChangeEventType:
        {
            emit trayIconChanged (*(VBoxChangeTrayIconEvent *) e);
            return true;
        }
#endif
#if defined(Q_WS_MAC)
        case VBoxDefs::ChangeDockIconUpdateEventType:
        {
            emit dockIconUpdateChanged (*(VBoxChangeDockIconUpdateEvent *) e);
            return true;
        }
        case VBoxDefs::ChangePresentationmodeEventType:
        {
            emit presentationModeChanged (*(VBoxChangePresentationModeEvent *) e);
            return true;
        }
#endif
        default:
            break;
    }

    return QObject::event (e);
}

bool VBoxGlobal::eventFilter (QObject *aObject, QEvent *aEvent)
{
    if (aEvent->type() == QEvent::LanguageChange &&
        aObject->isWidgetType() &&
        static_cast <QWidget *> (aObject)->isTopLevel())
    {
        /* Catch the language change event before any other widget gets it in
         * order to invalidate cached string resources (like the details view
         * templates) that may be used by other widgets. */
        QWidgetList list = QApplication::topLevelWidgets();
        if (list.first() == aObject)
        {
            /* call this only once per every language change (see
             * QApplication::installTranslator() for details) */
            retranslateUi();
        }
    }

    return QObject::eventFilter (aObject, aEvent);
}

// Private members
////////////////////////////////////////////////////////////////////////////////

void VBoxGlobal::init()
{
#ifdef DEBUG
    mVerString += " [DEBUG]";
#endif

#ifdef Q_WS_WIN
    /* COM for the main thread is initialized in main() */
#else
    HRESULT rc = COMBase::InitializeCOM();
    if (FAILED (rc))
    {
        vboxProblem().cannotInitCOM (rc);
        return;
    }
#endif

    mVBox.createInstance (CLSID_VirtualBox);
    if (!mVBox.isOk())
    {
        vboxProblem().cannotCreateVirtualBox (mVBox);
        return;
    }

    /* create default non-null global settings */
    gset = VBoxGlobalSettings (false);

    /* try to load global settings */
    gset.load (mVBox);
    if (!mVBox.isOk() || !gset)
    {
        vboxProblem().cannotLoadGlobalConfig (mVBox, gset.lastError());
        return;
    }

    /* Load the customized language as early as possible to get possible error
     * messages translated */
    QString sLanguageId = gset.languageId();
    if (!sLanguageId.isNull())
        loadLanguage (sLanguageId);

    retranslateUi();

#ifdef VBOX_GUI_WITH_SYSTRAY
    {
        /* Increase open Fe/Qt4 windows reference count. */
        int c = mVBox.GetExtraData (VBoxDefs::GUI_MainWindowCount).toInt() + 1;
        AssertMsgReturnVoid ((c >= 0) || (mVBox.isOk()),
            ("Something went wrong with the window reference count!"));
        mVBox.SetExtraData (VBoxDefs::GUI_MainWindowCount, QString ("%1").arg (c));
        mIncreasedWindowCounter = mVBox.isOk();
        AssertReturnVoid (mIncreasedWindowCounter);
    }
#endif

    /* Initialize guest OS Type list. */
    CGuestOSTypeVector coll = mVBox.GetGuestOSTypes();
    int osTypeCount = coll.size();
    AssertMsg (osTypeCount > 0, ("Number of OS types must not be zero"));
    if (osTypeCount > 0)
    {
        /* Here we assume the 'Other' type is always the first, so we
         * remember it and will append it to the list when finished. */
        CGuestOSType otherType = coll[0];
        QString otherFamilyId (otherType.GetFamilyId());

        /* Fill the lists with all the available OS Types except
         * the 'Other' type, which will be appended. */
        for (int i = 1; i < coll.size(); ++i)
        {
            CGuestOSType os = coll[i];
            QString familyId (os.GetFamilyId());
            if (!mFamilyIDs.contains (familyId))
            {
                mFamilyIDs << familyId;
                mTypes << QList <CGuestOSType> ();
            }
            mTypes [mFamilyIDs.indexOf (familyId)].append (os);
        }

        /* Append the 'Other' OS Type to the end of list. */
        if (!mFamilyIDs.contains (otherFamilyId))
        {
            mFamilyIDs << otherFamilyId;
            mTypes << QList <CGuestOSType> ();
        }
        mTypes [mFamilyIDs.indexOf (otherFamilyId)].append (otherType);
    }

    /* Fill in OS type icon dictionary. */
    static const char *kOSTypeIcons [][2] =
    {
        {"Other",           ":/os_other.png"},
        {"DOS",             ":/os_dos.png"},
        {"Netware",         ":/os_netware.png"},
        {"L4",              ":/os_l4.png"},
        {"Windows31",       ":/os_win31.png"},
        {"Windows95",       ":/os_win95.png"},
        {"Windows98",       ":/os_win98.png"},
        {"WindowsMe",       ":/os_winme.png"},
        {"WindowsNT4",      ":/os_winnt4.png"},
        {"Windows2000",     ":/os_win2k.png"},
        {"WindowsXP",       ":/os_winxp.png"},
        {"WindowsXP_64",    ":/os_winxp_64.png"},
        {"Windows2003",     ":/os_win2k3.png"},
        {"Windows2003_64",  ":/os_win2k3_64.png"},
        {"WindowsVista",    ":/os_winvista.png"},
        {"WindowsVista_64", ":/os_winvista_64.png"},
        {"Windows2008",     ":/os_win2k8.png"},
        {"Windows2008_64",  ":/os_win2k8_64.png"},
        {"Windows7",        ":/os_win7.png"},
        {"Windows7_64",     ":/os_win7_64.png"},
        {"WindowsNT",       ":/os_win_other.png"},
        {"OS2Warp3",        ":/os_os2warp3.png"},
        {"OS2Warp4",        ":/os_os2warp4.png"},
        {"OS2Warp45",       ":/os_os2warp45.png"},
        {"OS2eCS",          ":/os_os2ecs.png"},
        {"OS2",             ":/os_os2_other.png"},
        {"Linux22",         ":/os_linux22.png"},
        {"Linux24",         ":/os_linux24.png"},
        {"Linux24_64",      ":/os_linux24_64.png"},
        {"Linux26",         ":/os_linux26.png"},
        {"Linux26_64",      ":/os_linux26_64.png"},
        {"ArchLinux",       ":/os_archlinux.png"},
        {"ArchLinux_64",    ":/os_archlinux_64.png"},
        {"Debian",          ":/os_debian.png"},
        {"Debian_64",       ":/os_debian_64.png"},
        {"OpenSUSE",        ":/os_opensuse.png"},
        {"OpenSUSE_64",     ":/os_opensuse_64.png"},
        {"Fedora",          ":/os_fedora.png"},
        {"Fedora_64",       ":/os_fedora_64.png"},
        {"Gentoo",          ":/os_gentoo.png"},
        {"Gentoo_64",       ":/os_gentoo_64.png"},
        {"Mandriva",        ":/os_mandriva.png"},
        {"Mandriva_64",     ":/os_mandriva_64.png"},
        {"RedHat",          ":/os_redhat.png"},
        {"RedHat_64",       ":/os_redhat_64.png"},
        {"Turbolinux",      ":/os_turbolinux.png"},
        {"Turbolinux_64",   ":/os_turbolinux_64.png"},
        {"Ubuntu",          ":/os_ubuntu.png"},
        {"Ubuntu_64",       ":/os_ubuntu_64.png"},
        {"Xandros",         ":/os_xandros.png"},
        {"Xandros_64",      ":/os_xandros_64.png"},
        {"Oracle",          ":/os_oracle.png"},
        {"Oracle_64",       ":/os_oracle_64.png"},
        {"Linux",           ":/os_linux_other.png"},
        {"FreeBSD",         ":/os_freebsd.png"},
        {"FreeBSD_64",      ":/os_freebsd_64.png"},
        {"OpenBSD",         ":/os_openbsd.png"},
        {"OpenBSD_64",      ":/os_openbsd_64.png"},
        {"NetBSD",          ":/os_netbsd.png"},
        {"NetBSD_64",       ":/os_netbsd_64.png"},
        {"Solaris",         ":/os_solaris.png"},
        {"Solaris_64",      ":/os_solaris_64.png"},
        {"OpenSolaris",     ":/os_opensolaris.png"},
        {"OpenSolaris_64",  ":/os_opensolaris_64.png"},
        {"QNX",             ":/os_qnx.png"},
        {"MacOS",           ":/os_macosx.png"},
        {"MacOS_64",        ":/os_macosx_64.png"},
    };
    for (uint n = 0; n < SIZEOF_ARRAY (kOSTypeIcons); ++ n)
    {
        mOsTypeIcons.insert (kOSTypeIcons [n][0],
            new QPixmap (kOSTypeIcons [n][1]));
    }

    /* fill in VM state icon map */
    static const struct
    {
        KMachineState state;
        const char *name;
    }
    kVMStateIcons[] =
    {
        {KMachineState_Null, NULL},
        {KMachineState_PoweredOff, ":/state_powered_off_16px.png"},
        {KMachineState_Saved, ":/state_saved_16px.png"},
        {KMachineState_Aborted, ":/state_aborted_16px.png"},
        {KMachineState_Teleported, ":/state_saved_16px.png"},           /** @todo Live Migration: New icon? (not really important) */
        {KMachineState_Running, ":/state_running_16px.png"},
        {KMachineState_Paused, ":/state_paused_16px.png"},
        {KMachineState_Teleporting, ":/state_running_16px.png"},        /** @todo Live Migration: New icon? (not really important) */
        {KMachineState_LiveSnapshotting, ":/state_running_16px.png"},   /** @todo Live Migration: New icon? (not really important) */
        {KMachineState_Stuck, ":/state_stuck_16px.png"},
        {KMachineState_Starting, ":/state_running_16px.png"}, /// @todo (dmik) separate icon?
        {KMachineState_Stopping, ":/state_running_16px.png"}, /// @todo (dmik) separate icon?
        {KMachineState_Saving, ":/state_saving_16px.png"},
        {KMachineState_Restoring, ":/state_restoring_16px.png"},
        {KMachineState_TeleportingPausedVM, ":/state_saving_16px.png"}, /** @todo Live Migration: New icon? (not really important) */
        {KMachineState_TeleportingIn, ":/state_restoring_16px.png"},    /** @todo Live Migration: New icon? (not really important) */
        {KMachineState_RestoringSnapshot, ":/state_discarding_16px.png"},
        {KMachineState_DeletingSnapshot, ":/state_discarding_16px.png"},
        {KMachineState_DeletingSnapshotOnline, ":/state_discarding_16px.png"},  /// @todo live snapshot deletion: new icon?
        {KMachineState_DeletingSnapshotPaused, ":/state_discarding_16px.png"},  /// @todo live snapshot deletion: new icon?
        {KMachineState_SettingUp, ":/settings_16px.png"},
    };
    for (uint n = 0; n < SIZEOF_ARRAY (kVMStateIcons); n ++)
    {
        mVMStateIcons.insert (kVMStateIcons [n].state,
            new QPixmap (kVMStateIcons [n].name));
    }

    /* initialize state colors map */
    mVMStateColors.insert (KMachineState_Null,          new QColor (Qt::red));
    mVMStateColors.insert (KMachineState_PoweredOff,    new QColor (Qt::gray));
    mVMStateColors.insert (KMachineState_Saved,         new QColor (Qt::yellow));
    mVMStateColors.insert (KMachineState_Aborted,       new QColor (Qt::darkRed));
    mVMStateColors.insert (KMachineState_Teleported,    new QColor (Qt::red));
    mVMStateColors.insert (KMachineState_Running,       new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_Paused,        new QColor (Qt::darkGreen));
    mVMStateColors.insert (KMachineState_Stuck,         new QColor (Qt::darkMagenta));
    mVMStateColors.insert (KMachineState_Teleporting,   new QColor (Qt::blue));
    mVMStateColors.insert (KMachineState_LiveSnapshotting, new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_Starting,      new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_Stopping,      new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_Saving,        new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_Restoring,     new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_TeleportingPausedVM, new QColor (Qt::blue));
    mVMStateColors.insert (KMachineState_TeleportingIn, new QColor (Qt::blue));
    mVMStateColors.insert (KMachineState_RestoringSnapshot, new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_DeletingSnapshot, new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_DeletingSnapshotOnline, new QColor (Qt::green));
    mVMStateColors.insert (KMachineState_DeletingSnapshotPaused, new QColor (Qt::darkGreen));
    mVMStateColors.insert (KMachineState_SettingUp,     new QColor (Qt::green));

    /* online/offline snapshot icons */
    mOfflineSnapshotIcon = QPixmap (":/offline_snapshot_16px.png");
    mOnlineSnapshotIcon = QPixmap (":/online_snapshot_16px.png");

    qApp->installEventFilter (this);

    /* process command line */

    bool bForceSeamless = false;
    bool bForceFullscreen = false;

    vm_render_mode_str = RTStrDup (virtualBox()
            .GetExtraData (VBoxDefs::GUI_RenderMode).toAscii().constData());

#ifdef Q_WS_X11
    mIsKWinManaged = X11IsWindowManagerKWin();
#endif

#ifdef VBOX_WITH_DEBUGGER_GUI
# ifdef VBOX_WITH_DEBUGGER_GUI_MENU
    mDbgEnabled = true;
# else
    mDbgEnabled = RTEnvExist("VBOX_GUI_DBG_ENABLED");
# endif
    mDbgAutoShow = mDbgAutoShowCommandLine = mDbgAutoShowStatistics
        = RTEnvExist("VBOX_GUI_DBG_AUTO_SHOW");
    mStartPaused = false;
#endif

    mShowStartVMErrors = true;
    bool startVM = false;
    QString vmNameOrUuid;

    int argc = qApp->argc();
    int i = 1;
    while (i < argc)
    {
        const char *arg = qApp->argv() [i];
        /* NOTE: the check here must match the corresponding check for the
         * options to start a VM in main.cpp and hardenedmain.cpp exactly,
         * otherwise there will be weird error messages. */
        if (   !::strcmp (arg, "--startvm")
            || !::strcmp (arg, "-startvm"))
        {
            if (++i < argc)
            {
                vmNameOrUuid = QString (qApp->argv() [i]);
                startVM = true;
            }
        }
        else if (!::strcmp(arg, "-seamless") || !::strcmp(arg, "--seamless"))
        {
            bForceSeamless = true;
        }
        else if (!::strcmp(arg, "-fullscreen") || !::strcmp(arg, "--fullscreen"))
        {
            bForceFullscreen = true;
        }
#ifdef VBOX_GUI_WITH_SYSTRAY
        else if (!::strcmp (arg, "-systray") || !::strcmp (arg, "--systray"))
        {
            mIsTrayMenu = true;
        }
#endif
        else if (!::strcmp (arg, "-comment") || !::strcmp (arg, "--comment"))
        {
            ++i;
        }
        else if (!::strcmp (arg, "-rmode") || !::strcmp (arg, "--rmode"))
        {
            if (++i < argc)
                vm_render_mode_str = qApp->argv() [i];
        }
        else if (!::strcmp (arg, "--no-startvm-errormsgbox"))
        {
            mShowStartVMErrors = false;
        }
#ifdef VBOX_WITH_DEBUGGER_GUI
        else if (!::strcmp (arg, "-dbg") || !::strcmp (arg, "--dbg"))
        {
            mDbgEnabled = true;
        }
        else if (!::strcmp( arg, "-debug") || !::strcmp (arg, "--debug"))
        {
            mDbgEnabled = true;
            mDbgAutoShow = mDbgAutoShowCommandLine = mDbgAutoShowStatistics = true;
            mStartPaused = true;
        }
        else if (!::strcmp (arg, "--debug-command-line"))
        {
            mDbgEnabled = true;
            mDbgAutoShow = mDbgAutoShowCommandLine = true;
            mStartPaused = true;
        }
        else if (!::strcmp (arg, "--debug-statistics"))
        {
            mDbgEnabled = true;
            mDbgAutoShow = mDbgAutoShowStatistics = true;
            mStartPaused = true;
        }
        else if (!::strcmp (arg, "-no-debug") || !::strcmp (arg, "--no-debug"))
        {
            mDbgEnabled = false;
            mDbgAutoShow = false;
            mDbgAutoShowCommandLine = false;
            mDbgAutoShowStatistics = false;
        }
        /* Not quite debug options, but they're only useful with the debugger bits. */
        else if (!::strcmp (arg, "--start-paused"))
        {
            mStartPaused = true;
        }
        else if (!::strcmp (arg, "--start-running"))
        {
            mStartPaused = false;
        }
#endif
        /** @todo add an else { msgbox(syntax error); exit(1); } here, pretty please... */
        i++;
    }

    if (startVM)
    {
        QUuid uuid = QUuid(vmNameOrUuid);
        if (!uuid.isNull())
        {
            vmUuid = vmNameOrUuid;
        }
        else
        {
            CMachine m = mVBox.FindMachine (vmNameOrUuid);
            if (m.isNull())
            {
                if (showStartVMErrors())
                    vboxProblem().cannotFindMachineByName (mVBox, vmNameOrUuid);
                return;
            }
            vmUuid = m.GetId();
        }
    }

    if (bForceSeamless && !vmUuid.isEmpty())
    {
        mVBox.GetMachine(vmUuid).SetExtraData(VBoxDefs::GUI_Seamless, "on");
    }
    else if (bForceFullscreen && !vmUuid.isEmpty())
    {
        mVBox.GetMachine(vmUuid).SetExtraData(VBoxDefs::GUI_Fullscreen, "on");
    }

    vm_render_mode = vboxGetRenderMode (vm_render_mode_str);

    /* setup the callback */
    callback = CVirtualBoxCallback (new VBoxCallback (*this));
    mVBox.RegisterCallback (callback);
    AssertWrapperOk (mVBox);
    if (!mVBox.isOk())
        return;

#ifdef VBOX_WITH_DEBUGGER_GUI
    /* setup the debugger gui. */
    if (RTEnvExist("VBOX_GUI_NO_DEBUGGER"))
        mDbgEnabled = mDbgAutoShow =  mDbgAutoShowCommandLine = mDbgAutoShowStatistics = false;
    if (mDbgEnabled)
    {
        int vrc = SUPR3HardenedLdrLoadAppPriv("VBoxDbg", &mhVBoxDbg);
        if (RT_FAILURE(vrc))
        {
            mhVBoxDbg = NIL_RTLDRMOD;
            mDbgAutoShow =  mDbgAutoShowCommandLine = mDbgAutoShowStatistics = false;
            LogRel(("Failed to load VBoxDbg, rc=%Rrc\n", vrc));
        }
    }
#endif

    mValid = true;
}

/** @internal
 *
 *  This method should be never called directly. It is called automatically
 *  when the application terminates.
 */
void VBoxGlobal::cleanup()
{
    /* sanity check */
    if (!sVBoxGlobalInCleanup)
    {
        AssertMsgFailed (("Should never be called directly\n"));
        return;
    }

#ifdef VBOX_GUI_WITH_SYSTRAY
    if (mIncreasedWindowCounter)
    {
        /* Decrease open Fe/Qt4 windows reference count. */
        int c = mVBox.GetExtraData (VBoxDefs::GUI_MainWindowCount).toInt() - 1;
        AssertMsg ((c >= 0) || (mVBox.isOk()),
            ("Something went wrong with the window reference count!"));
        if (c < 0)
            c = 0;   /* Clean up the mess. */
        mVBox.SetExtraData (VBoxDefs::GUI_MainWindowCount,
                            (c > 0) ? QString ("%1").arg (c) : NULL);
        AssertWrapperOk (mVBox);
        if (c == 0)
        {
            mVBox.SetExtraData (VBoxDefs::GUI_TrayIconWinID, NULL);
            AssertWrapperOk (mVBox);
        }
    }
#endif

    if (!callback.isNull())
    {
        mVBox.UnregisterCallback (callback);
        AssertWrapperOk (mVBox);
        callback.detach();
    }

    if (mMediaEnumThread)
    {
        /* sVBoxGlobalInCleanup is true here, so just wait for the thread */
        mMediaEnumThread->wait();
        delete mMediaEnumThread;
        mMediaEnumThread = 0;
    }

#ifdef VBOX_WITH_REGISTRATION
    if (mRegDlg)
        mRegDlg->close();
#endif

    if (mConsoleWnd)
        delete mConsoleWnd;
    if (mSelectorWnd)
        delete mSelectorWnd;
#ifdef VBOX_WITH_NEW_RUNTIME_CORE
    if (m_pVirtualMachine)
        delete m_pVirtualMachine;
#endif

    /* ensure CGuestOSType objects are no longer used */
    mFamilyIDs.clear();
    mTypes.clear();

    /* media list contains a lot of CUUnknown, release them */
    mMediaList.clear();
    /* the last step to ensure we don't use COM any more */
    mVBox.detach();

    /* There may be VBoxMediaEnumEvent instances still in the message
     * queue which reference COM objects. Remove them to release those objects
     * before uninitializing the COM subsystem. */
    QApplication::removePostedEvents (this);

#ifdef Q_WS_WIN
    /* COM for the main thread is shutdown in main() */
#else
    COMBase::CleanupCOM();
#endif

    mValid = false;
}

/** @fn vboxGlobal
 *
 *  Shortcut to the static VBoxGlobal::instance() method, for convenience.
 */


/**
 *  USB Popup Menu class methods
 *  This class provides the list of USB devices attached to the host.
 */
VBoxUSBMenu::VBoxUSBMenu (QWidget *aParent) : QMenu (aParent)
{
    connect (this, SIGNAL (aboutToShow()),
             this, SLOT   (processAboutToShow()));
//    connect (this, SIGNAL (hovered (QAction *)),
//             this, SLOT   (processHighlighted (QAction *)));
}

const CUSBDevice& VBoxUSBMenu::getUSB (QAction *aAction)
{
    return mUSBDevicesMap [aAction];
}

void VBoxUSBMenu::setConsole (const CConsole &aConsole)
{
    mConsole = aConsole;
}

void VBoxUSBMenu::processAboutToShow()
{
    clear();
    mUSBDevicesMap.clear();

    CHost host = vboxGlobal().virtualBox().GetHost();

    bool isUSBEmpty = host.GetUSBDevices().size() == 0;
    if (isUSBEmpty)
    {
        QAction *action = addAction (tr ("<no devices available>", "USB devices"));
        action->setEnabled (false);
        action->setToolTip (tr ("No supported devices connected to the host PC",
                                "USB device tooltip"));
    }
    else
    {
        CHostUSBDeviceVector devvec = host.GetUSBDevices();
        for (int i = 0; i < devvec.size(); ++i)
        {
            CHostUSBDevice dev = devvec[i];
            CUSBDevice usb (dev);
            QAction *action = addAction (vboxGlobal().details (usb));
            action->setCheckable (true);
            mUSBDevicesMap [action] = usb;
            /* check if created item was alread attached to this session */
            if (!mConsole.isNull())
            {
                CUSBDevice attachedUSB =
                    mConsole.FindUSBDeviceById (usb.GetId());
                action->setChecked (!attachedUSB.isNull());
                action->setEnabled (dev.GetState() !=
                                    KUSBDeviceState_Unavailable);
            }
        }
    }
}

bool VBoxUSBMenu::event(QEvent *aEvent)
{
    /* We provide dynamic tooltips for the usb devices */
    if (aEvent->type() == QEvent::ToolTip)
    {
        QHelpEvent *helpEvent = static_cast<QHelpEvent *> (aEvent);
        QAction *action = actionAt (helpEvent->pos());
        if (action)
        {
            CUSBDevice usb = mUSBDevicesMap [action];
            if (!usb.isNull())
            {
                QToolTip::showText (helpEvent->globalPos(), vboxGlobal().toolTip (usb));
                return true;
            }
        }
    }
    return QMenu::event (aEvent);
}

/**
 *  Enable/Disable Menu class.
 *  This class provides enable/disable menu items.
 */
VBoxSwitchMenu::VBoxSwitchMenu (QWidget *aParent, QAction *aAction,
                                bool aInverted)
    : QMenu (aParent), mAction (aAction), mInverted (aInverted)
{
    /* this menu works only with toggle action */
    Assert (aAction->isCheckable());
    addAction(aAction);
    connect (this, SIGNAL (aboutToShow()),
             this, SLOT   (processAboutToShow()));
}

void VBoxSwitchMenu::setToolTip (const QString &aTip)
{
    mAction->setToolTip (aTip);
}

void VBoxSwitchMenu::processAboutToShow()
{
    QString text = mAction->isChecked() ^ mInverted ? tr ("Disable") : tr ("Enable");
    mAction->setText (text);
}