summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VirtualBox/src/platform/darwin/DarwinKeyboard.cpp
blob: 7e5d689b9a5bba5618ab8447bc233b6e20c2f7db (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
/* $Id$ */
/** @file
 * VBox Qt GUI - Declarations of utility functions for handling Darwin Keyboard specific tasks.
 */

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

/* Defines: */
#define LOG_GROUP LOG_GROUP_GUI
#define VBOX_WITH_KBD_LEDS_SYNC
//#define VBOX_WITHOUT_KBD_LEDS_SYNC_FILTERING

/* GUI includes: */
#include "DarwinKeyboard.h"
#ifndef USE_HID_FOR_MODIFIERS
# include "CocoaEventHelper.h"
#endif

/* Other VBox includes: */
#include <iprt/assert.h>
#include <iprt/asm.h>
#include <iprt/mem.h>
#include <iprt/time.h>
#include <VBox/log.h>
#ifdef DEBUG_PRINTF
# include <iprt/stream.h>
#endif
#ifdef VBOX_WITH_KBD_LEDS_SYNC
# include <iprt/errcore.h>
# include <iprt/semaphore.h>
# include <VBox/sup.h>
#endif

/* External includes: */
#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/usb/USB.h>
#ifdef USE_HID_FOR_MODIFIERS
# include <CoreFoundation/CoreFoundation.h>
# include <IOKit/hid/IOHIDUsageTables.h>
# include <mach/mach.h>
# include <mach/mach_error.h>
#endif
#ifdef VBOX_WITH_KBD_LEDS_SYNC
# include <IOKit/IOMessage.h>
# include <IOKit/usb/IOUSBLib.h>
#endif


RT_C_DECLS_BEGIN
/* Private interface in 10.3 and later. */
typedef int CGSConnection;
typedef enum
{
    kCGSGlobalHotKeyEnable = 0,
    kCGSGlobalHotKeyDisable,
    kCGSGlobalHotKeyDisableExceptUniversalAccess,
    kCGSGlobalHotKeyInvalid = -1 /* bird */
} CGSGlobalHotKeyOperatingMode;
extern CGSConnection _CGSDefaultConnection(void);
extern CGError CGSGetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode *enmMode);
extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode enmMode);
RT_C_DECLS_END


/* Defined Constants And Macros: */
#define QZ_RMETA        0x36
#define QZ_LMETA        0x37
#define QZ_LSHIFT       0x38
#define QZ_CAPSLOCK     0x39
#define QZ_LALT         0x3A
#define QZ_LCTRL        0x3B
#define QZ_RSHIFT       0x3C
#define QZ_RALT         0x3D
#define QZ_RCTRL        0x3E
// Found the definition of the fn-key in:
// http://stuff.mit.edu/afs/sipb/project/darwin/src/modules/IOHIDFamily/IOHIDSystem/IOHIKeyboardMapper.cpp &
// http://stuff.mit.edu/afs/sipb/project/darwin/src/modules/AppleADBKeyboard/AppleADBKeyboard.cpp
// Maybe we need this in the future.
#define QZ_FN           0x3F
#define QZ_NUMLOCK      0x47
/** Short hand for an extended key. */
#define K_EX            VBOXKEY_EXTENDED
/** Short hand for a modifier key. */
#define K_MOD           VBOXKEY_MODIFIER
/** Short hand for a lock key. */
#define K_LOCK          VBOXKEY_LOCK
#ifdef USE_HID_FOR_MODIFIERS
/** An attempt at catching reference leaks. */
# define MY_CHECK_CREFS(cRefs)   do { AssertMsg(cRefs < 25, ("%ld\n", cRefs)); NOREF(cRefs); } while (0)
#endif


/** This is derived partially from SDL_QuartzKeys.h and partially from testing.
  * (The funny thing about the virtual scan codes on the mac is that they aren't
  * offically documented, which is rather silly to say the least. Thus, the need
  * for looking at SDL and other odd places for docs.) */
static const uint16_t g_aDarwinToSet1[] =
{
    /* set-1                           SDL_QuartzKeys.h */
    0x1e,                       /* QZ_a            0x00 */
    0x1f,                       /* QZ_s            0x01 */
    0x20,                       /* QZ_d            0x02 */
    0x21,                       /* QZ_f            0x03 */
    0x23,                       /* QZ_h            0x04 */
    0x22,                       /* QZ_g            0x05 */
    0x2c,                       /* QZ_z            0x06 */
    0x2d,                       /* QZ_x            0x07 */
    0x2e,                       /* QZ_c            0x08 */
    0x2f,                       /* QZ_v            0x09 */
    0x56,                       /* between lshift and z. 'INT 1'? */
    0x30,                       /* QZ_b            0x0B */
    0x10,                       /* QZ_q            0x0C */
    0x11,                       /* QZ_w            0x0D */
    0x12,                       /* QZ_e            0x0E */
    0x13,                       /* QZ_r            0x0F */
    0x15,                       /* QZ_y            0x10 */
    0x14,                       /* QZ_t            0x11 */
    0x02,                       /* QZ_1            0x12 */
    0x03,                       /* QZ_2            0x13 */
    0x04,                       /* QZ_3            0x14 */
    0x05,                       /* QZ_4            0x15 */
    0x07,                       /* QZ_6            0x16 */
    0x06,                       /* QZ_5            0x17 */
    0x0d,                       /* QZ_EQUALS       0x18 */
    0x0a,                       /* QZ_9            0x19 */
    0x08,                       /* QZ_7            0x1A */
    0x0c,                       /* QZ_MINUS        0x1B */
    0x09,                       /* QZ_8            0x1C */
    0x0b,                       /* QZ_0            0x1D */
    0x1b,                       /* QZ_RIGHTBRACKET 0x1E */
    0x18,                       /* QZ_o            0x1F */
    0x16,                       /* QZ_u            0x20 */
    0x1a,                       /* QZ_LEFTBRACKET  0x21 */
    0x17,                       /* QZ_i            0x22 */
    0x19,                       /* QZ_p            0x23 */
    0x1c,                       /* QZ_RETURN       0x24 */
    0x26,                       /* QZ_l            0x25 */
    0x24,                       /* QZ_j            0x26 */
    0x28,                       /* QZ_QUOTE        0x27 */
    0x25,                       /* QZ_k            0x28 */
    0x27,                       /* QZ_SEMICOLON    0x29 */
    0x2b,                       /* QZ_BACKSLASH    0x2A */
    0x33,                       /* QZ_COMMA        0x2B */
    0x35,                       /* QZ_SLASH        0x2C */
    0x31,                       /* QZ_n            0x2D */
    0x32,                       /* QZ_m            0x2E */
    0x34,                       /* QZ_PERIOD       0x2F */
    0x0f,                       /* QZ_TAB          0x30 */
    0x39,                       /* QZ_SPACE        0x31 */
    0x29,                       /* QZ_BACKQUOTE    0x32 */
    0x0e,                       /* QZ_BACKSPACE    0x33 */
    0x9c,                       /* QZ_IBOOK_ENTER  0x34 */
    0x01,                       /* QZ_ESCAPE       0x35 */
    0x5c|K_EX|K_MOD,            /* QZ_RMETA        0x36 */
    0x5b|K_EX|K_MOD,            /* QZ_LMETA        0x37 */
    0x2a|K_MOD,                 /* QZ_LSHIFT       0x38 */
    0x3a|K_LOCK,                /* QZ_CAPSLOCK     0x39 */
    0x38|K_MOD,                 /* QZ_LALT         0x3A */
    0x1d|K_MOD,                 /* QZ_LCTRL        0x3B */
    0x36|K_MOD,                 /* QZ_RSHIFT       0x3C */
    0x38|K_EX|K_MOD,            /* QZ_RALT         0x3D */
    0x1d|K_EX|K_MOD,            /* QZ_RCTRL        0x3E */
       0,                       /*                      */
       0,                       /*                      */
    0x53,                       /* QZ_KP_PERIOD    0x41 */
       0,                       /*                      */
    0x37,                       /* QZ_KP_MULTIPLY  0x43 */
       0,                       /*                      */
    0x4e,                       /* QZ_KP_PLUS      0x45 */
       0,                       /*                      */
    0x45|K_LOCK,                /* QZ_NUMLOCK      0x47 */
       0,                       /*                      */
       0,                       /*                      */
       0,                       /*                      */
    0x35|K_EX,                  /* QZ_KP_DIVIDE    0x4B */
    0x1c|K_EX,                  /* QZ_KP_ENTER     0x4C */
       0,                       /*                      */
    0x4a,                       /* QZ_KP_MINUS     0x4E */
       0,                       /*                      */
       0,                       /*                      */
    0x0d/*?*/,                  /* QZ_KP_EQUALS    0x51 */
    0x52,                       /* QZ_KP0          0x52 */
    0x4f,                       /* QZ_KP1          0x53 */
    0x50,                       /* QZ_KP2          0x54 */
    0x51,                       /* QZ_KP3          0x55 */
    0x4b,                       /* QZ_KP4          0x56 */
    0x4c,                       /* QZ_KP5          0x57 */
    0x4d,                       /* QZ_KP6          0x58 */
    0x47,                       /* QZ_KP7          0x59 */
       0,                       /*                      */
    0x48,                       /* QZ_KP8          0x5B */
    0x49,                       /* QZ_KP9          0x5C */
    0x7d,                       /* yen, | (JIS)    0x5D */
    0x73,                       /* _, ro (JIS)     0x5E */
       0,                       /*                      */
    0x3f,                       /* QZ_F5           0x60 */
    0x40,                       /* QZ_F6           0x61 */
    0x41,                       /* QZ_F7           0x62 */
    0x3d,                       /* QZ_F3           0x63 */
    0x42,                       /* QZ_F8           0x64 */
    0x43,                       /* QZ_F9           0x65 */
    0x29,                       /* Zen/Han (JIS)   0x66 */
    0x57,                       /* QZ_F11          0x67 */
    0x29,                       /* Zen/Han (JIS)   0x68 */
    0x37|K_EX,                  /* QZ_PRINT / F13  0x69 */
    0x63,                       /* QZ_F16          0x6A */
    0x46|K_LOCK,                /* QZ_SCROLLOCK    0x6B */
       0,                       /*                      */
    0x44,                       /* QZ_F10          0x6D */
    0x5d|K_EX,                  /*                      */
    0x58,                       /* QZ_F12          0x6F */
       0,                       /*                      */
       0/* 0xe1,0x1d,0x45*/,    /* QZ_PAUSE        0x71 */
    0x52|K_EX,                  /* QZ_INSERT / HELP 0x72 */
    0x47|K_EX,                  /* QZ_HOME         0x73 */
    0x49|K_EX,                  /* QZ_PAGEUP       0x74 */
    0x53|K_EX,                  /* QZ_DELETE       0x75 */
    0x3e,                       /* QZ_F4           0x76 */
    0x4f|K_EX,                  /* QZ_END          0x77 */
    0x3c,                       /* QZ_F2           0x78 */
    0x51|K_EX,                  /* QZ_PAGEDOWN     0x79 */
    0x3b,                       /* QZ_F1           0x7A */
    0x4b|K_EX,                  /* QZ_LEFT         0x7B */
    0x4d|K_EX,                  /* QZ_RIGHT        0x7C */
    0x50|K_EX,                  /* QZ_DOWN         0x7D */
    0x48|K_EX,                  /* QZ_UP           0x7E */
       0,/*0x5e|K_EX*/          /* QZ_POWER        0x7F */ /* have different break key! */
                                                           /* do NEVER deliver the Power
                                                            * scancode as e.g. Windows will
                                                            * handle it, @bugref{7692}. */
};


/** Holds whether we've connected or not. */
static bool g_fConnectedToCGS = false;
/** Holds the cached connection. */
static CGSConnection g_CGSConnection;


#ifdef USE_HID_FOR_MODIFIERS

/** Holds the IO Master Port. */
static mach_port_t g_MasterPort = NULL;

/** Holds the amount of keyboards in the cache. */
static unsigned g_cKeyboards = 0;
/** Array of cached keyboard data. */
static struct KeyboardCacheData
{
    /** The device interface. */
    IOHIDDeviceInterface  **ppHidDeviceInterface;
    /** The queue interface. */
    IOHIDQueueInterface   **ppHidQueueInterface;

    /** Cookie translation array. */
    struct KeyboardCacheCookie
    {
        /** The cookie. */
        IOHIDElementCookie  Cookie;
        /** The corresponding modifier mask. */
        uint32_t            fMask;
    }                       aCookies[64];
    /** Number of cookies in the array. */
    unsigned                cCookies;
}                   g_aKeyboards[128];
/** Holds the keyboard cache creation timestamp. */
static uint64_t     g_u64KeyboardTS = 0;

/** Holds the HID queue status. */
static bool         g_fHIDQueueEnabled;
/** Holds the current modifier mask. */
static uint32_t     g_fHIDModifierMask;
/** Holds the old modifier mask. */
static uint32_t     g_fOldHIDModifierMask;

#endif /* USE_HID_FOR_MODIFIERS */


#ifdef VBOX_WITH_KBD_LEDS_SYNC

#define VBOX_BOOL_TO_STR_STATE(x) (x) ? "ON" : "OFF"
/** HID LEDs synchronization data: LED states. */
typedef struct VBoxLedState_t
{
    /** Holds the state of NUM LOCK. */
    bool fNumLockOn;
    /** Holds the  state of CAPS LOCK. */
    bool fCapsLockOn;
    /** Holds the  state of SCROLL LOCK. */
    bool fScrollLockOn;
} VBoxLedState_t;

/** HID LEDs synchronization data: keyboard states. */
typedef struct VBoxKbdState_t
{
    /** Holds the reference to IOKit HID device. */
    IOHIDDeviceRef    pDevice;
    /** Holds the LED states. */
    VBoxLedState_t    LED;
    /** Holds the  pointer to a VBoxHidsState_t instance where VBoxKbdState_t instance is stored. */
    void             *pParentContainer;
    /** Holds the position in global storage (used to simplify CFArray navigation when removing detached device). */
    CFIndex           idxPosition;
    /** Holds the KBD CAPS LOCK key hold timeout (some Apple keyboards only). */
    uint64_t          cCapsLockTimeout;
    /** Holds the HID Location ID: unique for an USB device registered in the system. */
    uint32_t          idLocation;
} VBoxKbdState_t;

/** A struct that used to pass input event info from IOKit callback to a Carbon one */
typedef struct VBoxKbdEvent_t
{
    VBoxKbdState_t *pKbd;
    uint32_t        iKeyCode;
    uint64_t        tsKeyDown;
} VBoxKbdEvent_t;

/** HID LEDs synchronization data: IOKit specific data. */
typedef struct VBoxHidsState_t
{
    /** Holds the IOKit HID manager reference. */
    IOHIDManagerRef     hidManagerRef;
    /** Holds the array which consists of VBoxKbdState_t elements. */
    CFMutableArrayRef   pDeviceCollection;
    /** Holds the LED states that were stored during last broadcast and reflect a guest LED states. */
    VBoxLedState_t      guestState;

    /** Holds the queue which will be appended in IOKit input callback. Carbon input callback will extract data from it. */
    CFMutableArrayRef   pFifoEventQueue;
    /** Holds the lock for pFifoEventQueue. */
    RTSEMMUTEX          fifoEventQueueLock;

    /** Holds the IOService notification reference: USB HID device matching. */
    io_iterator_t         pUsbHidDeviceMatchNotify;
    /** Holds the IOService notification reference: USB HID general interest notifications (IOService messages). */
    io_iterator_t         pUsbHidGeneralInterestNotify;
    /** Holds the IOService notification port reference: device match and device general interest message. */
    IONotificationPortRef pNotificationPrortRef;

    CFMachPortRef       pTapRef;
    CFRunLoopSourceRef  pLoopSourceRef;
} VBoxHidsState_t;

#endif /* VBOX_WITH_KBD_LEDS_SYNC */


unsigned DarwinKeycodeToSet1Scancode(unsigned uKeyCode)
{
    if (uKeyCode >= RT_ELEMENTS(g_aDarwinToSet1))
        return 0;
    return g_aDarwinToSet1[uKeyCode];
}

UInt32 DarwinAdjustModifierMask(UInt32 fModifiers, const void *pvCocoaEvent)
{
    /* Check if there is anything to adjust and perform the adjustment. */
    if (fModifiers & (shiftKey | rightShiftKey | controlKey | rightControlKey | optionKey | rightOptionKey | cmdKey | kEventKeyModifierRightCmdKeyMask))
    {
#ifndef USE_HID_FOR_MODIFIERS
        // WORKAROUND:
        // Convert the Cocoa modifiers to Carbon ones (the Cocoa modifier
        // definitions are tucked away in Objective-C headers, unfortunately).
        //
        // Update: CGEventTypes.h includes what looks like the Cocoa modifiers
        //         and the NX_* defines should be available as well. We should look
        //         into ways to intercept the CG (core graphics) events in the Carbon
        //         based setup and get rid of all this HID mess. */
        AssertPtr(pvCocoaEvent);
        //::darwinPrintEvent("dbg-adjMods: ", pvCocoaEvent);
        uint32_t fAltModifiers = ::darwinEventModifierFlagsXlated(pvCocoaEvent);
#else  /* USE_HID_FOR_MODIFIERS */
        /* Update the keyboard cache. */
        darwinHIDKeyboardCacheUpdate();
        const UInt32 fAltModifiers = g_fHIDModifierMask;
#endif /* USE_HID_FOR_MODIFIERS */

#ifdef DEBUG_PRINTF
        RTPrintf("dbg-fAltModifiers=%#x fModifiers=%#x", fAltModifiers, fModifiers);
#endif
        if (   (fModifiers    & (rightShiftKey | shiftKey))
            && (fAltModifiers & (rightShiftKey | shiftKey)))
        {
            fModifiers &= ~(rightShiftKey | shiftKey);
            fModifiers |= fAltModifiers & (rightShiftKey | shiftKey);
        }

        if (   (fModifiers    & (rightControlKey | controlKey))
            && (fAltModifiers & (rightControlKey | controlKey)))
        {
            fModifiers &= ~(rightControlKey | controlKey);
            fModifiers |= fAltModifiers & (rightControlKey | controlKey);
        }

        if (   (fModifiers    & (optionKey | rightOptionKey))
            && (fAltModifiers & (optionKey | rightOptionKey)))
        {
            fModifiers &= ~(optionKey | rightOptionKey);
            fModifiers |= fAltModifiers & (optionKey | rightOptionKey);
        }

        if (   (fModifiers    & (cmdKey | kEventKeyModifierRightCmdKeyMask))
            && (fAltModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask)))
        {
            fModifiers &= ~(cmdKey | kEventKeyModifierRightCmdKeyMask);
            fModifiers |= fAltModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask);
        }
#ifdef DEBUG_PRINTF
        RTPrintf(" -> %#x\n", fModifiers);
#endif
    }
    return fModifiers;
}

unsigned DarwinModifierMaskToSet1Scancode(UInt32 fModifiers)
{
    unsigned uScanCode = DarwinModifierMaskToDarwinKeycode(fModifiers);
    if (uScanCode < RT_ELEMENTS(g_aDarwinToSet1))
        uScanCode = g_aDarwinToSet1[uScanCode];
    else
        Assert(uScanCode == ~0U);
    return uScanCode;
}

unsigned DarwinModifierMaskToDarwinKeycode(UInt32 fModifiers)
{
    unsigned uKeyCode;

    /** @todo find symbols for these keycodes... */
    fModifiers &= shiftKey | rightShiftKey | controlKey | rightControlKey | optionKey | rightOptionKey | cmdKey
                | kEventKeyModifierRightCmdKeyMask | kEventKeyModifierNumLockMask | alphaLock | kEventKeyModifierFnMask;
    if (fModifiers == shiftKey)
        uKeyCode = QZ_LSHIFT;
    else if (fModifiers == rightShiftKey)
        uKeyCode = QZ_RSHIFT;
    else if (fModifiers == controlKey)
        uKeyCode = QZ_LCTRL;
    else if (fModifiers == rightControlKey)
        uKeyCode = QZ_RCTRL;
    else if (fModifiers == optionKey)
        uKeyCode = QZ_LALT;
    else if (fModifiers == rightOptionKey)
        uKeyCode = QZ_RALT;
    else if (fModifiers == cmdKey)
        uKeyCode = QZ_LMETA;
    else if (fModifiers == kEventKeyModifierRightCmdKeyMask /* hack */)
        uKeyCode = QZ_RMETA;
    else if (fModifiers == alphaLock)
        uKeyCode = QZ_CAPSLOCK;
    else if (fModifiers == kEventKeyModifierNumLockMask)
        uKeyCode = QZ_NUMLOCK;
    else if (fModifiers == kEventKeyModifierFnMask)
        uKeyCode = QZ_FN;
    else if (fModifiers == 0)
        uKeyCode = 0;
    else
        uKeyCode = ~0U; /* multiple */
    return uKeyCode;
}

UInt32 DarwinKeyCodeToDarwinModifierMask(unsigned uKeyCode)
{
    UInt32 fModifiers;

    /** @todo find symbols for these keycodes... */
    if (uKeyCode == QZ_LSHIFT)
        fModifiers = shiftKey;
    else if (uKeyCode == QZ_RSHIFT)
        fModifiers = rightShiftKey;
    else if (uKeyCode == QZ_LCTRL)
        fModifiers = controlKey;
    else if (uKeyCode == QZ_RCTRL)
        fModifiers = rightControlKey;
    else if (uKeyCode == QZ_LALT)
        fModifiers = optionKey;
    else if (uKeyCode == QZ_RALT)
        fModifiers = rightOptionKey;
    else if (uKeyCode == QZ_LMETA)
        fModifiers = cmdKey;
    else if (uKeyCode == QZ_RMETA)
        fModifiers = kEventKeyModifierRightCmdKeyMask; /* hack */
    else if (uKeyCode == QZ_CAPSLOCK)
        fModifiers = alphaLock;
    else if (uKeyCode == QZ_NUMLOCK)
        fModifiers = kEventKeyModifierNumLockMask;
    else if (uKeyCode == QZ_FN)
        fModifiers = kEventKeyModifierFnMask;
    else
        fModifiers = 0;
    return fModifiers;
}


void DarwinDisableGlobalHotKeys(bool fDisable)
{
    static unsigned s_cComplaints = 0;

    /* Lazy connect to the core graphics service. */
    if (!g_fConnectedToCGS)
    {
        g_CGSConnection = _CGSDefaultConnection();
        g_fConnectedToCGS = true;
    }

    /* Get the current mode. */
    CGSGlobalHotKeyOperatingMode enmMode = kCGSGlobalHotKeyInvalid;
    CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmMode);
    if (    enmMode != kCGSGlobalHotKeyEnable
        &&  enmMode != kCGSGlobalHotKeyDisable
        &&  enmMode != kCGSGlobalHotKeyDisableExceptUniversalAccess)
    {
        AssertMsgFailed(("%d\n", enmMode));
        if (s_cComplaints++ < 32)
            LogRel(("DarwinDisableGlobalHotKeys: Unexpected enmMode=%d\n", enmMode));
        return;
    }

    /* Calc the new mode. */
    if (fDisable)
    {
        if (enmMode != kCGSGlobalHotKeyEnable)
            return;
        enmMode = kCGSGlobalHotKeyDisableExceptUniversalAccess;
    }
    else
    {
        if (enmMode != kCGSGlobalHotKeyDisableExceptUniversalAccess)
            return;
        enmMode = kCGSGlobalHotKeyEnable;
    }

    /* Try set it and check the actual result. */
    CGSSetGlobalHotKeyOperatingMode(g_CGSConnection, enmMode);
    CGSGlobalHotKeyOperatingMode enmNewMode = kCGSGlobalHotKeyInvalid;
    CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmNewMode);
    if (enmNewMode != enmMode)
    {
        /* If the screensaver kicks in we should ignore failure here. */
        AssertMsg(enmMode == kCGSGlobalHotKeyEnable, ("enmNewMode=%d enmMode=%d\n", enmNewMode, enmMode));
        if (s_cComplaints++ < 32)
            LogRel(("DarwinDisableGlobalHotKeys: Failed to change mode; enmNewMode=%d enmMode=%d\n", enmNewMode, enmMode));
    }
}


#ifdef USE_HID_FOR_MODIFIERS

/** Callback function for consuming queued events.
  * @param   pvTarget  Brings the queue?
  * @param   rcIn      Brings what?
  * @param   pvRefcon  Brings the pointer to the keyboard cache entry.
  * @param   pvSender  Brings what? */
static void darwinQueueCallback(void *pvTarget, IOReturn rcIn, void *pvRefcon, void *pvSender)
{
    struct KeyboardCacheData *pKeyboardEntry = (struct KeyboardCacheData *)pvRefcon;
    if (!pKeyboardEntry->ppHidQueueInterface)
        return;
    NOREF(pvTarget);
    NOREF(rcIn);
    NOREF(pvSender);

    /* Consume the events. */
    g_fOldHIDModifierMask = g_fHIDModifierMask;
    for (;;)
    {
#ifdef DEBUG_PRINTF
        RTPrintf("dbg-ev: "); RTStrmFlush(g_pStdOut);
#endif
        IOHIDEventStruct Event;
        AbsoluteTime ZeroTime = {0,0};
        IOReturn rc = (*pKeyboardEntry->ppHidQueueInterface)->getNextEvent(pKeyboardEntry->ppHidQueueInterface,
                                                                           &Event, ZeroTime, 0);
        if (rc != kIOReturnSuccess)
            break;

        /* Translate the cookie value to a modifier mask. */
        uint32_t fMask = 0;
        unsigned i = pKeyboardEntry->cCookies;
        while (i-- > 0)
        {
            if (pKeyboardEntry->aCookies[i].Cookie == Event.elementCookie)
            {
                fMask = pKeyboardEntry->aCookies[i].fMask;
                break;
            }
        }

        /* Adjust the modifier mask. */
        if (Event.value)
            g_fHIDModifierMask |= fMask;
        else
            g_fHIDModifierMask &= ~fMask;
#ifdef DEBUG_PRINTF
        RTPrintf("t=%d c=%#x v=%#x cblv=%d lv=%p m=%#X\n", Event.type, Event.elementCookie, Event.value, Event.longValueSize, Event.value, fMask); RTStrmFlush(g_pStdOut);
#endif
    }
#ifdef DEBUG_PRINTF
    RTPrintf("dbg-ev: done\n"); RTStrmFlush(g_pStdOut);
#endif
}

/* Forward declaration for darwinBruteForcePropertySearch. */
static void darwinBruteForcePropertySearch(CFDictionaryRef DictRef, struct KeyboardCacheData *pKeyboardEntry);

/** Element enumeration callback. */
static void darwinBruteForcePropertySearchApplier(const void *pvValue, void *pvCacheEntry)
{
    if (CFGetTypeID(pvValue) == CFDictionaryGetTypeID())
        darwinBruteForcePropertySearch((CFMutableDictionaryRef)pvValue, (struct KeyboardCacheData *)pvCacheEntry);
}

/** Recurses through the keyboard properties looking for certain keys. */
static void darwinBruteForcePropertySearch(CFDictionaryRef DictRef, struct KeyboardCacheData *pKeyboardEntry)
{
    CFTypeRef ObjRef;

    /* Check for the usage page and usage key we want. */
    long lUsage;
    ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementUsageKey));
    if (    ObjRef
        &&  CFGetTypeID(ObjRef) == CFNumberGetTypeID()
        &&  CFNumberGetValue((CFNumberRef)ObjRef, kCFNumberLongType, &lUsage))
    {
        switch (lUsage)
        {
            case kHIDUsage_KeyboardLeftControl:
            case kHIDUsage_KeyboardLeftShift:
            case kHIDUsage_KeyboardLeftAlt:
            case kHIDUsage_KeyboardLeftGUI:
            case kHIDUsage_KeyboardRightControl:
            case kHIDUsage_KeyboardRightShift:
            case kHIDUsage_KeyboardRightAlt:
            case kHIDUsage_KeyboardRightGUI:
            {
                long lPage;
                ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementUsagePageKey));
                if (    !ObjRef
                    ||  CFGetTypeID(ObjRef) != CFNumberGetTypeID()
                    ||  !CFNumberGetValue((CFNumberRef)ObjRef, kCFNumberLongType, &lPage)
                    ||  lPage != kHIDPage_KeyboardOrKeypad)
                    break;

                if (pKeyboardEntry->cCookies >= RT_ELEMENTS(pKeyboardEntry->aCookies))
                {
                    AssertMsgFailed(("too many cookies!\n"));
                    break;
                }

                /* Get the cookie and modifier mask. */
                long lCookie;
                ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementCookieKey));
                if (    !ObjRef
                    ||  CFGetTypeID(ObjRef) != CFNumberGetTypeID()
                    ||  !CFNumberGetValue((CFNumberRef)ObjRef, kCFNumberLongType, &lCookie))
                    break;

                uint32_t fMask;
                switch (lUsage)
                {
                    case kHIDUsage_KeyboardLeftControl : fMask = controlKey; break;
                    case kHIDUsage_KeyboardLeftShift   : fMask = shiftKey; break;
                    case kHIDUsage_KeyboardLeftAlt     : fMask = optionKey; break;
                    case kHIDUsage_KeyboardLeftGUI     : fMask = cmdKey; break;
                    case kHIDUsage_KeyboardRightControl: fMask = rightControlKey; break;
                    case kHIDUsage_KeyboardRightShift  : fMask = rightShiftKey; break;
                    case kHIDUsage_KeyboardRightAlt    : fMask = rightOptionKey; break;
                    case kHIDUsage_KeyboardRightGUI    : fMask = kEventKeyModifierRightCmdKeyMask; break;
                    default: AssertMsgFailed(("%ld\n",lUsage)); fMask = 0; break;
                }

                /* If we've got a queue, add the cookie to the queue. */
                if (pKeyboardEntry->ppHidQueueInterface)
                {
                    IOReturn rc = (*pKeyboardEntry->ppHidQueueInterface)->addElement(pKeyboardEntry->ppHidQueueInterface, (IOHIDElementCookie)lCookie, 0);
                    AssertMsg(rc == kIOReturnSuccess, ("rc=%d\n", rc));
#ifdef DEBUG_PRINTF
                    RTPrintf("dbg-add: u=%#lx c=%#lx\n", lUsage, lCookie);
#endif
                }

                /* Add the cookie to the keyboard entry. */
                pKeyboardEntry->aCookies[pKeyboardEntry->cCookies].Cookie = (IOHIDElementCookie)lCookie;
                pKeyboardEntry->aCookies[pKeyboardEntry->cCookies].fMask = fMask;
                ++pKeyboardEntry->cCookies;
                break;
            }
        }
    }


    /* Get the elements key and recursively iterate the elements looking for they key cookies. */
    ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementKey));
    if (    ObjRef
        &&  CFGetTypeID(ObjRef) == CFArrayGetTypeID())
    {
        CFArrayRef ArrayObjRef = (CFArrayRef)ObjRef;
        CFRange Range = {0, CFArrayGetCount(ArrayObjRef)};
        CFArrayApplyFunction(ArrayObjRef, Range, darwinBruteForcePropertySearchApplier, pKeyboardEntry);
    }
}

/** Creates a keyboard cache entry.
  * @param  pKeyboardEntry  Brings the pointer to the entry.
  * @param  KeyboardDevice  Brings the keyboard device to create the entry for. */
static bool darwinHIDKeyboardCacheCreateEntry(struct KeyboardCacheData *pKeyboardEntry, io_object_t KeyboardDevice)
{
    unsigned long cRefs = 0;
    memset(pKeyboardEntry, 0, sizeof(*pKeyboardEntry));

    /* Query the HIDDeviceInterface for this HID (keyboard) object. */
    SInt32 Score = 0;
    IOCFPlugInInterface **ppPlugInInterface = NULL;
    IOReturn rc = IOCreatePlugInInterfaceForService(KeyboardDevice, kIOHIDDeviceUserClientTypeID,
                                                    kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
    if (rc == kIOReturnSuccess)
    {
        IOHIDDeviceInterface **ppHidDeviceInterface = NULL;
        HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
                                                           CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID),
                                                           (LPVOID *)&ppHidDeviceInterface);
        cRefs = (*ppPlugInInterface)->Release(ppPlugInInterface); MY_CHECK_CREFS(cRefs);
        ppPlugInInterface = NULL;
        if (hrc == S_OK)
        {
            rc = (*ppHidDeviceInterface)->open(ppHidDeviceInterface, 0);
            if (rc == kIOReturnSuccess)
            {
                /* Create a removal callback. */
                /** @todo */

                /* Create the queue so we can insert elements while searching the properties. */
                IOHIDQueueInterface   **ppHidQueueInterface = (*ppHidDeviceInterface)->allocQueue(ppHidDeviceInterface);
                if (ppHidQueueInterface)
                {
                    rc = (*ppHidQueueInterface)->create(ppHidQueueInterface, 0, 32);
                    if (rc != kIOReturnSuccess)
                    {
                        AssertMsgFailed(("rc=%d\n", rc));
                        cRefs = (*ppHidQueueInterface)->Release(ppHidQueueInterface); MY_CHECK_CREFS(cRefs);
                        ppHidQueueInterface = NULL;
                    }
                }
                else
                    AssertFailed();
                pKeyboardEntry->ppHidQueueInterface = ppHidQueueInterface;

                /* Brute force getting of attributes. */
                /** @todo read up on how to do this in a less resource intensive way! Suggestions are welcome! */
                CFMutableDictionaryRef PropertiesRef = 0;
                kern_return_t krc = IORegistryEntryCreateCFProperties(KeyboardDevice, &PropertiesRef, kCFAllocatorDefault, kNilOptions);
                if (krc == KERN_SUCCESS)
                {
                    darwinBruteForcePropertySearch(PropertiesRef, pKeyboardEntry);
                    CFRelease(PropertiesRef);
                }
                else
                    AssertMsgFailed(("krc=%#x\n", krc));

                if (ppHidQueueInterface)
                {
                    /* Now install our queue callback. */
                    CFRunLoopSourceRef RunLoopSrcRef = NULL;
                    rc = (*ppHidQueueInterface)->createAsyncEventSource(ppHidQueueInterface, &RunLoopSrcRef);
                    if (rc == kIOReturnSuccess)
                    {
                        CFRunLoopRef RunLoopRef = (CFRunLoopRef)GetCFRunLoopFromEventLoop(GetMainEventLoop());
                        CFRunLoopAddSource(RunLoopRef, RunLoopSrcRef, kCFRunLoopDefaultMode);
                    }

                    /* Now install our queue callback. */
                    rc = (*ppHidQueueInterface)->setEventCallout(ppHidQueueInterface, darwinQueueCallback, ppHidQueueInterface, pKeyboardEntry);
                    if (rc != kIOReturnSuccess)
                        AssertMsgFailed(("rc=%d\n", rc));
                }

                /* Complete the new keyboard cache entry. */
                pKeyboardEntry->ppHidDeviceInterface = ppHidDeviceInterface;
                pKeyboardEntry->ppHidQueueInterface = ppHidQueueInterface;
                return true;
            }

            AssertMsgFailed(("rc=%d\n", rc));
            cRefs = (*ppHidDeviceInterface)->Release(ppHidDeviceInterface); MY_CHECK_CREFS(cRefs);
        }
        else
            AssertMsgFailed(("hrc=%#x\n", hrc));
    }
    else
        AssertMsgFailed(("rc=%d\n", rc));

    return false;
}

/** Destroys a keyboard cache entry. */
static void darwinHIDKeyboardCacheDestroyEntry(struct KeyboardCacheData *pKeyboardEntry)
{
    unsigned long cRefs;

    /* Destroy the queue. */
    if (pKeyboardEntry->ppHidQueueInterface)
    {
        IOHIDQueueInterface **ppHidQueueInterface = pKeyboardEntry->ppHidQueueInterface;
        pKeyboardEntry->ppHidQueueInterface = NULL;

        /* Stop it just in case we haven't done so. doesn't really matter I think. */
        (*ppHidQueueInterface)->stop(ppHidQueueInterface);

        /* Deal with the run loop source. */
        CFRunLoopSourceRef RunLoopSrcRef = (*ppHidQueueInterface)->getAsyncEventSource(ppHidQueueInterface);
        if (RunLoopSrcRef)
        {
            CFRunLoopRef RunLoopRef = (CFRunLoopRef)GetCFRunLoopFromEventLoop(GetMainEventLoop());
            CFRunLoopRemoveSource(RunLoopRef, RunLoopSrcRef, kCFRunLoopDefaultMode);

            CFRelease(RunLoopSrcRef);
        }

        /* Dispose of and release the queue. */
        (*ppHidQueueInterface)->dispose(ppHidQueueInterface);
        cRefs = (*ppHidQueueInterface)->Release(ppHidQueueInterface); MY_CHECK_CREFS(cRefs);
    }

    /* Release the removal hook? */
    /** @todo */

    /* Close and release the device interface. */
    if (pKeyboardEntry->ppHidDeviceInterface)
    {
        IOHIDDeviceInterface **ppHidDeviceInterface = pKeyboardEntry->ppHidDeviceInterface;
        pKeyboardEntry->ppHidDeviceInterface = NULL;

        (*ppHidDeviceInterface)->close(ppHidDeviceInterface);
        cRefs = (*ppHidDeviceInterface)->Release(ppHidDeviceInterface); MY_CHECK_CREFS(cRefs);
    }
}

/** Zap the keyboard cache. */
static void darwinHIDKeyboardCacheZap(void)
{
    /* Release the old cache data first. */
    while (g_cKeyboards > 0)
    {
        unsigned i = --g_cKeyboards;
        darwinHIDKeyboardCacheDestroyEntry(&g_aKeyboards[i]);
    }
}

/** Updates the cached keyboard data.
  * @todo The current implementation is very brute force...
  *       Rewrite it so that it doesn't flush the cache completely but simply checks whether
  *       anything has changed in the HID config. With any luck, there might even be a callback
  *       or something we can poll for HID config changes...
  *       setRemovalCallback() is a start... */
static void darwinHIDKeyboardCacheDoUpdate(void)
{
    g_u64KeyboardTS = RTTimeMilliTS();

    /* Dispense with the old cache data. */
    darwinHIDKeyboardCacheZap();

    /* Open the master port on the first invocation. */
    if (!g_MasterPort)
    {
        kern_return_t krc = IOMasterPort(MACH_PORT_NULL, &g_MasterPort);
        AssertReturnVoid(krc == KERN_SUCCESS);
    }

    /* Create a matching dictionary for searching for keyboards devices. */
    static const UInt32 s_Page = kHIDPage_GenericDesktop;
    static const UInt32 s_Usage = kHIDUsage_GD_Keyboard;
    CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOHIDDeviceKey);
    AssertReturnVoid(RefMatchingDict);
    CFDictionarySetValue(RefMatchingDict, CFSTR(kIOHIDPrimaryUsagePageKey),
                         CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &s_Page));
    CFDictionarySetValue(RefMatchingDict, CFSTR(kIOHIDPrimaryUsageKey),
                         CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &s_Usage));

    /* Perform the search and get a collection of keyboard devices. */
    io_iterator_t Keyboards = NULL;
    IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &Keyboards);
    AssertMsgReturnVoid(rc == kIOReturnSuccess, ("rc=%d\n", rc));
    RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */

    /* Enumerate the keyboards and query the cache data. */
    unsigned i = 0;
    io_object_t KeyboardDevice;
    while (   i < RT_ELEMENTS(g_aKeyboards)
           && (KeyboardDevice = IOIteratorNext(Keyboards)) != 0)
    {
        if (darwinHIDKeyboardCacheCreateEntry(&g_aKeyboards[i], KeyboardDevice))
            i++;
        IOObjectRelease(KeyboardDevice);
    }
    g_cKeyboards = i;

    IOObjectRelease(Keyboards);
}

/** Updates the keyboard cache if it's time to do it again. */
static void darwinHIDKeyboardCacheUpdate(void)
{
    if (    !g_cKeyboards
        /*||  g_u64KeyboardTS - RTTimeMilliTS() > 7500*/ /* 7.5sec */)
        darwinHIDKeyboardCacheDoUpdate();
}

/** Queries the modifier keys from the (IOKit) HID Manager. */
static UInt32 darwinQueryHIDModifiers(void)
{
    /* Iterate thru the keyboards collecting their modifier masks. */
    UInt32 fHIDModifiers = 0;
    unsigned i = g_cKeyboards;
    while (i-- > 0)
    {
        IOHIDDeviceInterface **ppHidDeviceInterface = g_aKeyboards[i].ppHidDeviceInterface;
        if (!ppHidDeviceInterface)
            continue;

        unsigned j = g_aKeyboards[i].cCookies;
        while (j-- > 0)
        {
            IOHIDEventStruct HidEvent;
            IOReturn rc = (*ppHidDeviceInterface)->getElementValue(ppHidDeviceInterface,
                                                                   g_aKeyboards[i].aCookies[j].Cookie,
                                                                   &HidEvent);
            if (rc == kIOReturnSuccess)
            {
                if (HidEvent.value)
                    fHIDModifiers |= g_aKeyboards[i].aCookies[j].fMask;
            }
            else
                AssertMsgFailed(("rc=%#x\n", rc));
        }
    }

    return fHIDModifiers;
}

#endif /* USE_HID_FOR_MODIFIERS */


void DarwinGrabKeyboard(bool fGlobalHotkeys)
{
    LogFlow(("DarwinGrabKeyboard: fGlobalHotkeys=%RTbool\n", fGlobalHotkeys));

#ifdef USE_HID_FOR_MODIFIERS
    /* Update the keyboard cache. */
    darwinHIDKeyboardCacheUpdate();

    /* Start the keyboard queues and query the current mask. */
    g_fHIDQueueEnabled = true;

    unsigned i = g_cKeyboards;
    while (i-- > 0)
    {
        if (g_aKeyboards[i].ppHidQueueInterface)
            (*g_aKeyboards[i].ppHidQueueInterface)->start(g_aKeyboards[i].ppHidQueueInterface);
    }

    g_fHIDModifierMask = darwinQueryHIDModifiers();
#endif /* USE_HID_FOR_MODIFIERS */

    /* Disable hotkeys if requested. */
    if (fGlobalHotkeys)
        DarwinDisableGlobalHotKeys(true);
}

void DarwinReleaseKeyboard()
{
    LogFlow(("DarwinReleaseKeyboard\n"));

    /* Re-enable hotkeys. */
    DarwinDisableGlobalHotKeys(false);

#ifdef USE_HID_FOR_MODIFIERS
    /* Stop and drain the keyboard queues. */
    g_fHIDQueueEnabled = false;

#if 0
    unsigned i = g_cKeyboards;
    while (i-- > 0)
    {
        if (g_aKeyboards[i].ppHidQueueInterface)
        {

            (*g_aKeyboards[i].ppHidQueueInterface)->stop(g_aKeyboards[i].ppHidQueueInterface);

            /* drain it */
            IOReturn rc;
            unsigned c = 0;
            do
            {
                IOHIDEventStruct Event;
                AbsoluteTime MaxTime = {0,0};
                rc = (*g_aKeyboards[i].ppHidQueueInterface)->getNextEvent(g_aKeyboards[i].ppHidQueueInterface,
                                                                          &Event, MaxTime, 0);
            } while (   rc == kIOReturnSuccess
                     && c++ < 32);
        }
    }
#else
    /* Kill the keyboard cache. */
    darwinHIDKeyboardCacheZap();
#endif

    /* Clear the modifier mask. */
    g_fHIDModifierMask = 0;
#endif /* USE_HID_FOR_MODIFIERS */
}


#ifdef VBOX_WITH_KBD_LEDS_SYNC

/** Prepares dictionary that will be used to match HID LED device(s) while discovering. */
static CFDictionaryRef darwinQueryLedDeviceMatchingDictionary()
{
    CFDictionaryRef deviceMatchingDictRef;

    // Use two (key, value) pairs:
    //      - (kIOHIDDeviceUsagePageKey, kHIDPage_GenericDesktop),
    //      - (kIOHIDDeviceUsageKey,     kHIDUsage_GD_Keyboard). */

    CFNumberRef usagePageKeyCFNumberRef; int usagePageKeyCFNumberValue = kHIDPage_GenericDesktop;
    CFNumberRef usageKeyCFNumberRef;     int usageKeyCFNumberValue     = kHIDUsage_GD_Keyboard;

    usagePageKeyCFNumberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usagePageKeyCFNumberValue);
    if (usagePageKeyCFNumberRef)
    {
        usageKeyCFNumberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usageKeyCFNumberValue);
        if (usageKeyCFNumberRef)
        {
            CFStringRef dictionaryKeys[2] = { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) };
            CFNumberRef dictionaryVals[2] = { usagePageKeyCFNumberRef,         usageKeyCFNumberRef         };

            deviceMatchingDictRef = CFDictionaryCreate(kCFAllocatorDefault,
                                                       (const void **)dictionaryKeys,
                                                       (const void **)dictionaryVals,
                                                       2, /** two (key, value) pairs */
                                                       &kCFTypeDictionaryKeyCallBacks,
                                                       &kCFTypeDictionaryValueCallBacks);

            if (deviceMatchingDictRef)
            {
                CFRelease(usageKeyCFNumberRef);
                CFRelease(usagePageKeyCFNumberRef);

                return deviceMatchingDictRef;
            }

            CFRelease(usageKeyCFNumberRef);
        }

        CFRelease(usagePageKeyCFNumberRef);
    }

    return NULL;
}

/** Prepare dictionary that will be used to match HID LED device element(s) while discovering. */
static CFDictionaryRef darwinQueryLedElementMatchingDictionary()
{
    CFDictionaryRef elementMatchingDictRef;

    // Use only one (key, value) pair to match LED device element:
    //      - (kIOHIDElementUsagePageKey, kHIDPage_LEDs).  */

    CFNumberRef usagePageKeyCFNumberRef; int usagePageKeyCFNumberValue = kHIDPage_LEDs;

    usagePageKeyCFNumberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usagePageKeyCFNumberValue);
    if (usagePageKeyCFNumberRef)
    {
        CFStringRef dictionaryKeys[1] = { CFSTR(kIOHIDElementUsagePageKey), };
        CFNumberRef dictionaryVals[1] = { usagePageKeyCFNumberRef,          };

        elementMatchingDictRef = CFDictionaryCreate(kCFAllocatorDefault,
                                                    (const void **)dictionaryKeys,
                                                    (const void **)dictionaryVals,
                                                    1, /** one (key, value) pair */
                                                    &kCFTypeDictionaryKeyCallBacks,
                                                    &kCFTypeDictionaryValueCallBacks);

        if (elementMatchingDictRef)
        {
            CFRelease(usagePageKeyCFNumberRef);
            return elementMatchingDictRef;
        }

        CFRelease(usagePageKeyCFNumberRef);
    }

    return NULL;
}

/** Turn ON or OFF a particular LED. */
static int darwinLedElementSetValue(IOHIDDeviceRef hidDevice, IOHIDElementRef element, bool fEnabled)
{
    IOHIDValueRef valueRef;
    IOReturn      rc = kIOReturnError;

    /* Try to resume suspended keyboard devices. Abort if failed in order to avoid GUI freezes. */
    int rc1 = SUPR3ResumeSuspendedKeyboards();
    if (RT_FAILURE(rc1))
        return rc1;

    valueRef = IOHIDValueCreateWithIntegerValue(kCFAllocatorDefault, element, 0, (fEnabled) ? 1 : 0);
    if (valueRef)
    {
        rc = IOHIDDeviceSetValue(hidDevice, element, valueRef);
        if (rc != kIOReturnSuccess)
            LogRel2(("Warning! Something went wrong in attempt to turn %s HID device led (error %d)!\n", ((fEnabled) ? "on" : "off"), rc));
        else
            LogRel2(("Led (%d) is turned %s\n", (int)IOHIDElementGetUsage(element), ((fEnabled) ? "on" : "off")));

        CFRelease(valueRef);
    }

    return rc;
}

/** Get state of a particular led. */
static int darwinLedElementGetValue(IOHIDDeviceRef hidDevice, IOHIDElementRef element, bool *fEnabled)
{
    /* Try to resume suspended keyboard devices. Abort if failed in order to avoid GUI freezes. */
    int rc1 = SUPR3ResumeSuspendedKeyboards();
    if (RT_FAILURE(rc1))
        return rc1;

    IOHIDValueRef valueRef;
    IOReturn rc = IOHIDDeviceGetValue(hidDevice, element, &valueRef);
    if (rc == kIOReturnSuccess)
    {
        CFIndex integerValue = IOHIDValueGetIntegerValue(valueRef);
        switch (integerValue)
        {
            case 0:
                *fEnabled = false;
                break;
            case 1:
                *fEnabled = true;
                break;
            default:
                rc = kIOReturnError;
        }

        /*CFRelease(valueRef); - IOHIDDeviceGetValue does not return a reference, so no need to release it. */
    }

    return rc;
}

/** Set corresponding states from NumLock, CapsLock and ScrollLock leds. */
static int darwinSetDeviceLedsState(IOHIDDeviceRef hidDevice, CFDictionaryRef elementMatchingDict,
                                    bool fNumLockOn, bool fCapsLockOn, bool fScrollLockOn)
{
    CFArrayRef matchingElementsArrayRef;
    int        rc2 = 0;

    matchingElementsArrayRef = IOHIDDeviceCopyMatchingElements(hidDevice, elementMatchingDict, kIOHIDOptionsTypeNone);
    if (matchingElementsArrayRef)
    {
        CFIndex cElements = CFArrayGetCount(matchingElementsArrayRef);

        /* Cycle though all the elements we found */
        for (CFIndex i = 0; i < cElements; i++)
        {
            IOHIDElementRef element = (IOHIDElementRef)CFArrayGetValueAtIndex(matchingElementsArrayRef, i);
            uint32_t        usage   = IOHIDElementGetUsage(element);
            int             rc = 0;

            switch (usage)
            {
                case kHIDUsage_LED_NumLock:
                    rc = darwinLedElementSetValue(hidDevice, element, fNumLockOn);
                    break;

                case kHIDUsage_LED_CapsLock:
                    rc = darwinLedElementSetValue(hidDevice, element, fCapsLockOn);
                    break;
                case kHIDUsage_LED_ScrollLock:
                    rc = darwinLedElementSetValue(hidDevice, element, fScrollLockOn);
                    break;
            }
            if (rc != 0)
            {
                LogRel2(("Failed to set led (%d) state\n", (int)IOHIDElementGetUsage(element)));
                rc2 = kIOReturnError;
            }
        }

        CFRelease(matchingElementsArrayRef);
    }

    return rc2;
}

/** Get corresponding states for NumLock, CapsLock and ScrollLock leds. */
static int darwinGetDeviceLedsState(IOHIDDeviceRef hidDevice, CFDictionaryRef elementMatchingDict,
                                    bool *fNumLockOn, bool *fCapsLockOn, bool *fScrollLockOn)
{
    CFArrayRef matchingElementsArrayRef;
    int        rc2 = 0;

    matchingElementsArrayRef = IOHIDDeviceCopyMatchingElements(hidDevice, elementMatchingDict, kIOHIDOptionsTypeNone);
    if (matchingElementsArrayRef)
    {
        CFIndex cElements = CFArrayGetCount(matchingElementsArrayRef);

        /* Cycle though all the elements we found */
        for (CFIndex i = 0; i < cElements; i++)
        {
            IOHIDElementRef element = (IOHIDElementRef)CFArrayGetValueAtIndex(matchingElementsArrayRef, i);
            uint32_t        usage   = IOHIDElementGetUsage(element);
            int             rc = 0;

            switch (usage)
            {
                case kHIDUsage_LED_NumLock:
                    rc = darwinLedElementGetValue(hidDevice, element, fNumLockOn);
                    break;

                case kHIDUsage_LED_CapsLock:
                    rc = darwinLedElementGetValue(hidDevice, element, fCapsLockOn);
                    break;
                case kHIDUsage_LED_ScrollLock:
                    rc = darwinLedElementGetValue(hidDevice, element, fScrollLockOn);
                    break;
            }
            if (rc != 0)
            {
                LogRel2(("Failed to get led (%d) state\n", (int)IOHIDElementGetUsage(element)));
                rc2 = kIOReturnError;
            }
        }

        CFRelease(matchingElementsArrayRef);
    }

    return rc2;
}

/** Get integer property of HID device */
static uint32_t darwinQueryIntProperty(IOHIDDeviceRef pHidDeviceRef, CFStringRef pProperty)
{
    CFTypeRef pNumberRef;
    uint32_t  value = 0;

    AssertReturn(pHidDeviceRef, 0);
    AssertReturn(pProperty, 0);

    pNumberRef = IOHIDDeviceGetProperty(pHidDeviceRef, pProperty);
    if (pNumberRef)
    {
        if (CFGetTypeID(pNumberRef) == CFNumberGetTypeID())
        {
            if (CFNumberGetValue((CFNumberRef)pNumberRef, kCFNumberSInt32Type, &value))
                return value;
        }
    }

    return 0;
}

/** Get HID Vendor ID */
static uint32_t darwinHidVendorId(IOHIDDeviceRef pHidDeviceRef)
{
    return darwinQueryIntProperty(pHidDeviceRef, CFSTR(kIOHIDVendorIDKey));
}

/** Get HID Product ID */
static uint32_t darwinHidProductId(IOHIDDeviceRef pHidDeviceRef)
{
    return darwinQueryIntProperty(pHidDeviceRef, CFSTR(kIOHIDProductIDKey));
}

/** Get HID Location ID */
static uint32_t darwinHidLocationId(IOHIDDeviceRef pHidDeviceRef)
{
    return darwinQueryIntProperty(pHidDeviceRef, CFSTR(kIOHIDLocationIDKey));
}

/** Some keyboard devices might freeze after LEDs manipulation. We filter out such devices here.
  * In the list below, devices that known to have such issues. If you want to add new device,
  * then add it here. Currently, we only filter devices by Vendor ID.
  * In future it might make sense to take Product ID into account as well. */
static bool darwinHidDeviceSupported(IOHIDDeviceRef pHidDeviceRef)
{
#ifndef VBOX_WITHOUT_KBD_LEDS_SYNC_FILTERING
    bool     fSupported = true;
    uint32_t vendorId = darwinHidVendorId(pHidDeviceRef);
    uint32_t productId = darwinHidProductId(pHidDeviceRef);

    if (vendorId == 0x05D5)      /* Genius */
    {
        if (productId == 0x8001) /* GK-04008/C keyboard */
            fSupported = false;
    }
    if (vendorId == 0xE6A)       /* Megawin Technology */
    {
        if (productId == 0x6001) /* Japanese flexible keyboard */
            fSupported = false;
    }

    LogRel2(("HID device [VendorID=0x%X, ProductId=0x%X] %s in the list of supported devices.\n", vendorId, productId, (fSupported ? "is" : "is not")));

    return fSupported;
#else /* !VBOX_WITH_KBD_LEDS_SYNC_FILTERING */
    return true;
#endif
}

/** IOKit key press callback helper: take care about key-down event.
  * This code should be executed within a critical section under pHidState->fifoEventQueueLock. */
static void darwinHidInputCbKeyDown(VBoxKbdState_t *pKbd, uint32_t iKeyCode, VBoxHidsState_t *pHidState)
{
    VBoxKbdEvent_t *pEvent = (VBoxKbdEvent_t *)malloc(sizeof(VBoxKbdEvent_t));

    if (pEvent)
    {
        /* Queue Key-Down event. */
        pEvent->tsKeyDown = RTTimeSystemMilliTS();
        pEvent->pKbd      = pKbd;
        pEvent->iKeyCode  = iKeyCode;

        CFArrayAppendValue(pHidState->pFifoEventQueue, (void *)pEvent);

        LogRel2(("IOHID: KBD %d: Modifier Key-Down event\n", (int)pKbd->idxPosition));
    }
    else
        LogRel2(("IOHID: Modifier Key-Up event. Unable to find memory for KBD %d event\n", (int)pKbd->idxPosition));
}

/** IOkit and Carbon key press callbacks helper: CapsLock timeout checker.
  *
  * Returns FALSE if CAPS LOCK timeout not occurred and its state still was not switched (Apple kbd).
  * Returns TRUE if CAPS LOCK timeout occurred and its state was switched (Apple kbd).
  * Returns TRUE for non-Apple kbd. */
static bool darwinKbdCapsEventMatches(VBoxKbdEvent_t *pEvent, bool fCapsLed)
{
    // CapsLock timeout is only applicable if conditions
    // below are satisfied:
    //
    // a) Key pressed on Apple keyboard
    // b) CapsLed is OFF at the moment when CapsLock key is pressed

    bool fAppleKeyboard = (pEvent->pKbd->cCapsLockTimeout > 0);

    /* Apple keyboard */
    if (fAppleKeyboard && !fCapsLed)
    {
        uint64_t tsDiff = RTTimeSystemMilliTS() - pEvent->tsKeyDown;
        if (tsDiff < pEvent->pKbd->cCapsLockTimeout)
            return false;
    }

    return true;
}

/** IOKit key press callback helper: take care about key-up event.
  * This code should be executed within a critical section under pHidState->fifoEventQueueLock. */
static void darwinHidInputCbKeyUp(VBoxKbdState_t *pKbd, uint32_t iKeyCode, VBoxHidsState_t *pHidState)
{
    CFIndex         iQueue = 0;
    VBoxKbdEvent_t *pEvent = NULL;

    // Key-up event assumes that key-down event occured previously. If so, an event
    // data should be in event queue. Attempt to find it.
    for (CFIndex i = 0; i < CFArrayGetCount(pHidState->pFifoEventQueue); i++)
    {
        VBoxKbdEvent_t *pCachedEvent = (VBoxKbdEvent_t *)CFArrayGetValueAtIndex(pHidState->pFifoEventQueue, i);

        if (pCachedEvent && pCachedEvent->pKbd == pKbd && pCachedEvent->iKeyCode == iKeyCode)
        {
            pEvent = pCachedEvent;
            iQueue = i;
            break;
        }
    }

    /* Event found. */
    if (pEvent)
    {
        // NUM LOCK should not have timeout and its press should immidiately trigger Carbon callback.
        // Therefore, if it is still in queue this is a problem because it was not handled by Carbon callback.
        // This mean that NUM LOCK is most likely out of sync.
        if (iKeyCode == kHIDUsage_KeypadNumLock)
        {
            LogRel2(("IOHID: KBD %d: Modifier Key-Up event. Key-Down event was not habdled by Carbon callback. "
                "NUM LOCK is most likely out of sync\n", (int)pKbd->idxPosition));
        }
        else if (iKeyCode == kHIDUsage_KeyboardCapsLock)
        {
            // If CAPS LOCK key-press event still not match CAPS LOCK timeout criteria, Carbon callback
            // should not be triggered for this event at all. Threfore, event should be removed from queue.
            if (!darwinKbdCapsEventMatches(pEvent, pHidState->guestState.fCapsLockOn))
            {
                CFArrayRemoveValueAtIndex(pHidState->pFifoEventQueue, iQueue);

                LogRel2(("IOHID: KBD %d: Modifier Key-Up event on Apple keyboard. Key-Down event was triggered %llu ms "
                    "ago. Carbon event should not be triggered, removed from queue\n", (int)pKbd->idxPosition,
                    RTTimeSystemMilliTS() - pEvent->tsKeyDown));
                free(pEvent);
            }
            else
            {
                // CAPS LOCK key-press event matches to CAPS LOCK timeout criteria and still present in queue.
                // This might mean that Carbon callback was triggered for this event, but cached keyboard state was not updated.
                // It also might mean that Carbon callback still was not triggered, but it will be soon.
                // Threfore, CAPS LOCK might be out of sync.
                LogRel2(("IOHID: KBD %d: Modifier Key-Up event. Key-Down event was triggered %llu ms "
                    "ago and still was not handled by Carbon callback. CAPS LOCK might out of sync if "
                    "Carbon will not handle this\n", (int)pKbd->idxPosition, RTTimeSystemMilliTS() - pEvent->tsKeyDown));
            }
        }
    }
    else
        LogRel2(("IOHID: KBD %d: Modifier Key-Up event. Modifier state change was "
            "successfully handled by Carbon callback\n", (int)pKbd->idxPosition));
}

/** IOKit key press callback. Triggered before Carbon callback. We remember which keyboard produced a keypress here. */
static void darwinHidInputCallback(void *pData, IOReturn unused, void *unused1, IOHIDValueRef pValueRef)
{
    (void)unused;
    (void)unused1;

    AssertReturnVoid(pValueRef);

    IOHIDElementRef pElementRef = IOHIDValueGetElement(pValueRef);
    AssertReturnVoid(pElementRef);

    uint32_t usage = IOHIDElementGetUsage(pElementRef);

    if (IOHIDElementGetUsagePage(pElementRef) == kHIDPage_KeyboardOrKeypad)    /* Keyboard or keypad event */
        if (usage == kHIDUsage_KeyboardCapsLock ||                             /* CapsLock key has been pressed */
            usage == kHIDUsage_KeypadNumLock)                                  /* ... or NumLock key has been pressed */
        {
            VBoxKbdState_t *pKbd = (VBoxKbdState_t *)pData;

            if (pKbd && pKbd->pParentContainer)
            {
                bool             fKeyDown  = (IOHIDValueGetIntegerValue(pValueRef) == 1);
                VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pKbd->pParentContainer;

                AssertReturnVoid(pHidState);

                if (RT_FAILURE(RTSemMutexRequest(pHidState->fifoEventQueueLock, RT_INDEFINITE_WAIT)))
                    return ;

                /* Handle corresponding event. */
                if (fKeyDown)
                    darwinHidInputCbKeyDown(pKbd, usage, pHidState);
                else
                    darwinHidInputCbKeyUp(pKbd, usage, pHidState);

                RTSemMutexRelease(pHidState->fifoEventQueueLock);
            }
            else
                LogRel2(("IOHID: No KBD: A modifier key has been pressed\n"));
        }
}

/** Carbon key press callback helper: find last occured KBD event in queue
 * (ignoring those events which do not match CAPS LOCK timeout criteria).
 * Once event found, it is removed from queue. This code should be executed
 * within a critical section under pHidState->fifoEventQueueLock. */
static VBoxKbdEvent_t *darwinCarbonCbFindEvent(VBoxHidsState_t *pHidState)
{
    VBoxKbdEvent_t *pEvent = NULL;

    for (CFIndex i = 0; i < CFArrayGetCount(pHidState->pFifoEventQueue); i++)
    {
        pEvent = (VBoxKbdEvent_t *)CFArrayGetValueAtIndex(pHidState->pFifoEventQueue, i);

        /* Paranoia: skip potentially dangerous data items. */
        if (!pEvent || !pEvent->pKbd) continue;

        if ( pEvent->iKeyCode == kHIDUsage_KeypadNumLock
         || (pEvent->iKeyCode == kHIDUsage_KeyboardCapsLock && darwinKbdCapsEventMatches(pEvent, pHidState->guestState.fCapsLockOn)))
        {
            /* Found one. Remove it from queue. */
            CFArrayRemoveValueAtIndex(pHidState->pFifoEventQueue, i);

            LogRel2(("CARBON: Found event in queue: %d (KBD %d, tsKeyDown=%llu, pressed %llu ms ago)\n", (int)i,
                (int)pEvent->pKbd->idxPosition, pEvent->tsKeyDown, RTTimeSystemMilliTS() - pEvent->tsKeyDown));

            break;
        }
        else
            LogRel2(("CARBON: Skip keyboard event from KBD %d, key pressed %llu ms ago\n",
                (int)pEvent->pKbd->idxPosition, RTTimeSystemMilliTS() - pEvent->tsKeyDown));

        pEvent = NULL;
    }

    return pEvent;
}

/** Carbon key press callback. Triggered after IOKit callback. */
static CGEventRef darwinCarbonCallback(CGEventTapProxy unused, CGEventType unused1, CGEventRef pEventRef, void *pData)
{
    (void)unused;
    (void)unused1;

    CGEventFlags fMask = CGEventGetFlags(pEventRef);
    bool         fCaps = (bool)(fMask & NX_ALPHASHIFTMASK);
    bool         fNum  = (bool)(fMask & NX_NUMERICPADMASK);
    CGKeyCode    key   = CGEventGetIntegerValueField(pEventRef, kCGKeyboardEventKeycode);

    VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pData;
    AssertReturn(pHidState, pEventRef);

    if (RT_FAILURE(RTSemMutexRequest(pHidState->fifoEventQueueLock, RT_INDEFINITE_WAIT)))
        return pEventRef;

    if (key == kHIDUsage_KeyboardCapsLock ||
        key == kHIDUsage_KeypadNumLock)
    {
        /* Attempt to find an event queued by IOKit callback. */
        VBoxKbdEvent_t *pEvent = darwinCarbonCbFindEvent(pHidState);
        if (pEvent)
        {
            VBoxKbdState_t *pKbd = pEvent->pKbd;

            LogRel2(("CARBON: KBD %d: caps=%s, num=%s. tsKeyDown=%llu, tsKeyUp=%llu [tsDiff=%llu ms]. %d events in queue.\n",
                (int)pKbd->idxPosition, VBOX_BOOL_TO_STR_STATE(fCaps), VBOX_BOOL_TO_STR_STATE(fNum),
                pEvent->tsKeyDown, RTTimeSystemMilliTS(), RTTimeSystemMilliTS() - pEvent->tsKeyDown,
                CFArrayGetCount(pHidState->pFifoEventQueue)));

            pKbd->LED.fCapsLockOn = fCaps;
            pKbd->LED.fNumLockOn  = fNum;

            /* Silently resync last touched KBD device */
            if (pHidState)
            {
                CFDictionaryRef elementMatchingDict = darwinQueryLedElementMatchingDictionary();
                if (elementMatchingDict)
                {
                    (void)darwinSetDeviceLedsState(pKbd->pDevice,
                                                   elementMatchingDict,
                                                   pHidState->guestState.fNumLockOn,
                                                   pHidState->guestState.fCapsLockOn,
                                                   pHidState->guestState.fScrollLockOn);

                    CFRelease(elementMatchingDict);
                }
            }

            free(pEvent);
        }
        else
            LogRel2(("CARBON: No KBD to take care when modifier key has been pressed: caps=%s, num=%s (%d events in queue)\n",
                VBOX_BOOL_TO_STR_STATE(fCaps), VBOX_BOOL_TO_STR_STATE(fNum), CFArrayGetCount(pHidState->pFifoEventQueue)));
    }

    RTSemMutexRelease(pHidState->fifoEventQueueLock);

    return pEventRef;
}

/** Helper function to obtain interface for IOUSBInterface IOService. */
static IOUSBDeviceInterface ** darwinQueryUsbHidInterfaceInterface(io_service_t service)
{
    kern_return_t         rc;
    IOCFPlugInInterface **ppPluginInterface = NULL;
    SInt32                iScore;

    rc = IOCreatePlugInInterfaceForService(service, kIOUSBInterfaceUserClientTypeID,
                                           kIOCFPlugInInterfaceID, &ppPluginInterface, &iScore);

    if (rc == kIOReturnSuccess && ppPluginInterface != NULL)
    {
        IOUSBDeviceInterface **ppUsbDeviceInterface = NULL;

        rc = (*ppPluginInterface)->QueryInterface(ppPluginInterface, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
                                                  (LPVOID *)&ppUsbDeviceInterface);
        IODestroyPlugInInterface(ppPluginInterface);

        if (rc == kIOReturnSuccess && ppUsbDeviceInterface != NULL)
            return ppUsbDeviceInterface;
        else
            LogRel2(("Failed to query plugin interface for USB device\n"));

    }
    else
        LogRel2(("Failed to create plugin interface for USB device\n"));

    return NULL;
}

/** Helper function for IOUSBInterface IOService general interest notification callback: resync LEDs. */
static void darwinUsbHidResyncLeds(VBoxKbdState_t *pKbd)
{
    AssertReturnVoid(pKbd);

    VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pKbd->pParentContainer;
    CFDictionaryRef  elementMatchingDict = darwinQueryLedElementMatchingDictionary();
    if (elementMatchingDict)
    {
        LogRel2(("Do HID device resync at location 0x%X \n", pKbd->idLocation));
        (void)darwinSetDeviceLedsState(pKbd->pDevice, elementMatchingDict,
            pHidState->guestState.fNumLockOn, pHidState->guestState.fCapsLockOn, pHidState->guestState.fScrollLockOn);
        CFRelease(elementMatchingDict);
    }
}

/** IOUSBInterface IOService general interest notification callback. When we receive it, we do
 * silently resync kbd which has just changed its state. */
static void darwinUsbHidGeneralInterestCb(void *pData, io_service_t unused1, natural_t msg, void *unused2)
{
    NOREF(unused1);
    NOREF(unused2);

    AssertReturnVoid(pData);
    VBoxKbdState_t *pKbd = (VBoxKbdState_t *)pData;

    switch (msg)
    {
        case kIOUSBMessagePortHasBeenSuspended:
            {
                LogRel2(("IOUSBInterface IOService general interest notification kIOUSBMessagePortHasBeenSuspended for KBD %d (Location ID: 0x%X)\n",
                         (int)(pKbd->idxPosition), pKbd->idLocation));
                break;
            }

        case kIOUSBMessagePortHasBeenResumed:
            {
                LogRel2(("IOUSBInterface IOService general interest notification kIOUSBMessagePortHasBeenResumed for KBD %d (Location ID: 0x%X)\n",
                         (int)(pKbd->idxPosition), pKbd->idLocation));
                break;
            }

        case kIOUSBMessagePortHasBeenReset:
            {
                LogRel2(("IOUSBInterface IOService general interest notification kIOUSBMessagePortHasBeenReset for KBD %d (Location ID: 0x%X)\n",
                         (int)(pKbd->idxPosition), pKbd->idLocation));
                darwinUsbHidResyncLeds(pKbd);
                break;
            }

        case kIOUSBMessageCompositeDriverReconfigured:
            {
                LogRel2(("IOUSBInterface IOService general interest notification kIOUSBMessageCompositeDriverReconfigured for KBD %d (Location ID: 0x%X)\n",
                         (int)(pKbd->idxPosition), pKbd->idLocation));
                break;
            }

        case kIOMessageServiceWasClosed:
            {
                LogRel2(("IOUSBInterface IOService general interest notification kIOMessageServiceWasClosed for KBD %d (Location ID: 0x%X)\n",
                         (int)(pKbd->idxPosition), pKbd->idLocation));
                break;
            }

        default:
            LogRel2(("IOUSBInterface IOService general interest notification 0x%X for KBD %d (Location ID: 0x%X)\n",
                     msg, (int)(pKbd->idxPosition), pKbd->idLocation));
    }
}

/** Get pre-cached KBD device by its Location ID. */
static VBoxKbdState_t *darwinUsbHidQueryKbdByLocationId(uint32_t idLocation, VBoxHidsState_t *pHidState)
{
    AssertReturn(pHidState, NULL);

    for (CFIndex i = 0; i < CFArrayGetCount(pHidState->pDeviceCollection); i++)
    {
        VBoxKbdState_t *pKbd = (VBoxKbdState_t *)CFArrayGetValueAtIndex(pHidState->pDeviceCollection, i);
        if (pKbd && pKbd->idLocation == idLocation)
        {
            LogRel2(("Lookup USB HID Device by location ID 0x%X: found match\n", idLocation));
            return pKbd;
        }
    }

    LogRel2(("Lookup USB HID Device by location ID 0x%X: no matches found:\n", idLocation));

    return NULL;
}

/** IOUSBInterface IOService match notification callback: issued when IOService instantinates.
 * We subscribe to general interest notifications for available IOServices here. */
static void darwinUsbHidDeviceMatchCb(void *pData, io_iterator_t iter)
{
    AssertReturnVoid(pData);

    io_service_t     service;
    VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pData;

    while ((service = IOIteratorNext(iter)))
    {
        kern_return_t         rc;

        IOUSBDeviceInterface **ppUsbDeviceInterface = darwinQueryUsbHidInterfaceInterface(service);

        if (ppUsbDeviceInterface)
        {
            uint8_t  idDeviceClass, idDeviceSubClass;
            UInt32   idLocation;

            rc = (*ppUsbDeviceInterface)->GetLocationID    (ppUsbDeviceInterface,  &idLocation);       AssertMsg(rc == 0, ("Failed to get Location ID"));
            rc = (*ppUsbDeviceInterface)->GetDeviceClass   (ppUsbDeviceInterface,  &idDeviceClass);    AssertMsg(rc == 0, ("Failed to get Device Class"));
            rc = (*ppUsbDeviceInterface)->GetDeviceSubClass(ppUsbDeviceInterface,  &idDeviceSubClass); AssertMsg(rc == 0, ("Failed to get Device Subclass"));

            if (idDeviceClass == kUSBHIDInterfaceClass && idDeviceSubClass == kUSBHIDBootInterfaceSubClass)
            {
                VBoxKbdState_t *pKbd = darwinUsbHidQueryKbdByLocationId((uint32_t)idLocation, pHidState);

                if (pKbd)
                {
                    rc = IOServiceAddInterestNotification(pHidState->pNotificationPrortRef, service, kIOGeneralInterest,
                        darwinUsbHidGeneralInterestCb, pKbd, &pHidState->pUsbHidGeneralInterestNotify);

                    AssertMsg(rc == 0, ("Failed to add general interest notification"));

                    LogRel2(("Found HID device at location 0x%X: class 0x%X, subclass 0x%X\n", idLocation, idDeviceClass, idDeviceSubClass));
                }
            }

            rc = (*ppUsbDeviceInterface)->Release(ppUsbDeviceInterface); AssertMsg(rc == 0, ("Failed to release USB device interface"));
        }

        IOObjectRelease(service);
    }
}

/** Register IOUSBInterface IOService match notification callback in order to recync KBD
 * device when it reports state change. */
static int darwinUsbHidSubscribeInterestNotifications(VBoxHidsState_t *pHidState)
{
    AssertReturn(pHidState, kIOReturnBadArgument);

    int rc = kIOReturnNoMemory;
    CFDictionaryRef pDictionary = IOServiceMatching(kIOUSBInterfaceClassName);

    if (pDictionary)
    {
        pHidState->pNotificationPrortRef = IONotificationPortCreate(kIOMasterPortDefault);
        if (pHidState->pNotificationPrortRef)
        {
            CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(pHidState->pNotificationPrortRef), kCFRunLoopDefaultMode);

            rc = IOServiceAddMatchingNotification(pHidState->pNotificationPrortRef, kIOMatchedNotification,
                                                  pDictionary, darwinUsbHidDeviceMatchCb, pHidState,
                                                  &pHidState->pUsbHidDeviceMatchNotify);

            if (rc == kIOReturnSuccess && pHidState->pUsbHidDeviceMatchNotify != IO_OBJECT_NULL)
            {
                darwinUsbHidDeviceMatchCb(pHidState, pHidState->pUsbHidDeviceMatchNotify);
                LogRel2(("Successfully subscribed to IOUSBInterface IOService match notifications\n"));
            }
            else
                LogRel2(("Failed to subscribe to IOUSBInterface IOService match notifications: subscription error 0x%X\n", rc));
        }
        else
            LogRel2(("Failed to subscribe to IOUSBInterface IOService match notifications: unable to create notification port\n"));
    }
    else
        LogRel2(("Failed to subscribe to IOUSBInterface IOService match notifications: no memory\n"));

    return rc;
}

/** Remove IOUSBInterface IOService match notification subscription. */
static void darwinUsbHidUnsubscribeInterestNotifications(VBoxHidsState_t *pHidState)
{
    AssertReturnVoid(pHidState);

    CFRunLoopRemoveSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(pHidState->pNotificationPrortRef), kCFRunLoopDefaultMode);
    IONotificationPortDestroy(pHidState->pNotificationPrortRef);
    pHidState->pNotificationPrortRef = NULL;

    LogRel2(("Successfully un-subscribed from IOUSBInterface IOService match notifications\n"));
}

/** This callback is called when user physically removes HID device. We remove device from cache here. */
static void darwinHidRemovalCallback(void *pData, IOReturn unused, void *unused1)
{
    (void)unused;
    (void)unused1;

    VBoxKbdState_t  *pKbd      = (VBoxKbdState_t  *)pData;                  AssertReturnVoid(pKbd);
    VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pKbd->pParentContainer; AssertReturnVoid(pHidState);

    AssertReturnVoid(pHidState->pDeviceCollection);

    LogRel2(("Forget KBD %d\n", (int)pKbd->idxPosition));

    //if (RT_FAILURE(RTSemMutexRequest(pHidState->fifoEventQueueLock, RT_INDEFINITE_WAIT)))
    //    return ;

    CFArrayRemoveValueAtIndex(pHidState->pDeviceCollection, pKbd->idxPosition);
    free(pKbd);

    //RTSemMutexRelease(pHidState->fifoEventQueueLock);
}

/** Check if we already cached given device */
static bool darwinIsDeviceInCache(VBoxHidsState_t *pState, IOHIDDeviceRef pDevice)
{
    AssertReturn(pState, false);
    AssertReturn(pState->pDeviceCollection, false);

    for (CFIndex i = 0; i < CFArrayGetCount(pState->pDeviceCollection); i++)
    {
        VBoxKbdState_t *pKbd = (VBoxKbdState_t *)CFArrayGetValueAtIndex(pState->pDeviceCollection, i);
        if (pKbd && pKbd->pDevice == pDevice)
            return true;
    }

    return false;
}

/** Add device to cache. */
static void darwinHidAddDevice(VBoxHidsState_t *pHidState, IOHIDDeviceRef pDevice, bool fApplyLedState)
{
    int rc;

    if (!darwinIsDeviceInCache(pHidState, pDevice))
    {
        if (IOHIDDeviceConformsTo(pDevice, kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard)
         && darwinHidDeviceSupported(pDevice))
        {
            VBoxKbdState_t *pKbd = (VBoxKbdState_t *)malloc(sizeof(VBoxKbdState_t));
            if (pKbd)
            {
                pKbd->pDevice = pDevice;
                pKbd->pParentContainer = (void *)pHidState;
                pKbd->idxPosition = CFArrayGetCount(pHidState->pDeviceCollection);
                pKbd->idLocation = darwinHidLocationId(pDevice);

                // Some Apple keyboards have CAPS LOCK key timeout. According to corresponding
                // kext plist files, it is equals to 75 ms. For such devices we only add info into our FIFO event
                // queue if the time between Key-Down and Key-Up events >= 75 ms.
                pKbd->cCapsLockTimeout = (darwinHidVendorId(pKbd->pDevice) == kIOUSBVendorIDAppleComputer) ? 75 : 0;

                CFDictionaryRef elementMatchingDict = darwinQueryLedElementMatchingDictionary();
                if (elementMatchingDict)
                {
                    rc = darwinGetDeviceLedsState(pKbd->pDevice,
                                                  elementMatchingDict,
                                                  &pKbd->LED.fNumLockOn,
                                                  &pKbd->LED.fCapsLockOn,
                                                  &pKbd->LED.fScrollLockOn);

                    // This should never happen, but if happened -- mark all the leds of current
                    // device as turned OFF.
                    if (rc != 0)
                    {
                        LogRel2(("Unable to get leds state for device %d. Mark leds as turned off\n", (int)(pKbd->idxPosition)));
                        pKbd->LED.fNumLockOn    =
                        pKbd->LED.fCapsLockOn   =
                        pKbd->LED.fScrollLockOn = false;
                    }

                    /* Register per-device removal callback */
                    IOHIDDeviceRegisterRemovalCallback(pKbd->pDevice, darwinHidRemovalCallback, (void *)pKbd);

                    /* Register per-device input callback */
                    IOHIDDeviceRegisterInputValueCallback(pKbd->pDevice, darwinHidInputCallback, (void *)pKbd);
                    IOHIDDeviceScheduleWithRunLoop(pKbd->pDevice, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);

                    CFArrayAppendValue(pHidState->pDeviceCollection, (void *)pKbd);

                    LogRel2(("Saved LEDs for KBD %d (%p): fNumLockOn=%s, fCapsLockOn=%s, fScrollLockOn=%s\n",
                        (int)pKbd->idxPosition, pKbd, VBOX_BOOL_TO_STR_STATE(pKbd->LED.fNumLockOn), VBOX_BOOL_TO_STR_STATE(pKbd->LED.fCapsLockOn),
                        VBOX_BOOL_TO_STR_STATE(pKbd->LED.fScrollLockOn)));

                    if (fApplyLedState)
                    {
                        rc = darwinSetDeviceLedsState(pKbd->pDevice, elementMatchingDict, pHidState->guestState.fNumLockOn,
                                                      pHidState->guestState.fCapsLockOn, pHidState->guestState.fScrollLockOn);
                        if (rc != 0)
                            LogRel2(("Unable to apply guest state to newly attached device\n"));
                    }

                    CFRelease(elementMatchingDict);
                    return;
                }

                free(pKbd);
            }
        }
    }
}

/** This callback is called when new HID device discovered by IOHIDManager. We add devices to cache here and only here! */
static void darwinHidMatchingCallback(void *pData, IOReturn unused, void *unused1, IOHIDDeviceRef pDevice)
{
    (void)unused;
    (void)unused1;

    VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pData;

    AssertReturnVoid(pHidState);
    AssertReturnVoid(pHidState->pDeviceCollection);
    AssertReturnVoid(pDevice);

    darwinHidAddDevice(pHidState, pDevice, true);
}

/** Register Carbon key press callback. */
static int darwinAddCarbonHandler(VBoxHidsState_t *pHidState)
{
    CFMachPortRef pTapRef;
    CGEventMask   fMask = CGEventMaskBit(kCGEventFlagsChanged);

    AssertReturn(pHidState, kIOReturnError);

    /* Create FIFO event queue for keyboard events */
    pHidState->pFifoEventQueue = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
    AssertReturn(pHidState->pFifoEventQueue, kIOReturnError);

    /* Create Lock for FIFO event queue */
    if (RT_FAILURE(RTSemMutexCreate(&pHidState->fifoEventQueueLock)))
    {
        LogRel2(("Unable to create Lock for FIFO event queue\n"));
        CFRelease(pHidState->pFifoEventQueue);
        pHidState->pFifoEventQueue = NULL;
        return kIOReturnError;
    }

    pTapRef = CGEventTapCreate(kCGSessionEventTap, kCGTailAppendEventTap, kCGEventTapOptionDefault, fMask,
                               darwinCarbonCallback, (void *)pHidState);
    if (pTapRef)
    {
        CFRunLoopSourceRef pLoopSourceRef;
        pLoopSourceRef = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, pTapRef, 0);
        if (pLoopSourceRef)
        {
            CFRunLoopAddSource(CFRunLoopGetCurrent(), pLoopSourceRef, kCFRunLoopDefaultMode);
            CGEventTapEnable(pTapRef, true);

            pHidState->pTapRef = pTapRef;
            pHidState->pLoopSourceRef = pLoopSourceRef;

            return 0;
        }
        else
            LogRel2(("Unable to create a loop source\n"));

        CFRelease(pTapRef);
    }
    else
        LogRel2(("Unable to create an event tap\n"));

    return kIOReturnError;
}

/** Remove Carbon key press callback. */
static void darwinRemoveCarbonHandler(VBoxHidsState_t *pHidState)
{
    AssertReturnVoid(pHidState);
    AssertReturnVoid(pHidState->pTapRef);
    AssertReturnVoid(pHidState->pLoopSourceRef);
    AssertReturnVoid(pHidState->pFifoEventQueue);

    CGEventTapEnable(pHidState->pTapRef, false);
    CFRunLoopRemoveSource(CFRunLoopGetCurrent(), pHidState->pLoopSourceRef, kCFRunLoopDefaultMode);
    CFRelease(pHidState->pLoopSourceRef);
    CFRelease(pHidState->pTapRef);

    RTSemMutexRequest(pHidState->fifoEventQueueLock, RT_INDEFINITE_WAIT);
    CFRelease(pHidState->pFifoEventQueue);
    pHidState->pFifoEventQueue = NULL;
    RTSemMutexRelease(pHidState->fifoEventQueueLock);

    RTSemMutexDestroy(pHidState->fifoEventQueueLock);
}

#endif /* !VBOX_WITH_KBD_LEDS_SYNC */


void *DarwinHidDevicesKeepLedsState()
{
#ifdef VBOX_WITH_KBD_LEDS_SYNC
    IOReturn         rc;
    VBoxHidsState_t *pHidState;

    pHidState = (VBoxHidsState_t *)malloc(sizeof(VBoxHidsState_t));
    AssertReturn(pHidState, NULL);

    pHidState->hidManagerRef = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
    if (pHidState->hidManagerRef)
    {
        CFDictionaryRef deviceMatchingDictRef = darwinQueryLedDeviceMatchingDictionary();
        if (deviceMatchingDictRef)
        {
            IOHIDManagerScheduleWithRunLoop(pHidState->hidManagerRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
            IOHIDManagerSetDeviceMatching(pHidState->hidManagerRef, deviceMatchingDictRef);

            rc = IOHIDManagerOpen(pHidState->hidManagerRef, kIOHIDOptionsTypeNone);
            if (rc == kIOReturnSuccess)
            {
                pHidState->pDeviceCollection = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
                if (pHidState->pDeviceCollection)
                {
                    if (darwinAddCarbonHandler(pHidState) == 0)
                    {
                        /* Populate cache with HID devices */
                        CFSetRef pDevicesSet = IOHIDManagerCopyDevices(pHidState->hidManagerRef);
                        if (pDevicesSet)
                        {
                            CFIndex cDevices = CFSetGetCount(pDevicesSet);

                            IOHIDDeviceRef *ppDevices = (IOHIDDeviceRef *)malloc((size_t)cDevices * sizeof(IOHIDDeviceRef));
                            if (ppDevices)
                            {
                                CFSetGetValues(pDevicesSet, (const void **)ppDevices);
                                for (CFIndex i= 0; i < cDevices; i++)
                                    darwinHidAddDevice(pHidState, (IOHIDDeviceRef)ppDevices[i], false);

                                free(ppDevices);
                            }

                            CFRelease(pDevicesSet);
                        }

                        IOHIDManagerRegisterDeviceMatchingCallback(pHidState->hidManagerRef, darwinHidMatchingCallback, (void *)pHidState);

                        CFRelease(deviceMatchingDictRef);

                        /* This states should be set on broadcast */
                        pHidState->guestState.fNumLockOn =
                        pHidState->guestState.fCapsLockOn =
                        pHidState->guestState.fScrollLockOn = false;

                        /* Finally, subscribe to USB HID notifications in order to prevent LED artifacts on
                           automatic power management */
                        if (darwinUsbHidSubscribeInterestNotifications(pHidState) == 0)
                            return pHidState;
                    }
                }

                rc = IOHIDManagerClose(pHidState->hidManagerRef, 0);
                if (rc != kIOReturnSuccess)
                    LogRel2(("Warning! Something went wrong in attempt to close HID device manager!\n"));
            }

            CFRelease(deviceMatchingDictRef);
        }

        CFRelease(pHidState->hidManagerRef);
    }

    free(pHidState);

    return NULL;
#else /* !VBOX_WITH_KBD_LEDS_SYNC */
    return NULL;
#endif
}


int DarwinHidDevicesApplyAndReleaseLedsState(void *pState)
{
#ifdef VBOX_WITH_KBD_LEDS_SYNC
    VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pState;
    IOReturn         rc, rc2 = 0;

    AssertReturn(pHidState, kIOReturnError);

    darwinUsbHidUnsubscribeInterestNotifications(pHidState);

    /* Need to unregister Carbon stuff first: */
    darwinRemoveCarbonHandler(pHidState);

    CFDictionaryRef elementMatchingDict = darwinQueryLedElementMatchingDictionary();
    if (elementMatchingDict)
    {
        /* Restore LEDs: */
        for (CFIndex i = 0; i < CFArrayGetCount(pHidState->pDeviceCollection); i++)
        {
            /* Cycle through supported devices only. */
            VBoxKbdState_t *pKbd;
            pKbd = (VBoxKbdState_t *)CFArrayGetValueAtIndex(pHidState->pDeviceCollection, i);

            if (pKbd)
            {
                rc = darwinSetDeviceLedsState(pKbd->pDevice,
                                              elementMatchingDict,
                                              pKbd->LED.fNumLockOn,
                                              pKbd->LED.fCapsLockOn,
                                              pKbd->LED.fScrollLockOn);
                if (rc != 0)
                {
                    LogRel2(("Unable to restore led states for device (%d)!\n", (int)i));
                    rc2 = kIOReturnError;
                }

                IOHIDDeviceUnscheduleFromRunLoop(pKbd->pDevice, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);

                LogRel2(("Restored LEDs for KBD %d (%p): fNumLockOn=%s, fCapsLockOn=%s, fScrollLockOn=%s\n",
                     (int)i, pKbd, VBOX_BOOL_TO_STR_STATE(pKbd->LED.fNumLockOn), VBOX_BOOL_TO_STR_STATE(pKbd->LED.fCapsLockOn),
                     VBOX_BOOL_TO_STR_STATE(pKbd->LED.fScrollLockOn)));

                free(pKbd);
            }
        }

        CFRelease(elementMatchingDict);
    }

    /* Free resources: */
    CFRelease(pHidState->pDeviceCollection);

    rc = IOHIDManagerClose(pHidState->hidManagerRef, 0);
    if (rc != kIOReturnSuccess)
    {
        LogRel2(("Warning! Something went wrong in attempt to close HID device manager!\n"));
        rc2 = kIOReturnError;
    }

    IOHIDManagerUnscheduleFromRunLoop(pHidState->hidManagerRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);

    CFRelease(pHidState->hidManagerRef);

    free(pHidState);

    return rc2;
#else /* !VBOX_WITH_KBD_LEDS_SYNC */
    (void)pState;
    return 0;
#endif /* !VBOX_WITH_KBD_LEDS_SYNC */
}

void DarwinHidDevicesBroadcastLeds(void *pState, bool fNumLockOn, bool fCapsLockOn, bool fScrollLockOn)
{
#ifdef VBOX_WITH_KBD_LEDS_SYNC
    VBoxHidsState_t *pHidState = (VBoxHidsState_t *)pState;
    IOReturn         rc;

    AssertReturnVoid(pHidState);
    AssertReturnVoid(pHidState->pDeviceCollection);

    CFDictionaryRef elementMatchingDict = darwinQueryLedElementMatchingDictionary();
    if (elementMatchingDict)
    {
        LogRel2(("Start LEDs broadcast: fNumLockOn=%s, fCapsLockOn=%s, fScrollLockOn=%s\n",
            VBOX_BOOL_TO_STR_STATE(fNumLockOn), VBOX_BOOL_TO_STR_STATE(fCapsLockOn), VBOX_BOOL_TO_STR_STATE(fScrollLockOn)));

        for (CFIndex i = 0; i < CFArrayGetCount(pHidState->pDeviceCollection); i++)
        {
            /* Cycle through supported devices only. */
            VBoxKbdState_t *pKbd;
            pKbd = (VBoxKbdState_t *)CFArrayGetValueAtIndex(pHidState->pDeviceCollection, i);

            if (pKbd && darwinHidDeviceSupported(pKbd->pDevice))
            {
                rc = darwinSetDeviceLedsState(pKbd->pDevice,
                                              elementMatchingDict,
                                              fNumLockOn,
                                              fCapsLockOn,
                                              fScrollLockOn);
                if (rc != 0)
                    LogRel2(("Unable to restore led states for device (%d)!\n", (int)i));
            }
        }

        LogRel2(("LEDs broadcast completed\n"));

        CFRelease(elementMatchingDict);
    }

    /* Dynamically attached device will use these states: */
    pHidState->guestState.fNumLockOn    = fNumLockOn;
    pHidState->guestState.fCapsLockOn   = fCapsLockOn;
    pHidState->guestState.fScrollLockOn = fScrollLockOn;
#else /* !VBOX_WITH_KBD_LEDS_SYNC */
    (void)fNumLockOn;
    (void)fCapsLockOn;
    (void)fScrollLockOn;
#endif /* !VBOX_WITH_KBD_LEDS_SYNC */
}