VirtualBox

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

Last change on this file since 33540 was 33540, checked in by vboxsync, 14 years ago

*: spelling fixes, thanks Timeless!

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 40.3 KB
Line 
1/* $Id: DarwinKeyboard.cpp 33540 2010-10-28 09:27:05Z vboxsync $ */
2/** @file
3 * Common GUI Library - Darwin Keyboard routines.
4 *
5 * @todo Move this up somewhere so that the two SDL GUIs can use parts of this code too (-HID crap).
6 */
7
8/*
9 * Copyright (C) 2006-2007 Oracle Corporation
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 */
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23#define LOG_GROUP LOG_GROUP_GUI
24#include "DarwinKeyboard.h"
25#include <iprt/assert.h>
26#include <iprt/asm.h>
27#include <iprt/time.h>
28#include <VBox/log.h>
29#ifdef DEBUG_PRINTF
30# include <iprt/stream.h>
31#endif
32
33#ifdef USE_HID_FOR_MODIFIERS
34# include <mach/mach.h>
35# include <mach/mach_error.h>
36# include <IOKit/IOKitLib.h>
37# include <IOKit/IOCFPlugIn.h>
38# include <IOKit/hid/IOHIDLib.h>
39# include <IOKit/hid/IOHIDUsageTables.h>
40# include <IOKit/usb/USB.h>
41# include <CoreFoundation/CoreFoundation.h>
42#endif
43#include <ApplicationServices/ApplicationServices.h>
44#include <Carbon/Carbon.h>
45
46#ifndef USE_HID_FOR_MODIFIERS
47# include "CocoaEventHelper.h"
48#endif
49
50
51RT_C_DECLS_BEGIN
52/* Private interface in 10.3 and later. */
53typedef int CGSConnection;
54typedef enum
55{
56 kCGSGlobalHotKeyEnable = 0,
57 kCGSGlobalHotKeyDisable,
58 kCGSGlobalHotKeyInvalid = -1 /* bird */
59} CGSGlobalHotKeyOperatingMode;
60extern CGSConnection _CGSDefaultConnection(void);
61extern CGError CGSGetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode *enmMode);
62extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection Connection, CGSGlobalHotKeyOperatingMode enmMode);
63RT_C_DECLS_END
64
65
66/*******************************************************************************
67* Defined Constants And Macros *
68*******************************************************************************/
69
70#define QZ_RMETA 0x36
71#define QZ_LMETA 0x37
72#define QZ_LSHIFT 0x38
73#define QZ_CAPSLOCK 0x39
74#define QZ_LALT 0x3A
75#define QZ_LCTRL 0x3B
76#define QZ_RSHIFT 0x3C
77#define QZ_RALT 0x3D
78#define QZ_RCTRL 0x3E
79/* Found the definition of the fn-key in:
80 * http://stuff.mit.edu/afs/sipb/project/darwin/src/modules/IOHIDFamily/IOHIDSystem/IOHIKeyboardMapper.cpp &
81 * http://stuff.mit.edu/afs/sipb/project/darwin/src/modules/AppleADBKeyboard/AppleADBKeyboard.cpp
82 * Maybe we need this in the future.*/
83#define QZ_FN 0x3F
84#define QZ_NUMLOCK 0x47
85
86/** short hand for an extended key. */
87#define K_EX VBOXKEY_EXTENDED
88/** short hand for a modifier key. */
89#define K_MOD VBOXKEY_MODIFIER
90/** short hand for a lock key. */
91#define K_LOCK VBOXKEY_LOCK
92
93#ifdef USE_HID_FOR_MODIFIERS
94
95/** An attempt at catching reference leaks. */
96#define MY_CHECK_CREFS(cRefs) do { AssertMsg(cRefs < 25, ("%ld\n", cRefs)); NOREF(cRefs); } while (0)
97
98#endif
99
100/*******************************************************************************
101* Global Variables *
102*******************************************************************************/
103/**
104 * This is derived partially from SDL_QuartzKeys.h and partially from testing.
105 *
106 * (The funny thing about the virtual scan codes on the mac is that they aren't
107 * offically documented, which is rather silly to say the least. Thus, the need
108 * for looking at SDL and other odd places for docs.)
109 */
110static const uint16_t g_aDarwinToSet1[] =
111{
112 /* set-1 SDL_QuartzKeys.h */
113 0x1e, /* QZ_a 0x00 */
114 0x1f, /* QZ_s 0x01 */
115 0x20, /* QZ_d 0x02 */
116 0x21, /* QZ_f 0x03 */
117 0x23, /* QZ_h 0x04 */
118 0x22, /* QZ_g 0x05 */
119 0x2c, /* QZ_z 0x06 */
120 0x2d, /* QZ_x 0x07 */
121 0x2e, /* QZ_c 0x08 */
122 0x2f, /* QZ_v 0x09 */
123 0x56, /* between lshift and z. 'INT 1'? */
124 0x30, /* QZ_b 0x0B */
125 0x10, /* QZ_q 0x0C */
126 0x11, /* QZ_w 0x0D */
127 0x12, /* QZ_e 0x0E */
128 0x13, /* QZ_r 0x0F */
129 0x15, /* QZ_y 0x10 */
130 0x14, /* QZ_t 0x11 */
131 0x02, /* QZ_1 0x12 */
132 0x03, /* QZ_2 0x13 */
133 0x04, /* QZ_3 0x14 */
134 0x05, /* QZ_4 0x15 */
135 0x07, /* QZ_6 0x16 */
136 0x06, /* QZ_5 0x17 */
137 0x0d, /* QZ_EQUALS 0x18 */
138 0x0a, /* QZ_9 0x19 */
139 0x08, /* QZ_7 0x1A */
140 0x0c, /* QZ_MINUS 0x1B */
141 0x09, /* QZ_8 0x1C */
142 0x0b, /* QZ_0 0x1D */
143 0x1b, /* QZ_RIGHTBRACKET 0x1E */
144 0x18, /* QZ_o 0x1F */
145 0x16, /* QZ_u 0x20 */
146 0x1a, /* QZ_LEFTBRACKET 0x21 */
147 0x17, /* QZ_i 0x22 */
148 0x19, /* QZ_p 0x23 */
149 0x1c, /* QZ_RETURN 0x24 */
150 0x26, /* QZ_l 0x25 */
151 0x24, /* QZ_j 0x26 */
152 0x28, /* QZ_QUOTE 0x27 */
153 0x25, /* QZ_k 0x28 */
154 0x27, /* QZ_SEMICOLON 0x29 */
155 0x2b, /* QZ_BACKSLASH 0x2A */
156 0x33, /* QZ_COMMA 0x2B */
157 0x35, /* QZ_SLASH 0x2C */
158 0x31, /* QZ_n 0x2D */
159 0x32, /* QZ_m 0x2E */
160 0x34, /* QZ_PERIOD 0x2F */
161 0x0f, /* QZ_TAB 0x30 */
162 0x39, /* QZ_SPACE 0x31 */
163 0x29, /* QZ_BACKQUOTE 0x32 */
164 0x0e, /* QZ_BACKSPACE 0x33 */
165 0x9c, /* QZ_IBOOK_ENTER 0x34 */
166 0x01, /* QZ_ESCAPE 0x35 */
167 0x5c|K_EX|K_MOD, /* QZ_RMETA 0x36 */
168 0x5b|K_EX|K_MOD, /* QZ_LMETA 0x37 */
169 0x2a|K_MOD, /* QZ_LSHIFT 0x38 */
170 0x3a|K_LOCK, /* QZ_CAPSLOCK 0x39 */
171 0x38|K_MOD, /* QZ_LALT 0x3A */
172 0x1d|K_MOD, /* QZ_LCTRL 0x3B */
173 0x36|K_MOD, /* QZ_RSHIFT 0x3C */
174 0x38|K_EX|K_MOD, /* QZ_RALT 0x3D */
175 0x1d|K_EX|K_MOD, /* QZ_RCTRL 0x3E */
176 0, /* */
177 0, /* */
178 0x53, /* QZ_KP_PERIOD 0x41 */
179 0, /* */
180 0x37, /* QZ_KP_MULTIPLY 0x43 */
181 0, /* */
182 0x4e, /* QZ_KP_PLUS 0x45 */
183 0, /* */
184 0x45|K_LOCK, /* QZ_NUMLOCK 0x47 */
185 0, /* */
186 0, /* */
187 0, /* */
188 0x35|K_EX, /* QZ_KP_DIVIDE 0x4B */
189 0x1c|K_EX, /* QZ_KP_ENTER 0x4C */
190 0, /* */
191 0x4a, /* QZ_KP_MINUS 0x4E */
192 0, /* */
193 0, /* */
194 0x0d/*?*/, /* QZ_KP_EQUALS 0x51 */
195 0x52, /* QZ_KP0 0x52 */
196 0x4f, /* QZ_KP1 0x53 */
197 0x50, /* QZ_KP2 0x54 */
198 0x51, /* QZ_KP3 0x55 */
199 0x4b, /* QZ_KP4 0x56 */
200 0x4c, /* QZ_KP5 0x57 */
201 0x4d, /* QZ_KP6 0x58 */
202 0x47, /* QZ_KP7 0x59 */
203 0, /* */
204 0x48, /* QZ_KP8 0x5B */
205 0x49, /* QZ_KP9 0x5C */
206 0x7d, /* yen, | (JIS) 0x5D */
207 0x73, /* _, ro (JIS) 0x5E */
208 0, /* */
209 0x3f, /* QZ_F5 0x60 */
210 0x40, /* QZ_F6 0x61 */
211 0x41, /* QZ_F7 0x62 */
212 0x3d, /* QZ_F3 0x63 */
213 0x42, /* QZ_F8 0x64 */
214 0x43, /* QZ_F9 0x65 */
215 0x29, /* Zen/Han (JIS) 0x66 */
216 0x57, /* QZ_F11 0x67 */
217 0x29, /* Zen/Han (JIS) 0x68 */
218 0x37|K_EX, /* QZ_PRINT / F13 0x69 */
219 0x63, /* QZ_F16 0x6A */
220 0x46|K_LOCK, /* QZ_SCROLLOCK 0x6B */
221 0, /* */
222 0x44, /* QZ_F10 0x6D */
223 0x5d|K_EX, /* */
224 0x58, /* QZ_F12 0x6F */
225 0, /* */
226 0/* 0xe1,0x1d,0x45*/, /* QZ_PAUSE 0x71 */
227 0x52|K_EX, /* QZ_INSERT / HELP 0x72 */
228 0x47|K_EX, /* QZ_HOME 0x73 */
229 0x49|K_EX, /* QZ_PAGEUP 0x74 */
230 0x53|K_EX, /* QZ_DELETE 0x75 */
231 0x3e, /* QZ_F4 0x76 */
232 0x4f|K_EX, /* QZ_END 0x77 */
233 0x3c, /* QZ_F2 0x78 */
234 0x51|K_EX, /* QZ_PAGEDOWN 0x79 */
235 0x3b, /* QZ_F1 0x7A */
236 0x4b|K_EX, /* QZ_LEFT 0x7B */
237 0x4d|K_EX, /* QZ_RIGHT 0x7C */
238 0x50|K_EX, /* QZ_DOWN 0x7D */
239 0x48|K_EX, /* QZ_UP 0x7E */
240 0x5e|K_EX, /* QZ_POWER 0x7F */ /* have different break key! */
241};
242
243
244/** Whether we've connected or not. */
245static bool g_fConnectedToCGS = false;
246/** Cached connection. */
247static CGSConnection g_CGSConnection;
248
249
250#ifdef USE_HID_FOR_MODIFIERS
251
252/** The IO Master Port. */
253static mach_port_t g_MasterPort = NULL;
254
255/** Keyboards in the cache. */
256static unsigned g_cKeyboards = 0;
257/** Array of cached keyboard data. */
258static struct KeyboardCacheData
259{
260 /** The device interface. */
261 IOHIDDeviceInterface **ppHidDeviceInterface;
262 /** The queue interface. */
263 IOHIDQueueInterface **ppHidQueueInterface;
264
265 /* cookie translation array. */
266 struct KeyboardCacheCookie
267 {
268 /** The cookie. */
269 IOHIDElementCookie Cookie;
270 /** The corresponding modifier mask. */
271 uint32_t fMask;
272 } aCookies[64];
273 /** Number of cookies in the array. */
274 unsigned cCookies;
275} g_aKeyboards[128];
276/** The keyboard cache creation timestamp. */
277static uint64_t g_u64KeyboardTS = 0;
278
279/** HID queue status. */
280static bool g_fHIDQueueEnabled;
281/** The current modifier mask. */
282static uint32_t g_fHIDModifierMask;
283/** The old modifier mask. */
284static uint32_t g_fOldHIDModifierMask;
285
286#endif /* USE_HID_FOR_MODIFIERS */
287
288
289/*******************************************************************************
290* Internal Functions *
291*******************************************************************************/
292#ifdef USE_HID_FOR_MODIFIERS
293static void darwinBruteForcePropertySearch(CFDictionaryRef DictRef, struct KeyboardCacheData *pKeyboardEntry);
294#endif
295
296
297/**
298 * Converts a darwin (virtual) key code to a set 1 scan code.
299 *
300 * @returns set 1 scan code.
301 * @param uKeyCode The darwin key code.
302 */
303unsigned DarwinKeycodeToSet1Scancode(unsigned uKeyCode)
304{
305 if (uKeyCode >= RT_ELEMENTS(g_aDarwinToSet1))
306 return 0;
307 return g_aDarwinToSet1[uKeyCode];
308}
309
310
311/**
312 * Converts a single modifier to a set 1 scan code.
313 *
314 * @returns Set 1 scan code.
315 * @returns ~0U if more than one modifier is set.
316 * @param fModifiers The darwin modifier mask.
317 */
318unsigned DarwinModifierMaskToSet1Scancode(UInt32 fModifiers)
319{
320 unsigned uScanCode = DarwinModifierMaskToDarwinKeycode(fModifiers);
321 if (uScanCode < RT_ELEMENTS(g_aDarwinToSet1))
322 uScanCode = g_aDarwinToSet1[uScanCode];
323 else
324 Assert(uScanCode == ~0U);
325 return uScanCode;
326}
327
328
329/**
330 * Converts a single modifier to a darwin keycode.
331 *
332 * @returns Darwin keycode.
333 * @returns 0 if none of the support masks were set.
334 * @returns ~0U if more than one modifier is set.
335 * @param fModifiers The darwin modifier mask.
336 */
337unsigned DarwinModifierMaskToDarwinKeycode(UInt32 fModifiers)
338{
339 unsigned uKeyCode;
340
341 /** @todo find symbols for these keycodes... */
342 fModifiers &= shiftKey | rightShiftKey | controlKey | rightControlKey | optionKey | rightOptionKey | cmdKey
343 | kEventKeyModifierRightCmdKeyMask | kEventKeyModifierNumLockMask | alphaLock | kEventKeyModifierFnMask;
344 if (fModifiers == shiftKey)
345 uKeyCode = QZ_LSHIFT;
346 else if (fModifiers == rightShiftKey)
347 uKeyCode = QZ_RSHIFT;
348 else if (fModifiers == controlKey)
349 uKeyCode = QZ_LCTRL;
350 else if (fModifiers == rightControlKey)
351 uKeyCode = QZ_RCTRL;
352 else if (fModifiers == optionKey)
353 uKeyCode = QZ_LALT;
354 else if (fModifiers == rightOptionKey)
355 uKeyCode = QZ_RALT;
356 else if (fModifiers == cmdKey)
357 uKeyCode = QZ_LMETA;
358 else if (fModifiers == kEventKeyModifierRightCmdKeyMask /* hack */)
359 uKeyCode = QZ_RMETA;
360 else if (fModifiers == alphaLock)
361 uKeyCode = QZ_CAPSLOCK;
362 else if (fModifiers == kEventKeyModifierNumLockMask)
363 uKeyCode = QZ_NUMLOCK;
364 else if (fModifiers == kEventKeyModifierFnMask)
365 uKeyCode = QZ_FN;
366 else if (fModifiers == 0)
367 uKeyCode = 0;
368 else
369 uKeyCode = ~0U; /* multiple */
370 return uKeyCode;
371}
372
373
374/**
375 * Converts a darwin keycode to a modifier mask.
376 *
377 * @returns Darwin modifier mask.
378 * @returns 0 if the keycode isn't a modifier we know.
379 * @param uKeyCode The darwin
380 */
381UInt32 DarwinKeyCodeToDarwinModifierMask(unsigned uKeyCode)
382{
383 UInt32 fModifiers;
384
385 /** @todo find symbols for these keycodes... */
386 if (uKeyCode == QZ_LSHIFT)
387 fModifiers = shiftKey;
388 else if (uKeyCode == QZ_RSHIFT)
389 fModifiers = rightShiftKey;
390 else if (uKeyCode == QZ_LCTRL)
391 fModifiers = controlKey;
392 else if (uKeyCode == QZ_RCTRL)
393 fModifiers = rightControlKey;
394 else if (uKeyCode == QZ_LALT)
395 fModifiers = optionKey;
396 else if (uKeyCode == QZ_RALT)
397 fModifiers = rightOptionKey;
398 else if (uKeyCode == QZ_LMETA)
399 fModifiers = cmdKey;
400 else if (uKeyCode == QZ_RMETA)
401 fModifiers = kEventKeyModifierRightCmdKeyMask; /* hack */
402 else if (uKeyCode == QZ_CAPSLOCK)
403 fModifiers = alphaLock;
404 else if (uKeyCode == QZ_NUMLOCK)
405 fModifiers = kEventKeyModifierNumLockMask;
406 else if (uKeyCode == QZ_FN)
407 fModifiers = kEventKeyModifierFnMask;
408 else
409 fModifiers = 0;
410 return fModifiers;
411}
412
413
414/**
415 * Disables or enabled global hot keys.
416 *
417 * @param fDisable Pass 'true' to disable the hot keys, pass 'false' to re-enable them.
418 */
419void DarwinDisableGlobalHotKeys(bool fDisable)
420{
421 static unsigned s_cComplaints = 0;
422
423 /*
424 * Lazy connect to the core graphics service.
425 */
426 if (!g_fConnectedToCGS)
427 {
428 g_CGSConnection = _CGSDefaultConnection();
429 g_fConnectedToCGS = true;
430 }
431
432 /*
433 * Get the current mode.
434 */
435 CGSGlobalHotKeyOperatingMode enmMode = kCGSGlobalHotKeyInvalid;
436 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmMode);
437 if ( enmMode != kCGSGlobalHotKeyEnable
438 && enmMode != kCGSGlobalHotKeyDisable)
439 {
440 AssertMsgFailed(("%d\n", enmMode));
441 if (s_cComplaints++ < 32)
442 LogRel(("DarwinDisableGlobalHotKeys: Unexpected enmMode=%d\n", enmMode));
443 return;
444 }
445
446 /*
447 * Calc the new mode.
448 */
449 if (fDisable)
450 {
451 if (enmMode != kCGSGlobalHotKeyEnable)
452 return;
453 enmMode = kCGSGlobalHotKeyDisable;
454 }
455 else
456 {
457 if (enmMode != kCGSGlobalHotKeyDisable)
458 return;
459 enmMode = kCGSGlobalHotKeyEnable;
460 }
461
462 /*
463 * Try set it and check the actual result.
464 */
465 CGSSetGlobalHotKeyOperatingMode(g_CGSConnection, enmMode);
466 CGSGlobalHotKeyOperatingMode enmNewMode = kCGSGlobalHotKeyInvalid;
467 CGSGetGlobalHotKeyOperatingMode(g_CGSConnection, &enmNewMode);
468 if (enmNewMode != enmMode)
469 {
470 /* If the screensaver kicks in we should ignore failure here. */
471 AssertMsg(enmMode == kCGSGlobalHotKeyEnable, ("enmNewMode=%d enmMode=%d\n", enmNewMode, enmMode));
472 if (s_cComplaints++ < 32)
473 LogRel(("DarwinDisableGlobalHotKeys: Failed to change mode; enmNewMode=%d enmMode=%d\n", enmNewMode, enmMode));
474 }
475}
476
477#ifdef USE_HID_FOR_MODIFIERS
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 recursively 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 * Left / right adjust the modifier mask using the current
963 * keyboard state.
964 *
965 * @returns left/right adjusted fModifiers.
966 * @param fModifiers The mask to adjust.
967 * @param pvCocoaEvent The associated Cocoa keyboard event. This is NULL
968 * when using HID for modifier corrections.
969 *
970 */
971UInt32 DarwinAdjustModifierMask(UInt32 fModifiers, const void *pvCocoaEvent)
972{
973 /*
974 * Check if there is anything to adjust and perform the adjustment.
975 */
976 if (fModifiers & (shiftKey | rightShiftKey | controlKey | rightControlKey | optionKey | rightOptionKey | cmdKey | kEventKeyModifierRightCmdKeyMask))
977 {
978#ifndef USE_HID_FOR_MODIFIERS
979 /*
980 * Convert the Cocoa modifiers to Carbon ones (the Cocoa modifier
981 * definitions are tucked away in Objective-C headers, unfortunately).
982 *
983 * Update: CGEventTypes.h includes what looks like the Cocoa modifiers
984 * and the NX_* defines should be available as well. We should look
985 * into ways to intercept the CG (core graphics) events in the Carbon
986 * based setup and get rid of all this HID mess.
987 */
988 AssertPtr(pvCocoaEvent);
989 //::darwinPrintEvent("dbg-adjMods: ", pvCocoaEvent);
990 uint32_t fAltModifiers = ::darwinEventModifierFlagsXlated(pvCocoaEvent);
991
992#else /* USE_HID_FOR_MODIFIERS */
993 /*
994 * Update the keyboard cache.
995 */
996 darwinHIDKeyboardCacheUpdate();
997 const UInt32 fAltModifiers = g_fHIDModifierMask;
998
999#endif /* USE_HID_FOR_MODIFIERS */
1000#ifdef DEBUG_PRINTF
1001 RTPrintf("dbg-fAltModifiers=%#x fModifiers=%#x", fAltModifiers, fModifiers);
1002#endif
1003 if ( (fModifiers & (rightShiftKey | shiftKey))
1004 && (fAltModifiers & (rightShiftKey | shiftKey)))
1005 {
1006 fModifiers &= ~(rightShiftKey | shiftKey);
1007 fModifiers |= fAltModifiers & (rightShiftKey | shiftKey);
1008 }
1009
1010 if ( (fModifiers & (rightControlKey | controlKey))
1011 && (fAltModifiers & (rightControlKey | controlKey)))
1012 {
1013 fModifiers &= ~(rightControlKey | controlKey);
1014 fModifiers |= fAltModifiers & (rightControlKey | controlKey);
1015 }
1016
1017 if ( (fModifiers & (optionKey | rightOptionKey))
1018 && (fAltModifiers & (optionKey | rightOptionKey)))
1019 {
1020 fModifiers &= ~(optionKey | rightOptionKey);
1021 fModifiers |= fAltModifiers & (optionKey | rightOptionKey);
1022 }
1023
1024 if ( (fModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask))
1025 && (fAltModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask)))
1026 {
1027 fModifiers &= ~(cmdKey | kEventKeyModifierRightCmdKeyMask);
1028 fModifiers |= fAltModifiers & (cmdKey | kEventKeyModifierRightCmdKeyMask);
1029 }
1030#ifdef DEBUG_PRINTF
1031 RTPrintf(" -> %#x\n", fModifiers);
1032#endif
1033 }
1034 return fModifiers;
1035}
1036
1037
1038/**
1039 * Start grabbing keyboard events.
1040 *
1041 * This only concerns itself with modifiers and disabling global hotkeys (if requested).
1042 *
1043 * @param fGlobalHotkeys Whether to disable global hotkeys or not.
1044 */
1045void DarwinGrabKeyboard(bool fGlobalHotkeys)
1046{
1047 LogFlow(("DarwinGrabKeyboard: fGlobalHotkeys=%RTbool\n", fGlobalHotkeys));
1048
1049#ifdef USE_HID_FOR_MODIFIERS
1050 /*
1051 * Update the keyboard cache.
1052 */
1053 darwinHIDKeyboardCacheUpdate();
1054
1055 /*
1056 * Start the keyboard queues and query the current mask.
1057 */
1058 g_fHIDQueueEnabled = true;
1059
1060 unsigned i = g_cKeyboards;
1061 while (i-- > 0)
1062 {
1063 if (g_aKeyboards[i].ppHidQueueInterface)
1064 (*g_aKeyboards[i].ppHidQueueInterface)->start(g_aKeyboards[i].ppHidQueueInterface);
1065 }
1066
1067 g_fHIDModifierMask = darwinQueryHIDModifiers();
1068#endif /* USE_HID_FOR_MODIFIERS */
1069
1070 /*
1071 * Disable hotkeys if requested.
1072 */
1073 if (fGlobalHotkeys)
1074 DarwinDisableGlobalHotKeys(true);
1075}
1076
1077
1078/**
1079 * Reverses the actions taken by DarwinGrabKeyboard.
1080 */
1081void DarwinReleaseKeyboard(void)
1082{
1083 LogFlow(("DarwinReleaseKeyboard\n"));
1084
1085 /*
1086 * Re-enable hotkeys.
1087 */
1088 DarwinDisableGlobalHotKeys(false);
1089
1090#ifdef USE_HID_FOR_MODIFIERS
1091 /*
1092 * Stop and drain the keyboard queues.
1093 */
1094 g_fHIDQueueEnabled = false;
1095
1096#if 0
1097 unsigned i = g_cKeyboards;
1098 while (i-- > 0)
1099 {
1100 if (g_aKeyboards[i].ppHidQueueInterface)
1101 {
1102
1103 (*g_aKeyboards[i].ppHidQueueInterface)->stop(g_aKeyboards[i].ppHidQueueInterface);
1104
1105 /* drain it */
1106 IOReturn rc;
1107 unsigned c = 0;
1108 do
1109 {
1110 IOHIDEventStruct Event;
1111 AbsoluteTime MaxTime = {0,0};
1112 rc = (*g_aKeyboards[i].ppHidQueueInterface)->getNextEvent(g_aKeyboards[i].ppHidQueueInterface,
1113 &Event, MaxTime, 0);
1114 } while ( rc == kIOReturnSuccess
1115 && c++ < 32);
1116 }
1117 }
1118#else
1119
1120 /*
1121 * Kill the keyboard cache.
1122 * This will hopefully fix the crash in getElementValue()/fillElementValue()...
1123 */
1124 darwinHIDKeyboardCacheZap();
1125#endif
1126
1127 /* Clear the modifier mask. */
1128 g_fHIDModifierMask = 0;
1129#endif /* USE_HID_FOR_MODIFIERS */
1130}
1131
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