VirtualBox

source: vbox/trunk/src/VBox/Frontends/VirtualBox/src/darwin/DarwinKeyboard.cpp@ 6523

Last change on this file since 6523 was 6523, checked in by vboxsync, 17 years ago

Mac OS X: Recognize the fn-key as an modifier key which exists on the various mac books.

  • Property svn:eol-style set to native
File size: 39.3 KB
Line 
1/** @file
2 * Common GUI Library - Darwin Keyboard routines.
3 *
4 * @todo Move this up somewhere so that the two SDL GUIs can use parts of this code too (-HID crap).
5 */
6
7/*
8 * Copyright (C) 2006-2007 innotek GmbH
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19
20
21#define USE_HID_FOR_MODIFIERS
22
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#define LOG_GROUP LOG_GROUP_GUI
28#include "DarwinKeyboard.h"
29#include <iprt/assert.h>
30#include <iprt/asm.h>
31#include <iprt/time.h>
32#include <VBox/log.h>
33#ifdef DEBUG_PRINTF
34# include <iprt/stream.h>
35#endif
36
37#ifdef USE_HID_FOR_MODIFIERS
38# include <mach/mach.h>
39# include <mach/mach_error.h>
40# include <IOKit/IOKitLib.h>
41# include <IOKit/IOCFPlugIn.h>
42# include <IOKit/hid/IOHIDLib.h>
43# include <IOKit/hid/IOHIDUsageTables.h>
44# include <IOKit/usb/USB.h>
45# include <CoreFoundation/CoreFoundation.h>
46#endif
47#include <Carbon/Carbon.h>
48
49__BEGIN_DECLS
50/* Private interface in 10.3 and later. */
51typedef int CGSConnection;
52typedef enum
53{
54 kCGSGlobalHotKeyEnable = 0,
55 kCGSGlobalHotKeyDisable,
56 kCGSGlobalHotKeyInvalid = -1 /* bird */
57} CGSGlobalHotKeyOperatingMode;
58extern CGSConnection _CGSDefaultConnection(void);
59extern CGError CGSGetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode *enmMode);
60extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode enmMode);
61__END_DECLS
62
63
64/*******************************************************************************
65* Defined Constants And Macros *
66*******************************************************************************/
67
68#define QZ_RMETA 0x36
69#define QZ_LMETA 0x37
70#define QZ_LSHIFT 0x38
71#define QZ_CAPSLOCK 0x39
72#define QZ_LALT 0x3A
73#define QZ_LCTRL 0x3B
74#define QZ_RSHIFT 0x3C
75#define QZ_RALT 0x3D
76#define QZ_RCTRL 0x3E
77/* Found the definition of the fn-key in:
78 * http://stuff.mit.edu/afs/sipb/project/darwin/src/modules/IOHIDFamily/IOHIDSystem/IOHIKeyboardMapper.cpp &
79 * http://stuff.mit.edu/afs/sipb/project/darwin/src/modules/AppleADBKeyboard/AppleADBKeyboard.cpp
80 * Maybe we need this in the future.*/
81#define QZ_FN 0x3F
82#define QZ_NUMLOCK 0x47
83
84/** short hand for an extended key. */
85#define K_EX VBOXKEY_EXTENDED
86/** short hand for a modifier key. */
87#define K_MOD VBOXKEY_MODIFIER
88/** short hand for a lock key. */
89#define K_LOCK VBOXKEY_LOCK
90
91#ifdef USE_HID_FOR_MODIFIERS
92
93/** An attempt at catching reference leaks. */
94#define MY_CHECK_CREFS(cRefs) do { AssertMsg(cRefs < 25, ("%ld\n", cRefs)); NOREF(cRefs); } while (0)
95
96#endif
97
98/*******************************************************************************
99* Global Variables *
100*******************************************************************************/
101/**
102 * This is derived partially from SDL_QuartzKeys.h and partially from testing.
103 *
104 * (The funny thing about the virtual scan codes on the mac is that they aren't
105 * offically documented, which is rather silly to say the least. Thus, the need
106 * for looking at SDL and other odd places for docs.)
107 */
108static const uint16_t g_aDarwinToSet1[] =
109{
110 /* set-1 SDL_QuartzKeys.h */
111 0x1e, /* QZ_a 0x00 */
112 0x1f, /* QZ_s 0x01 */
113 0x20, /* QZ_d 0x02 */
114 0x21, /* QZ_f 0x03 */
115 0x23, /* QZ_h 0x04 */
116 0x22, /* QZ_g 0x05 */
117 0x2c, /* QZ_z 0x06 */
118 0x2d, /* QZ_x 0x07 */
119 0x2e, /* QZ_c 0x08 */
120 0x2f, /* QZ_v 0x09 */
121 0x56, /* between lshift and z. 'INT 1'? */
122 0x30, /* QZ_b 0x0B */
123 0x10, /* QZ_q 0x0C */
124 0x11, /* QZ_w 0x0D */
125 0x12, /* QZ_e 0x0E */
126 0x13, /* QZ_r 0x0F */
127 0x15, /* QZ_y 0x10 */
128 0x14, /* QZ_t 0x11 */
129 0x02, /* QZ_1 0x12 */
130 0x03, /* QZ_2 0x13 */
131 0x04, /* QZ_3 0x14 */
132 0x05, /* QZ_4 0x15 */
133 0x07, /* QZ_6 0x16 */
134 0x06, /* QZ_5 0x17 */
135 0x0d, /* QZ_EQUALS 0x18 */
136 0x0a, /* QZ_9 0x19 */
137 0x08, /* QZ_7 0x1A */
138 0x0c, /* QZ_MINUS 0x1B */
139 0x09, /* QZ_8 0x1C */
140 0x0b, /* QZ_0 0x1D */
141 0x1b, /* QZ_RIGHTBRACKET 0x1E */
142 0x18, /* QZ_o 0x1F */
143 0x16, /* QZ_u 0x20 */
144 0x1a, /* QZ_LEFTBRACKET 0x21 */
145 0x17, /* QZ_i 0x22 */
146 0x19, /* QZ_p 0x23 */
147 0x1c, /* QZ_RETURN 0x24 */
148 0x26, /* QZ_l 0x25 */
149 0x24, /* QZ_j 0x26 */
150 0x28, /* QZ_QUOTE 0x27 */
151 0x25, /* QZ_k 0x28 */
152 0x27, /* QZ_SEMICOLON 0x29 */
153 0x2b, /* QZ_BACKSLASH 0x2A */
154 0x33, /* QZ_COMMA 0x2B */
155 0x35, /* QZ_SLASH 0x2C */
156 0x31, /* QZ_n 0x2D */
157 0x32, /* QZ_m 0x2E */
158 0x34, /* QZ_PERIOD 0x2F */
159 0x0f, /* QZ_TAB 0x30 */
160 0x39, /* QZ_SPACE 0x31 */
161 0x29, /* QZ_BACKQUOTE 0x32 */
162 0x0e, /* QZ_BACKSPACE 0x33 */
163 0x9c, /* QZ_IBOOK_ENTER 0x34 */
164 0x01, /* QZ_ESCAPE 0x35 */
165 0x5c|K_EX|K_MOD, /* QZ_RMETA 0x36 */
166 0x5b|K_EX|K_MOD, /* QZ_LMETA 0x37 */
167 0x2a|K_MOD, /* QZ_LSHIFT 0x38 */
168 0x3a|K_LOCK, /* QZ_CAPSLOCK 0x39 */
169 0x38|K_MOD, /* QZ_LALT 0x3A */
170 0x1d|K_MOD, /* QZ_LCTRL 0x3B */
171 0x36|K_MOD, /* QZ_RSHIFT 0x3C */
172 0x38|K_EX|K_MOD, /* QZ_RALT 0x3D */
173 0x1d|K_EX|K_MOD, /* QZ_RCTRL 0x3E */
174 0, /* */
175 0, /* */
176 0x53, /* QZ_KP_PERIOD 0x41 */
177 0, /* */
178 0x37, /* QZ_KP_MULTIPLY 0x43 */
179 0, /* */
180 0x4e, /* QZ_KP_PLUS 0x45 */
181 0, /* */
182 0x45|K_LOCK, /* QZ_NUMLOCK 0x47 */
183 0, /* */
184 0, /* */
185 0, /* */
186 0x35|K_EX, /* QZ_KP_DIVIDE 0x4B */
187 0x1c|K_EX, /* QZ_KP_ENTER 0x4C */
188 0, /* */
189 0x4a, /* QZ_KP_MINUS 0x4E */
190 0, /* */
191 0, /* */
192 0x0d/*?*/, /* QZ_KP_EQUALS 0x51 */
193 0x52, /* QZ_KP0 0x52 */
194 0x4f, /* QZ_KP1 0x53 */
195 0x50, /* QZ_KP2 0x54 */
196 0x51, /* QZ_KP3 0x55 */
197 0x4b, /* QZ_KP4 0x56 */
198 0x4c, /* QZ_KP5 0x57 */
199 0x4d, /* QZ_KP6 0x58 */
200 0x47, /* QZ_KP7 0x59 */
201 0, /* */
202 0x48, /* QZ_KP8 0x5B */
203 0x49, /* QZ_KP9 0x5C */
204 0x7d, /* yen, | (JIS) 0x5D */
205 0x73, /* _, ro (JIS) 0x5E */
206 0, /* */
207 0x3f, /* QZ_F5 0x60 */
208 0x40, /* QZ_F6 0x61 */
209 0x41, /* QZ_F7 0x62 */
210 0x3d, /* QZ_F3 0x63 */
211 0x42, /* QZ_F8 0x64 */
212 0x43, /* QZ_F9 0x65 */
213 0x29, /* Zen/Han (JIS) 0x66 */
214 0x57, /* QZ_F11 0x67 */
215 0x29, /* Zen/Han (JIS) 0x68 */
216 0x37|K_EX, /* QZ_PRINT / F13 0x69 */
217 0x63, /* QZ_F16 0x6A */
218 0x46|K_LOCK, /* QZ_SCROLLOCK 0x6B */
219 0, /* */
220 0x44, /* QZ_F10 0x6D */
221 0x5d|K_EX, /* */
222 0x58, /* QZ_F12 0x6F */
223 0, /* */
224 0/* 0xe1,0x1d,0x45*/, /* QZ_PAUSE 0x71 */
225 0x52|K_EX, /* QZ_INSERT / HELP 0x72 */
226 0x47|K_EX, /* QZ_HOME 0x73 */
227 0x49|K_EX, /* QZ_PAGEUP 0x74 */
228 0x53|K_EX, /* QZ_DELETE 0x75 */
229 0x3e, /* QZ_F4 0x76 */
230 0x4f|K_EX, /* QZ_END 0x77 */
231 0x3c, /* QZ_F2 0x78 */
232 0x51|K_EX, /* QZ_PAGEDOWN 0x79 */
233 0x3b, /* QZ_F1 0x7A */
234 0x4b|K_EX, /* QZ_LEFT 0x7B */
235 0x4d|K_EX, /* QZ_RIGHT 0x7C */
236 0x50|K_EX, /* QZ_DOWN 0x7D */
237 0x48|K_EX, /* QZ_UP 0x7E */
238 0x5e|K_EX, /* QZ_POWER 0x7F */ /* have different break key! */
239};
240
241
242/** Whether we've connected or not. */
243static bool g_fConnectedToCGS = false;
244/** Cached connection. */
245static CGSConnection g_CGSConnection;
246
247
248#ifdef USE_HID_FOR_MODIFIERS
249
250/** The IO Master Port. */
251static mach_port_t g_MasterPort = NULL;
252
253/** Keyboards in the cache. */
254static unsigned g_cKeyboards = 0;
255/** Array of cached keyboard data. */
256static struct KeyboardCacheData
257{
258 /** The device interface. */
259 IOHIDDeviceInterface **ppHidDeviceInterface;
260 /** The queue interface. */
261 IOHIDQueueInterface **ppHidQueueInterface;
262
263 /* cookie translation array. */
264 struct KeyboardCacheCookie
265 {
266 /** The cookie. */
267 IOHIDElementCookie Cookie;
268 /** The corresponding modifier mask. */
269 uint32_t fMask;
270 } aCookies[64];
271 /** Number of cookies in the array. */
272 unsigned cCookies;
273} g_aKeyboards[128];
274/** The keyboard cache creation timestamp. */
275static uint64_t g_u64KeyboardTS = 0;
276
277/** HID queue status. */
278static bool g_fHIDQueueEnabled;
279/** The current modifier mask. */
280static uint32_t g_fHIDModifierMask;
281/** The old modifier mask. */
282static uint32_t g_fOldHIDModifierMask;
283
284#endif /* USE_HID_FOR_MODIFIERS */
285
286
287/*******************************************************************************
288* Internal Functions *
289*******************************************************************************/
290static void darwinBruteForcePropertySearch(CFDictionaryRef DictRef, struct KeyboardCacheData *pKeyboardEntry);
291
292
293
294/**
295 * Converts a darwin (virtual) key code to a set 1 scan code.
296 *
297 * @returns set 1 scan code.
298 * @param uKeyCode The darwin key code.
299 */
300unsigned DarwinKeycodeToSet1Scancode(unsigned uKeyCode)
301{
302 if (uKeyCode >= RT_ELEMENTS(g_aDarwinToSet1))
303 return 0;
304 return g_aDarwinToSet1[uKeyCode];
305}
306
307
308/**
309 * Converts a single modifier to a set 1 scan code.
310 *
311 * @returns Set 1 scan code.
312 * @returns ~0U if more than one modifier is set.
313 * @param fModifiers The darwin modifier mask.
314 */
315unsigned DarwinModifierMaskToSet1Scancode(UInt32 fModifiers)
316{
317 unsigned uScanCode = DarwinModifierMaskToDarwinKeycode(fModifiers);
318 if (uScanCode < RT_ELEMENTS(g_aDarwinToSet1))
319 uScanCode = g_aDarwinToSet1[uScanCode];
320 else
321 Assert(uScanCode == ~0U);
322 return uScanCode;
323}
324
325
326/**
327 * Converts a single modifier to a darwin keycode.
328 *
329 * @returns Darwin keycode.
330 * @returns 0 if none of the support masks were set.
331 * @returns ~0U if more than one modifier is set.
332 * @param fModifiers The darwin modifier mask.
333 */
334unsigned DarwinModifierMaskToDarwinKeycode(UInt32 fModifiers)
335{
336 unsigned uKeyCode;
337
338 /** @todo find symbols for these keycodes... */
339 fModifiers &= shiftKey | rightShiftKey | controlKey | rightControlKey | optionKey | rightOptionKey | cmdKey
340 | kEventKeyModifierRightCmdKeyMask | kEventKeyModifierNumLockMask | alphaLock | kEventKeyModifierFnMask;
341 if (fModifiers == shiftKey)
342 uKeyCode = QZ_LSHIFT;
343 else if (fModifiers == rightShiftKey)
344 uKeyCode = QZ_RSHIFT;
345 else if (fModifiers == controlKey)
346 uKeyCode = QZ_LCTRL;
347 else if (fModifiers == rightControlKey)
348 uKeyCode = QZ_RCTRL;
349 else if (fModifiers == optionKey)
350 uKeyCode = QZ_LALT;
351 else if (fModifiers == rightOptionKey)
352 uKeyCode = QZ_RALT;
353 else if (fModifiers == cmdKey)
354 uKeyCode = QZ_LMETA;
355 else if (fModifiers == kEventKeyModifierRightCmdKeyMask /* hack */)
356 uKeyCode = QZ_RMETA;
357 else if (fModifiers == alphaLock)
358 uKeyCode = QZ_CAPSLOCK;
359 else if (fModifiers == kEventKeyModifierNumLockMask)
360 uKeyCode = QZ_NUMLOCK;
361 else if (fModifiers == kEventKeyModifierFnMask)
362 uKeyCode = QZ_FN;
363 else if (fModifiers == 0)
364 uKeyCode = 0;
365 else
366 uKeyCode = ~0U; /* multiple */
367 return uKeyCode;
368}
369
370
371/**
372 * Converts a darwin keycode to a modifier mask.
373 *
374 * @returns Darwin modifier mask.
375 * @returns 0 if the keycode isn't a modifier we know.
376 * @param uKeyCode The darwin
377 */
378UInt32 DarwinKeyCodeToDarwinModifierMask(unsigned uKeyCode)
379{
380 UInt32 fModifiers;
381
382 /** @todo find symbols for these keycodes... */
383 if (uKeyCode == QZ_LSHIFT)
384 fModifiers = shiftKey;
385 else if (uKeyCode == QZ_RSHIFT)
386 fModifiers = rightShiftKey;
387 else if (uKeyCode == QZ_LCTRL)
388 fModifiers = controlKey;
389 else if (uKeyCode == QZ_RCTRL)
390 fModifiers = rightControlKey;
391 else if (uKeyCode == QZ_LALT)
392 fModifiers = optionKey;
393 else if (uKeyCode == QZ_RALT)
394 fModifiers = rightOptionKey;
395 else if (uKeyCode == QZ_LMETA)
396 fModifiers = cmdKey;
397 else if (uKeyCode == QZ_RMETA)
398 fModifiers = kEventKeyModifierRightCmdKeyMask; /* hack */
399 else if (uKeyCode == QZ_CAPSLOCK)
400 fModifiers = alphaLock;
401 else if (uKeyCode == QZ_NUMLOCK)
402 fModifiers = kEventKeyModifierNumLockMask;
403 else if (uKeyCode == QZ_FN)
404 fModifiers = kEventKeyModifierFnMask;
405 else
406 fModifiers = 0;
407 return fModifiers;
408}
409
410
411/**
412 * Disables or enabled global hot keys.
413 *
414 * @param fDisable Pass 'true' to disable the hot keys, pass 'false' to re-enable them.
415 */
416void DarwinDisableGlobalHotKeys(bool fDisable)
417{
418 static unsigned s_cComplaints = 0;
419
420 /*
421 * Lazy connect to the core graphics service.
422 */
423 if (!g_fConnectedToCGS)
424 {
425 g_CGSConnection = _CGSDefaultConnection();
426 g_fConnectedToCGS = true;
427 }
428
429 /*
430 * Get the current mode.
431 */
432 CGSGlobalHotKeyOperatingMode enmMode = kCGSGlobalHotKeyInvalid;
433 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmMode);
434 if ( enmMode != kCGSGlobalHotKeyEnable
435 && enmMode != kCGSGlobalHotKeyDisable)
436 {
437 AssertMsgFailed(("%d\n", enmMode));
438 if (s_cComplaints++ < 32)
439 LogRel(("DarwinDisableGlobalHotKeys: Unexpected enmMode=%d\n", enmMode));
440 return;
441 }
442
443 /*
444 * Calc the new mode.
445 */
446 if (fDisable)
447 {
448 if (enmMode != kCGSGlobalHotKeyEnable)
449 return;
450 enmMode = kCGSGlobalHotKeyDisable;
451 }
452 else
453 {
454 if (enmMode != kCGSGlobalHotKeyDisable)
455 return;
456 enmMode = kCGSGlobalHotKeyEnable;
457 }
458
459 /*
460 * Try set it and check the actual result.
461 */
462 CGSSetGlobalHotKeyOperatingMode(g_CGSConnection, enmMode);
463 CGSGlobalHotKeyOperatingMode enmNewMode = kCGSGlobalHotKeyInvalid;
464 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmNewMode);
465 if (enmNewMode != enmMode)
466 {
467 /* If the screensaver kicks in we should ignore failure here. */
468 AssertMsg(enmMode == kCGSGlobalHotKeyEnable, ("enmNewMode=%d enmMode=%d\n", enmNewMode, enmMode));
469 if (s_cComplaints++ < 32)
470 LogRel(("DarwinDisableGlobalHotKeys: Failed to change mode; enmNewMode=%d enmMode=%d\n", enmNewMode, enmMode));
471 }
472}
473
474
475
476#ifdef USE_HID_FOR_MODIFIERS
477
478
479/**
480 * Callback function for consuming queued events.
481 *
482 * @param pvTarget queue?
483 * @param rcIn ?
484 * @param pvRefcon Pointer to the keyboard cache entry.
485 * @param pvSender ?
486 */
487static void darwinQueueCallback(void *pvTarget, IOReturn rcIn, void *pvRefcon, void *pvSender)
488{
489 struct KeyboardCacheData *pKeyboardEntry = (struct KeyboardCacheData *)pvRefcon;
490 if (!pKeyboardEntry->ppHidQueueInterface)
491 return;
492 NOREF(pvTarget);
493 NOREF(rcIn);
494 NOREF(pvSender);
495
496 /*
497 * Consume the events.
498 */
499 g_fOldHIDModifierMask = g_fHIDModifierMask;
500 for (;;)
501 {
502#ifdef DEBUG_PRINTF
503 RTPrintf("dbg-ev: "); RTStrmFlush(g_pStdOut);
504#endif
505 IOHIDEventStruct Event;
506 AbsoluteTime ZeroTime = {0,0};
507 IOReturn rc = (*pKeyboardEntry->ppHidQueueInterface)->getNextEvent(pKeyboardEntry->ppHidQueueInterface,
508 &Event, ZeroTime, 0);
509 if (rc != kIOReturnSuccess)
510 break;
511
512 /* Translate the cookie value to a modifier mask. */
513 uint32_t fMask = 0;
514 unsigned i = pKeyboardEntry->cCookies;
515 while (i-- > 0)
516 {
517 if (pKeyboardEntry->aCookies[i].Cookie == Event.elementCookie)
518 {
519 fMask = pKeyboardEntry->aCookies[i].fMask;
520 break;
521 }
522 }
523
524 /*
525 * Adjust the modifier mask.
526 *
527 * Note that we don't bother to deal with anyone pressing the same modifier
528 * on 2 or more keyboard. That's not worth the effort involved.
529 */
530 if (Event.value)
531 g_fHIDModifierMask |= fMask;
532 else
533 g_fHIDModifierMask &= ~fMask;
534#ifdef DEBUG_PRINTF
535 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);
536#endif
537 }
538#ifdef DEBUG_PRINTF
539 RTPrintf("dbg-ev: done\n"); RTStrmFlush(g_pStdOut);
540#endif
541}
542
543
544
545/**
546 * Element enumeration callback.
547 */
548static void darwinBruteForcePropertySearchApplier(const void *pvValue, void *pvCacheEntry)
549{
550 if (CFGetTypeID(pvValue) == CFDictionaryGetTypeID())
551 darwinBruteForcePropertySearch((CFMutableDictionaryRef)pvValue, (struct KeyboardCacheData *)pvCacheEntry);
552}
553
554
555/**
556 * Recurses thru the keyboard properties looking for certain keys.
557 *
558 * @remark Yes, this can probably be done in a more efficient way. If you
559 * know how to do this, don't hesitate to let us know!
560 */
561static void darwinBruteForcePropertySearch(CFDictionaryRef DictRef, struct KeyboardCacheData *pKeyboardEntry)
562{
563 CFTypeRef ObjRef;
564
565 /*
566 * Check for the usage page and usage key we want.
567 */
568 long lUsage;
569 ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementUsageKey));
570 if ( ObjRef
571 && CFGetTypeID(ObjRef) == CFNumberGetTypeID()
572 && CFNumberGetValue((CFNumberRef)ObjRef, kCFNumberLongType, &lUsage))
573 {
574 switch (lUsage)
575 {
576 case kHIDUsage_KeyboardLeftControl:
577 case kHIDUsage_KeyboardLeftShift:
578 case kHIDUsage_KeyboardLeftAlt:
579 case kHIDUsage_KeyboardLeftGUI:
580 case kHIDUsage_KeyboardRightControl:
581 case kHIDUsage_KeyboardRightShift:
582 case kHIDUsage_KeyboardRightAlt:
583 case kHIDUsage_KeyboardRightGUI:
584 {
585 long lPage;
586 ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementUsagePageKey));
587 if ( !ObjRef
588 || CFGetTypeID(ObjRef) != CFNumberGetTypeID()
589 || !CFNumberGetValue((CFNumberRef)ObjRef, kCFNumberLongType, &lPage)
590 || lPage != kHIDPage_KeyboardOrKeypad)
591 break;
592
593 if (pKeyboardEntry->cCookies >= RT_ELEMENTS(pKeyboardEntry->aCookies))
594 {
595 AssertMsgFailed(("too many cookies!\n"));
596 break;
597 }
598
599 /*
600 * Get the cookie and modifier mask.
601 */
602 long lCookie;
603 ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementCookieKey));
604 if ( !ObjRef
605 || CFGetTypeID(ObjRef) != CFNumberGetTypeID()
606 || !CFNumberGetValue((CFNumberRef)ObjRef, kCFNumberLongType, &lCookie))
607 break;
608
609 uint32_t fMask;
610 switch (lUsage)
611 {
612 case kHIDUsage_KeyboardLeftControl : fMask = controlKey; break;
613 case kHIDUsage_KeyboardLeftShift : fMask = shiftKey; break;
614 case kHIDUsage_KeyboardLeftAlt : fMask = optionKey; break;
615 case kHIDUsage_KeyboardLeftGUI : fMask = cmdKey; break;
616 case kHIDUsage_KeyboardRightControl: fMask = rightControlKey; break;
617 case kHIDUsage_KeyboardRightShift : fMask = rightShiftKey; break;
618 case kHIDUsage_KeyboardRightAlt : fMask = rightOptionKey; break;
619 case kHIDUsage_KeyboardRightGUI : fMask = kEventKeyModifierRightCmdKeyMask; break;
620 default: AssertMsgFailed(("%ld\n",lUsage)); fMask = 0; break;
621 }
622
623 /*
624 * If we've got a queue, add the cookie to the queue.
625 */
626 if (pKeyboardEntry->ppHidQueueInterface)
627 {
628 IOReturn rc = (*pKeyboardEntry->ppHidQueueInterface)->addElement(pKeyboardEntry->ppHidQueueInterface, (IOHIDElementCookie)lCookie, 0);
629 AssertMsg(rc == kIOReturnSuccess, ("rc=%d\n", rc));
630#ifdef DEBUG_PRINTF
631 RTPrintf("dbg-add: u=%#lx c=%#lx\n", lUsage, lCookie);
632#endif
633 }
634
635 /*
636 * Add the cookie to the keyboard entry.
637 */
638 pKeyboardEntry->aCookies[pKeyboardEntry->cCookies].Cookie = (IOHIDElementCookie)lCookie;
639 pKeyboardEntry->aCookies[pKeyboardEntry->cCookies].fMask = fMask;
640 ++pKeyboardEntry->cCookies;
641 break;
642 }
643 }
644 }
645
646
647 /*
648 * Get the elements key and recursivly iterate the elements looking
649 * for they key cookies.
650 */
651 ObjRef = CFDictionaryGetValue(DictRef, CFSTR(kIOHIDElementKey));
652 if ( ObjRef
653 && CFGetTypeID(ObjRef) == CFArrayGetTypeID())
654 {
655 CFArrayRef ArrayObjRef = (CFArrayRef)ObjRef;
656 CFRange Range = {0, CFArrayGetCount(ArrayObjRef)};
657 CFArrayApplyFunction(ArrayObjRef, Range, darwinBruteForcePropertySearchApplier, pKeyboardEntry);
658 }
659}
660
661
662/**
663 * Creates a keyboard cache entry.
664 *
665 * @returns true if the entry was created successfully, otherwise false.
666 * @param pKeyboardEntry Pointer to the entry.
667 * @param KeyboardDevice The keyboard device to create the entry for.
668 *
669 */
670static bool darwinHIDKeyboardCacheCreateEntry(struct KeyboardCacheData *pKeyboardEntry, io_object_t KeyboardDevice)
671{
672 unsigned long cRefs = 0;
673 memset(pKeyboardEntry, 0, sizeof(*pKeyboardEntry));
674
675 /*
676 * Query the HIDDeviceInterface for this HID (keyboard) object.
677 */
678 SInt32 Score = 0;
679 IOCFPlugInInterface **ppPlugInInterface = NULL;
680 IOReturn rc = IOCreatePlugInInterfaceForService(KeyboardDevice, kIOHIDDeviceUserClientTypeID,
681 kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
682 if (rc == kIOReturnSuccess)
683 {
684 IOHIDDeviceInterface **ppHidDeviceInterface = NULL;
685 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
686 CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID),
687 (LPVOID *)&ppHidDeviceInterface);
688 cRefs = (*ppPlugInInterface)->Release(ppPlugInInterface); MY_CHECK_CREFS(cRefs);
689 ppPlugInInterface = NULL;
690 if (hrc == S_OK)
691 {
692 rc = (*ppHidDeviceInterface)->open(ppHidDeviceInterface, 0);
693 if (rc == kIOReturnSuccess)
694 {
695 /*
696 * create a removal callback.
697 */
698 /** @todo */
699
700
701 /*
702 * Create the queue so we can insert elements while searching the properties.
703 */
704 IOHIDQueueInterface **ppHidQueueInterface = (*ppHidDeviceInterface)->allocQueue(ppHidDeviceInterface);
705 if (ppHidQueueInterface)
706 {
707 rc = (*ppHidQueueInterface)->create(ppHidQueueInterface, 0, 32);
708 if (rc != kIOReturnSuccess)
709 {
710 AssertMsgFailed(("rc=%d\n", rc));
711 cRefs = (*ppHidQueueInterface)->Release(ppHidQueueInterface); MY_CHECK_CREFS(cRefs);
712 ppHidQueueInterface = NULL;
713 }
714 }
715 else
716 AssertFailed();
717 pKeyboardEntry->ppHidQueueInterface = ppHidQueueInterface;
718
719 /*
720 * Brute force getting of attributes.
721 */
722 /** @todo read up on how to do this in a less resource intensive way! Suggestions are welcome! */
723 CFMutableDictionaryRef PropertiesRef = 0;
724 kern_return_t krc = IORegistryEntryCreateCFProperties(KeyboardDevice, &PropertiesRef, kCFAllocatorDefault, kNilOptions);
725 if (krc == KERN_SUCCESS)
726 {
727 darwinBruteForcePropertySearch(PropertiesRef, pKeyboardEntry);
728 CFRelease(PropertiesRef);
729 }
730 else
731 AssertMsgFailed(("krc=%#x\n", krc));
732
733 if (ppHidQueueInterface)
734 {
735 /*
736 * Now install our queue callback.
737 */
738 CFRunLoopSourceRef RunLoopSrcRef = NULL;
739 rc = (*ppHidQueueInterface)->createAsyncEventSource(ppHidQueueInterface, &RunLoopSrcRef);
740 if (rc == kIOReturnSuccess)
741 {
742 CFRunLoopRef RunLoopRef = (CFRunLoopRef)GetCFRunLoopFromEventLoop(GetMainEventLoop());
743 CFRunLoopAddSource(RunLoopRef, RunLoopSrcRef, kCFRunLoopDefaultMode);
744 }
745
746 /*
747 * Now install our queue callback.
748 */
749 rc = (*ppHidQueueInterface)->setEventCallout(ppHidQueueInterface, darwinQueueCallback, ppHidQueueInterface, pKeyboardEntry);
750 if (rc != kIOReturnSuccess)
751 AssertMsgFailed(("rc=%d\n", rc));
752 }
753
754 /*
755 * Complete the new keyboard cache entry.
756 */
757 pKeyboardEntry->ppHidDeviceInterface = ppHidDeviceInterface;
758 pKeyboardEntry->ppHidQueueInterface = ppHidQueueInterface;
759 return true;
760 }
761
762 AssertMsgFailed(("rc=%d\n", rc));
763 cRefs = (*ppHidDeviceInterface)->Release(ppHidDeviceInterface); MY_CHECK_CREFS(cRefs);
764 }
765 else
766 AssertMsgFailed(("hrc=%#x\n", hrc));
767 }
768 else
769 AssertMsgFailed(("rc=%d\n", rc));
770
771 return false;
772}
773
774
775/**
776 * Destroys a keyboard cache entry.
777 *
778 * @param pKeyboardEntry The entry.
779 */
780static void darwinHIDKeyboardCacheDestroyEntry(struct KeyboardCacheData *pKeyboardEntry)
781{
782 unsigned long cRefs;
783
784 /*
785 * Destroy the queue
786 */
787 if (pKeyboardEntry->ppHidQueueInterface)
788 {
789 IOHIDQueueInterface **ppHidQueueInterface = pKeyboardEntry->ppHidQueueInterface;
790 pKeyboardEntry->ppHidQueueInterface = NULL;
791
792 /* stop it just in case we haven't done so. doesn't really matter I think. */
793 (*ppHidQueueInterface)->stop(ppHidQueueInterface);
794
795 /* deal with the run loop source. */
796 CFRunLoopSourceRef RunLoopSrcRef = (*ppHidQueueInterface)->getAsyncEventSource(ppHidQueueInterface);
797 if (RunLoopSrcRef)
798 {
799 CFRunLoopRef RunLoopRef = (CFRunLoopRef)GetCFRunLoopFromEventLoop(GetMainEventLoop());
800 CFRunLoopRemoveSource(RunLoopRef, RunLoopSrcRef, kCFRunLoopDefaultMode);
801
802 CFRelease(RunLoopSrcRef);
803 }
804
805 /* dispose of and release the queue. */
806 (*ppHidQueueInterface)->dispose(ppHidQueueInterface);
807 cRefs = (*ppHidQueueInterface)->Release(ppHidQueueInterface); MY_CHECK_CREFS(cRefs);
808 }
809
810 /*
811 * Release the removal hook?
812 */
813 /** @todo */
814
815 /*
816 * Close and release the device interface.
817 */
818 if (pKeyboardEntry->ppHidDeviceInterface)
819 {
820 IOHIDDeviceInterface **ppHidDeviceInterface = pKeyboardEntry->ppHidDeviceInterface;
821 pKeyboardEntry->ppHidDeviceInterface = NULL;
822
823 (*ppHidDeviceInterface)->close(ppHidDeviceInterface);
824 cRefs = (*ppHidDeviceInterface)->Release(ppHidDeviceInterface); MY_CHECK_CREFS(cRefs);
825 }
826}
827
828
829/**
830 * Zap the keyboard cache.
831 */
832static void darwinHIDKeyboardCacheZap(void)
833{
834 /*
835 * Release the old cache data first.
836 */
837 while (g_cKeyboards > 0)
838 {
839 unsigned i = --g_cKeyboards;
840 darwinHIDKeyboardCacheDestroyEntry(&g_aKeyboards[i]);
841 }
842}
843
844
845/**
846 * Updates the cached keyboard data.
847 *
848 * @todo The current implementation is very brute force...
849 * Rewrite it so that it doesn't flush the cache completely but simply checks whether
850 * anything has changed in the HID config. With any luck, there might even be a callback
851 * or something we can poll for HID config changes...
852 * setRemovalCallback() is a start...
853 */
854static void darwinHIDKeyboardCacheDoUpdate(void)
855{
856 g_u64KeyboardTS = RTTimeMilliTS();
857
858 /*
859 * Dispense with the old cache data.
860 */
861 darwinHIDKeyboardCacheZap();
862
863 /*
864 * Open the master port on the first invocation.
865 */
866 if (!g_MasterPort)
867 {
868 kern_return_t krc = IOMasterPort(MACH_PORT_NULL, &g_MasterPort);
869 AssertReturnVoid(krc == KERN_SUCCESS);
870 }
871
872 /*
873 * Create a matching dictionary for searching for keyboards devices.
874 */
875 static const UInt32 s_Page = kHIDPage_GenericDesktop;
876 static const UInt32 s_Usage = kHIDUsage_GD_Keyboard;
877 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOHIDDeviceKey);
878 AssertReturnVoid(RefMatchingDict);
879 CFDictionarySetValue(RefMatchingDict, CFSTR(kIOHIDPrimaryUsagePageKey),
880 CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &s_Page));
881 CFDictionarySetValue(RefMatchingDict, CFSTR(kIOHIDPrimaryUsageKey),
882 CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &s_Usage));
883
884 /*
885 * Perform the search and get a collection of keyboard devices.
886 */
887 io_iterator_t Keyboards = NULL;
888 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &Keyboards);
889 AssertMsgReturnVoid(rc == kIOReturnSuccess, ("rc=%d\n", rc));
890 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
891
892 /*
893 * Enumerate the keyboards and query the cache data.
894 */
895 unsigned i = 0;
896 io_object_t KeyboardDevice;
897 while ( i < RT_ELEMENTS(g_aKeyboards)
898 && (KeyboardDevice = IOIteratorNext(Keyboards)) != 0)
899 {
900 if (darwinHIDKeyboardCacheCreateEntry(&g_aKeyboards[i], KeyboardDevice))
901 i++;
902 IOObjectRelease(KeyboardDevice);
903 }
904 g_cKeyboards = i;
905
906 IOObjectRelease(Keyboards);
907}
908
909
910/**
911 * Updates the keyboard cache if it's time to do it again.
912 */
913static void darwinHIDKeyboardCacheUpdate(void)
914{
915 if ( !g_cKeyboards
916 /*|| g_u64KeyboardTS - RTTimeMilliTS() > 7500*/ /* 7.5sec */)
917 darwinHIDKeyboardCacheDoUpdate();
918}
919
920
921/**
922 * Queries the modifier keys from the (IOKit) HID Manager.
923 *
924 * @returns Carbon modifier mask with right/left set correctly.
925 */
926static UInt32 darwinQueryHIDModifiers(void)
927{
928 /*
929 * Iterate thru the keyboards collecting their modifier masks.
930 */
931 UInt32 fHIDModifiers = 0;
932 unsigned i = g_cKeyboards;
933 while (i-- > 0)
934 {
935 IOHIDDeviceInterface **ppHidDeviceInterface = g_aKeyboards[i].ppHidDeviceInterface;
936 if (!ppHidDeviceInterface)
937 continue;
938
939 unsigned j = g_aKeyboards[i].cCookies;
940 while (j-- > 0)
941 {
942 IOHIDEventStruct HidEvent;
943 IOReturn rc = (*ppHidDeviceInterface)->getElementValue(ppHidDeviceInterface,
944 g_aKeyboards[i].aCookies[j].Cookie,
945 &HidEvent);
946 if (rc == kIOReturnSuccess)
947 {
948 if (HidEvent.value)
949 fHIDModifiers |= g_aKeyboards[i].aCookies[j].fMask;
950 }
951 else
952 AssertMsgFailed(("rc=%#x\n", rc));
953 }
954 }
955
956 return fHIDModifiers;
957}
958
959#endif /* USE_HID_FOR_MODIFIERS */
960
961
962
963/**
964 * Left / rigth adjust the modifier mask using the current
965 * keyboard state.
966 *
967 * @returns left/right adjusted fModifiers.
968 * @param fModifiers The mask to adjust.
969 */
970UInt32 DarwinAdjustModifierMask(UInt32 fModifiers)
971{
972#ifdef USE_HID_FOR_MODIFIERS
973 /*
974 * Update the keyboard cache.
975 */
976 darwinHIDKeyboardCacheUpdate();
977
978 /*
979 * Check if there is anything to adjust and perform the adjustment.
980 */
981 if (fModifiers & (shiftKey | rightShiftKey | controlKey | rightControlKey | optionKey | rightOptionKey | cmdKey | kEventKeyModifierRightCmdKeyMask))
982 {
983 const UInt32 fHIDModifiers = g_fHIDModifierMask;
984#ifdef DEBUG_PRINTF
985 RTPrintf("dbg-fHIDModifier=%#x fModifiers=%#x", fHIDModifiers, fModifiers);
986#endif
987 if ( (fModifiers & (rightShiftKey | shiftKey))
988 && (fHIDModifiers & (rightShiftKey | shiftKey)))
989 {
990 fModifiers &= ~(rightShiftKey | shiftKey);
991 fModifiers |= fHIDModifiers & (rightShiftKey | shiftKey);
992 }
993
994 if ( (fModifiers & (rightControlKey | controlKey))
995 && (fHIDModifiers & (rightControlKey | controlKey)))
996 {
997 fModifiers &= ~(rightControlKey | controlKey);
998 fModifiers |= fHIDModifiers & (rightControlKey | controlKey);
999 }
1000
1001 if ( (fModifiers & (optionKey | rightOptionKey))
1002 && (fHIDModifiers & (optionKey | rightOptionKey)))
1003 {
1004 fModifiers &= ~(optionKey | rightOptionKey);
1005 fModifiers |= fHIDModifiers & (optionKey | rightOptionKey);
1006 }
1007
1008 if ( (fModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask))
1009 && (fHIDModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask)))
1010 {
1011 fModifiers &= ~(cmdKey | kEventKeyModifierRightCmdKeyMask);
1012 fModifiers |= fHIDModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask);
1013 }
1014#ifdef DEBUG_PRINTF
1015 RTPrintf(" -> %#x", fModifiers);
1016#endif
1017 }
1018#endif /* USE_HID_FOR_MODIFIERS */
1019
1020 return fModifiers;
1021}
1022
1023
1024/**
1025 * Start grabbing keyboard events.
1026 *
1027 * This only concerns itself with modifiers and disabling global hotkeys (if requested).
1028 *
1029 * @param fGlobalHotkeys Whether to disable global hotkeys or not.
1030 */
1031void DarwinGrabKeyboard(bool fGlobalHotkeys)
1032{
1033 LogFlow(("DarwinGrabKeyboard: fGlobalHotkeys=%RTbool\n", fGlobalHotkeys));
1034
1035#ifdef USE_HID_FOR_MODIFIERS
1036 /*
1037 * Update the keyboard cache.
1038 */
1039 darwinHIDKeyboardCacheUpdate();
1040
1041 /*
1042 * Start the keyboard queues and query the current mask.
1043 */
1044 g_fHIDQueueEnabled = true;
1045
1046 unsigned i = g_cKeyboards;
1047 while (i-- > 0)
1048 {
1049 if (g_aKeyboards[i].ppHidQueueInterface)
1050 (*g_aKeyboards[i].ppHidQueueInterface)->start(g_aKeyboards[i].ppHidQueueInterface);
1051 }
1052
1053 g_fHIDModifierMask = darwinQueryHIDModifiers();
1054#endif /* USE_HID_FOR_MODIFIERS */
1055
1056 /*
1057 * Disable hotkeys if requested.
1058 */
1059 if (fGlobalHotkeys)
1060 DarwinDisableGlobalHotKeys(true);
1061}
1062
1063
1064/**
1065 * Reverses the actions taken by DarwinGrabKeyboard.
1066 */
1067void DarwinReleaseKeyboard(void)
1068{
1069 LogFlow(("DarwinReleaseKeyboard\n"));
1070
1071 /*
1072 * Re-enable hotkeys.
1073 */
1074 DarwinDisableGlobalHotKeys(false);
1075
1076#ifdef USE_HID_FOR_MODIFIERS
1077 /*
1078 * Stop and drain the keyboard queues.
1079 */
1080 g_fHIDQueueEnabled = false;
1081
1082#if 0
1083 unsigned i = g_cKeyboards;
1084 while (i-- > 0)
1085 {
1086 if (g_aKeyboards[i].ppHidQueueInterface)
1087 {
1088
1089 (*g_aKeyboards[i].ppHidQueueInterface)->stop(g_aKeyboards[i].ppHidQueueInterface);
1090
1091 /* drain it */
1092 IOReturn rc;
1093 unsigned c = 0;
1094 do
1095 {
1096 IOHIDEventStruct Event;
1097 AbsoluteTime MaxTime = {0,0};
1098 rc = (*g_aKeyboards[i].ppHidQueueInterface)->getNextEvent(g_aKeyboards[i].ppHidQueueInterface,
1099 &Event, MaxTime, 0);
1100 } while ( rc == kIOReturnSuccess
1101 && c++ < 32);
1102 }
1103 }
1104#else
1105
1106 /*
1107 * Kill the keyboard cache.
1108 * This will hopefully fix the crash in getElementValue()/fillElementValue()...
1109 */
1110 darwinHIDKeyboardCacheZap();
1111#endif
1112
1113 /* Clear the modifier mask. */
1114 g_fHIDModifierMask = 0;
1115#endif /* USE_HID_FOR_MODIFIERS */
1116}
1117
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette