src/joystick/darwin/SDL_sysjoystick.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 08 Nov 2008 07:34:21 +0000
changeset 2776 caf3d5b2153f
parent 2735 204be4fc2726
child 2859 99210400e8b9
permissions -rw-r--r--
Sort by HID usage, which makes more sense and is more cross-platform
     1 /*
     2 	SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2004 Sam Lantinga
     4 
     5 	This library is free software; you can redistribute it and/or
     6 	modify it under the terms of the GNU Library General Public
     7 	License as published by the Free Software Foundation; either
     8 	version 2 of the License, or (at your option) any later version.
     9 
    10 	This library is distributed in the hope that it will be useful,
    11 	but WITHOUT ANY WARRANTY; without even the implied warranty of
    12 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13 	Library General Public License for more details.
    14 
    15 	You should have received a copy of the GNU Library General Public
    16 	License along with this library; if not, write to the Free
    17 	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    18 
    19 	Sam Lantinga
    20 	slouken@libsdl.org
    21 */
    22 #include "SDL_config.h"
    23 
    24 #ifdef SDL_JOYSTICK_IOKIT
    25 
    26 /* SDL joystick driver for Darwin / Mac OS X, based on the IOKit HID API */
    27 /* Written 2001 by Max Horn */
    28 
    29 #include <unistd.h>
    30 #include <ctype.h>
    31 #include <sysexits.h>
    32 #include <mach/mach.h>
    33 #include <mach/mach_error.h>
    34 #include <IOKit/IOKitLib.h>
    35 #include <IOKit/IOCFPlugIn.h>
    36 #ifdef MACOS_10_0_4
    37 #include <IOKit/hidsystem/IOHIDUsageTables.h>
    38 #else
    39 /* The header was moved here in Mac OS X 10.1 */
    40 #include <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
    41 #endif
    42 #if MAC_OS_X_VERSION_MIN_REQUIRED == 1030
    43 #include "10.3.9-FIX/IOHIDLib.h"
    44 #else
    45 #include <IOKit/hid/IOHIDLib.h>
    46 #endif
    47 #include <IOKit/hid/IOHIDKeys.h>
    48 #include <CoreFoundation/CoreFoundation.h>
    49 #include <Carbon/Carbon.h>      /* for NewPtrClear, DisposePtr */
    50 
    51 /* For force feedback testing. */
    52 #include <ForceFeedback/ForceFeedback.h>
    53 #include <ForceFeedback/ForceFeedbackConstants.h>
    54 
    55 #include "SDL_joystick.h"
    56 #include "../SDL_sysjoystick.h"
    57 #include "../SDL_joystick_c.h"
    58 #include "SDL_sysjoystick_c.h"
    59 
    60 
    61 /* Linked list of all available devices */
    62 static recDevice *gpDeviceList = NULL;
    63 
    64 
    65 static void
    66 HIDReportErrorNum(char *strError, long numError)
    67 {
    68     SDL_SetError(strError);
    69 }
    70 
    71 static void HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
    72                                      recDevice * pDevice);
    73 
    74 /* returns current value for element, polling element
    75  * will return 0 on error conditions which should be accounted for by application
    76  */
    77 
    78 static SInt32
    79 HIDGetElementValue(recDevice * pDevice, recElement * pElement)
    80 {
    81     IOReturn result = kIOReturnSuccess;
    82     IOHIDEventStruct hidEvent;
    83     hidEvent.value = 0;
    84 
    85     if (NULL != pDevice && NULL != pElement && NULL != pDevice->interface) {
    86         result =
    87             (*(pDevice->interface))->getElementValue(pDevice->interface,
    88                                                      pElement->cookie,
    89                                                      &hidEvent);
    90         if (kIOReturnSuccess == result) {
    91             /* record min and max for auto calibration */
    92             if (hidEvent.value < pElement->minReport)
    93                 pElement->minReport = hidEvent.value;
    94             if (hidEvent.value > pElement->maxReport)
    95                 pElement->maxReport = hidEvent.value;
    96         }
    97     }
    98 
    99     /* auto user scale */
   100     return hidEvent.value;
   101 }
   102 
   103 static SInt32
   104 HIDScaledCalibratedValue(recDevice * pDevice, recElement * pElement,
   105                          long min, long max)
   106 {
   107     float deviceScale = max - min;
   108     float readScale = pElement->maxReport - pElement->minReport;
   109     SInt32 value = HIDGetElementValue(pDevice, pElement);
   110     if (readScale == 0)
   111         return value;           /* no scaling at all */
   112     else
   113         return ((value - pElement->minReport) * deviceScale / readScale) +
   114             min;
   115 }
   116 
   117 
   118 static void
   119 HIDRemovalCallback(void *target, IOReturn result, void *refcon, void *sender)
   120 {
   121     recDevice *device = (recDevice *) refcon;
   122     device->removed = 1;
   123     device->uncentered = 1;
   124 }
   125 
   126 
   127 
   128 /* Create and open an interface to device, required prior to extracting values or building queues.
   129  * Note: appliction now owns the device and must close and release it prior to exiting
   130  */
   131 
   132 static IOReturn
   133 HIDCreateOpenDeviceInterface(io_object_t hidDevice, recDevice * pDevice)
   134 {
   135     IOReturn result = kIOReturnSuccess;
   136     HRESULT plugInResult = S_OK;
   137     SInt32 score = 0;
   138     IOCFPlugInInterface **ppPlugInInterface = NULL;
   139 
   140     if (NULL == pDevice->interface) {
   141         result =
   142             IOCreatePlugInInterfaceForService(hidDevice,
   143                                               kIOHIDDeviceUserClientTypeID,
   144                                               kIOCFPlugInInterfaceID,
   145                                               &ppPlugInInterface, &score);
   146         if (kIOReturnSuccess == result) {
   147             /* Call a method of the intermediate plug-in to create the device interface */
   148             plugInResult =
   149                 (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
   150                                                      CFUUIDGetUUIDBytes
   151                                                      (kIOHIDDeviceInterfaceID),
   152                                                      (void *)
   153                                                      &(pDevice->interface));
   154             if (S_OK != plugInResult)
   155                 HIDReportErrorNum
   156                     ("CouldnŐt query HID class device interface from plugInInterface",
   157                      plugInResult);
   158             (*ppPlugInInterface)->Release(ppPlugInInterface);
   159         } else
   160             HIDReportErrorNum
   161                 ("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.",
   162                  result);
   163     }
   164     if (NULL != pDevice->interface) {
   165         result = (*(pDevice->interface))->open(pDevice->interface, 0);
   166         if (kIOReturnSuccess != result)
   167             HIDReportErrorNum
   168                 ("Failed to open pDevice->interface via open.", result);
   169         else
   170             (*(pDevice->interface))->setRemovalCallback(pDevice->interface,
   171                                                         HIDRemovalCallback,
   172                                                         pDevice, pDevice);
   173 
   174     }
   175     return result;
   176 }
   177 
   178 /* Closes and releases interface to device, should be done prior to exting application
   179  * Note: will have no affect if device or interface do not exist
   180  * application will "own" the device if interface is not closed
   181  * (device may have to be plug and re-plugged in different location to get it working again without a restart)
   182  */
   183 
   184 static IOReturn
   185 HIDCloseReleaseInterface(recDevice * pDevice)
   186 {
   187     IOReturn result = kIOReturnSuccess;
   188 
   189     if ((NULL != pDevice) && (NULL != pDevice->interface)) {
   190         /* close the interface */
   191         result = (*(pDevice->interface))->close(pDevice->interface);
   192         if (kIOReturnNotOpen == result) {
   193             /* do nothing as device was not opened, thus can't be closed */
   194         } else if (kIOReturnSuccess != result)
   195             HIDReportErrorNum("Failed to close IOHIDDeviceInterface.",
   196                               result);
   197         /* release the interface */
   198         result = (*(pDevice->interface))->Release(pDevice->interface);
   199         if (kIOReturnSuccess != result)
   200             HIDReportErrorNum("Failed to release IOHIDDeviceInterface.",
   201                               result);
   202         pDevice->interface = NULL;
   203     }
   204     return result;
   205 }
   206 
   207 /* extracts actual specific element information from each element CF dictionary entry */
   208 
   209 static void
   210 HIDGetElementInfo(CFTypeRef refElement, recElement * pElement)
   211 {
   212     long number;
   213     CFTypeRef refType;
   214 
   215     refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementCookieKey));
   216     if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
   217         pElement->cookie = (IOHIDElementCookie) number;
   218     refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMinKey));
   219     if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
   220         pElement->minReport = pElement->min = number;
   221     pElement->maxReport = pElement->min;
   222     refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMaxKey));
   223     if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
   224         pElement->maxReport = pElement->max = number;
   225 /*
   226 	TODO: maybe should handle the following stuff somehow?
   227 
   228 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
   229 	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
   230 		pElement->scaledMin = number;
   231 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
   232 	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
   233 		pElement->scaledMax = number;
   234 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
   235 	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
   236 		pElement->size = number;
   237 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
   238 	if (refType)
   239 		pElement->relative = CFBooleanGetValue (refType);
   240 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
   241 	if (refType)
   242 		pElement->wrapping = CFBooleanGetValue (refType);
   243 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
   244 	if (refType)
   245 		pElement->nonLinear = CFBooleanGetValue (refType);
   246 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
   247 	if (refType)
   248 		pElement->preferredState = CFBooleanGetValue (refType);
   249 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
   250 	if (refType)
   251 		pElement->nullState = CFBooleanGetValue (refType);
   252 */
   253 }
   254 
   255 /* examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements
   256  * if element of interest allocate storage, add to list and retrieve element specific info
   257  * if collection then pass on to deconstruction collection into additional individual elements
   258  */
   259 
   260 static void
   261 HIDAddElement(CFTypeRef refElement, recDevice * pDevice)
   262 {
   263     recElement *element = NULL;
   264     recElement **headElement = NULL;
   265     long elementType, usagePage, usage;
   266     CFTypeRef refElementType =
   267         CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementTypeKey));
   268     CFTypeRef refUsagePage =
   269         CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsagePageKey));
   270     CFTypeRef refUsage =
   271         CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsageKey));
   272 
   273 
   274     if ((refElementType)
   275         &&
   276         (CFNumberGetValue(refElementType, kCFNumberLongType, &elementType))) {
   277         /* look at types of interest */
   278         if ((elementType == kIOHIDElementTypeInput_Misc)
   279             || (elementType == kIOHIDElementTypeInput_Button)
   280             || (elementType == kIOHIDElementTypeInput_Axis)) {
   281             if (refUsagePage
   282                 && CFNumberGetValue(refUsagePage, kCFNumberLongType,
   283                                     &usagePage) && refUsage
   284                 && CFNumberGetValue(refUsage, kCFNumberLongType, &usage)) {
   285                 switch (usagePage) {    /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */
   286                 case kHIDPage_GenericDesktop:
   287                     {
   288                         switch (usage) {        /* look at usage to determine function */
   289                         case kHIDUsage_GD_X:
   290                         case kHIDUsage_GD_Y:
   291                         case kHIDUsage_GD_Z:
   292                         case kHIDUsage_GD_Rx:
   293                         case kHIDUsage_GD_Ry:
   294                         case kHIDUsage_GD_Rz:
   295                         case kHIDUsage_GD_Slider:
   296                         case kHIDUsage_GD_Dial:
   297                         case kHIDUsage_GD_Wheel:
   298                             element = (recElement *)
   299                                 NewPtrClear(sizeof(recElement));
   300                             if (element) {
   301                                 pDevice->axes++;
   302                                 headElement = &(pDevice->firstAxis);
   303                             }
   304                             break;
   305                         case kHIDUsage_GD_Hatswitch:
   306                             element = (recElement *)
   307                                 NewPtrClear(sizeof(recElement));
   308                             if (element) {
   309                                 pDevice->hats++;
   310                                 headElement = &(pDevice->firstHat);
   311                             }
   312                             break;
   313                         }
   314                     }
   315                     break;
   316                 case kHIDPage_Button:
   317                     element = (recElement *)
   318                         NewPtrClear(sizeof(recElement));
   319                     if (element) {
   320                         pDevice->buttons++;
   321                         headElement = &(pDevice->firstButton);
   322                     }
   323                     break;
   324                 default:
   325                     break;
   326                 }
   327             }
   328         } else if (kIOHIDElementTypeCollection == elementType)
   329             HIDGetCollectionElements((CFMutableDictionaryRef) refElement,
   330                                      pDevice);
   331     }
   332 
   333     if (element && headElement) {       /* add to list */
   334         recElement *elementPrevious = NULL;
   335         recElement *elementCurrent = *headElement;
   336         while (elementCurrent && usage >= elementCurrent->usage) {
   337             elementPrevious = elementCurrent;
   338             elementCurrent = elementCurrent->pNext;
   339         }
   340         if (elementPrevious) {
   341             elementPrevious->pNext = element;
   342         } else {
   343             *headElement = element;
   344         }
   345         element->usagePage = usagePage;
   346         element->usage = usage;
   347         element->pNext = elementCurrent;
   348         HIDGetElementInfo(refElement, element);
   349         pDevice->elements++;
   350     }
   351 }
   352 
   353 /* collects information from each array member in device element list (each array memeber = element) */
   354 
   355 static void
   356 HIDGetElementsCFArrayHandler(const void *value, void *parameter)
   357 {
   358     if (CFGetTypeID(value) == CFDictionaryGetTypeID())
   359         HIDAddElement((CFTypeRef) value, (recDevice *) parameter);
   360 }
   361 
   362 /* handles retrieval of element information from arrays of elements in device IO registry information */
   363 
   364 static void
   365 HIDGetElements(CFTypeRef refElementCurrent, recDevice * pDevice)
   366 {
   367     CFTypeID type = CFGetTypeID(refElementCurrent);
   368     if (type == CFArrayGetTypeID()) {   /* if element is an array */
   369         CFRange range = { 0, CFArrayGetCount(refElementCurrent) };
   370         /* CountElementsCFArrayHandler called for each array member */
   371         CFArrayApplyFunction(refElementCurrent, range,
   372                              HIDGetElementsCFArrayHandler, pDevice);
   373     }
   374 }
   375 
   376 /* handles extracting element information from element collection CF types
   377  * used from top level element decoding and hierarchy deconstruction to flatten device element list
   378  */
   379 
   380 static void
   381 HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
   382                          recDevice * pDevice)
   383 {
   384     CFTypeRef refElementTop =
   385         CFDictionaryGetValue(deviceProperties, CFSTR(kIOHIDElementKey));
   386     if (refElementTop)
   387         HIDGetElements(refElementTop, pDevice);
   388 }
   389 
   390 /* use top level element usage page and usage to discern device usage page and usage setting appropriate vlaues in device record */
   391 
   392 static void
   393 HIDTopLevelElementHandler(const void *value, void *parameter)
   394 {
   395     CFTypeRef refCF = 0;
   396     if (CFGetTypeID(value) != CFDictionaryGetTypeID())
   397         return;
   398     refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsagePageKey));
   399     if (!CFNumberGetValue
   400         (refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage))
   401         SDL_SetError("CFNumberGetValue error retrieving pDevice->usagePage.");
   402     refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsageKey));
   403     if (!CFNumberGetValue
   404         (refCF, kCFNumberLongType, &((recDevice *) parameter)->usage))
   405         SDL_SetError("CFNumberGetValue error retrieving pDevice->usage.");
   406 }
   407 
   408 /* extracts device info from CF dictionary records in IO registry */
   409 
   410 static void
   411 HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties,
   412                  recDevice * pDevice)
   413 {
   414     CFMutableDictionaryRef usbProperties = 0;
   415     io_registry_entry_t parent1, parent2;
   416 
   417     /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
   418      * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
   419      */
   420     if ((KERN_SUCCESS ==
   421          IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1))
   422         && (KERN_SUCCESS ==
   423             IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))
   424         && (KERN_SUCCESS ==
   425             IORegistryEntryCreateCFProperties(parent2, &usbProperties,
   426                                               kCFAllocatorDefault,
   427                                               kNilOptions))) {
   428         if (usbProperties) {
   429             CFTypeRef refCF = 0;
   430             /* get device info
   431              * try hid dictionary first, if fail then go to usb dictionary
   432              */
   433 
   434 
   435             /* get product name */
   436             refCF =
   437                 CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey));
   438             if (!refCF)
   439                 refCF =
   440                     CFDictionaryGetValue(usbProperties,
   441                                          CFSTR("USB Product Name"));
   442             if (refCF) {
   443                 if (!CFStringGetCString
   444                     (refCF, pDevice->product, 256,
   445                      CFStringGetSystemEncoding()))
   446                     SDL_SetError
   447                         ("CFStringGetCString error retrieving pDevice->product.");
   448             }
   449 
   450             /* get usage page and usage */
   451             refCF =
   452                 CFDictionaryGetValue(hidProperties,
   453                                      CFSTR(kIOHIDPrimaryUsagePageKey));
   454             if (refCF) {
   455                 if (!CFNumberGetValue
   456                     (refCF, kCFNumberLongType, &pDevice->usagePage))
   457                     SDL_SetError
   458                         ("CFNumberGetValue error retrieving pDevice->usagePage.");
   459                 refCF =
   460                     CFDictionaryGetValue(hidProperties,
   461                                          CFSTR(kIOHIDPrimaryUsageKey));
   462                 if (refCF)
   463                     if (!CFNumberGetValue
   464                         (refCF, kCFNumberLongType, &pDevice->usage))
   465                         SDL_SetError
   466                             ("CFNumberGetValue error retrieving pDevice->usage.");
   467             }
   468 
   469             if (NULL == refCF) {        /* get top level element HID usage page or usage */
   470                 /* use top level element instead */
   471                 CFTypeRef refCFTopElement = 0;
   472                 refCFTopElement =
   473                     CFDictionaryGetValue(hidProperties,
   474                                          CFSTR(kIOHIDElementKey));
   475                 {
   476                     /* refCFTopElement points to an array of element dictionaries */
   477                     CFRange range = { 0, CFArrayGetCount(refCFTopElement) };
   478                     CFArrayApplyFunction(refCFTopElement, range,
   479                                          HIDTopLevelElementHandler, pDevice);
   480                 }
   481             }
   482 
   483             CFRelease(usbProperties);
   484         } else
   485             SDL_SetError
   486                 ("IORegistryEntryCreateCFProperties failed to create usbProperties.");
   487 
   488         if (kIOReturnSuccess != IOObjectRelease(parent2))
   489             SDL_SetError("IOObjectRelease error with parent2.");
   490         if (kIOReturnSuccess != IOObjectRelease(parent1))
   491             SDL_SetError("IOObjectRelease error with parent1.");
   492     }
   493 }
   494 
   495 
   496 static recDevice *
   497 HIDBuildDevice(io_object_t hidDevice)
   498 {
   499     recDevice *pDevice = (recDevice *) NewPtrClear(sizeof(recDevice));
   500     if (pDevice) {
   501         /* get dictionary for HID properties */
   502         CFMutableDictionaryRef hidProperties = 0;
   503         kern_return_t result =
   504             IORegistryEntryCreateCFProperties(hidDevice, &hidProperties,
   505                                               kCFAllocatorDefault,
   506                                               kNilOptions);
   507         if ((result == KERN_SUCCESS) && hidProperties) {
   508             /* create device interface */
   509             result = HIDCreateOpenDeviceInterface(hidDevice, pDevice);
   510             if (kIOReturnSuccess == result) {
   511                 HIDGetDeviceInfo(hidDevice, hidProperties, pDevice);    /* hidDevice used to find parents in registry tree */
   512                 HIDGetCollectionElements(hidProperties, pDevice);
   513             } else {
   514                 DisposePtr((Ptr) pDevice);
   515                 pDevice = NULL;
   516             }
   517             CFRelease(hidProperties);
   518         } else {
   519             DisposePtr((Ptr) pDevice);
   520             pDevice = NULL;
   521         }
   522     }
   523     return pDevice;
   524 }
   525 
   526 /* disposes of the element list associated with a device and the memory associated with the list
   527  */
   528 
   529 static void
   530 HIDDisposeElementList(recElement ** elementList)
   531 {
   532     recElement *pElement = *elementList;
   533     while (pElement) {
   534         recElement *pElementNext = pElement->pNext;
   535         DisposePtr((Ptr) pElement);
   536         pElement = pElementNext;
   537     }
   538     *elementList = NULL;
   539 }
   540 
   541 /* disposes of a single device, closing and releaseing interface, freeing memory fro device and elements, setting device pointer to NULL
   542  * all your device no longer belong to us... (i.e., you do not 'own' the device anymore)
   543  */
   544 
   545 static recDevice *
   546 HIDDisposeDevice(recDevice ** ppDevice)
   547 {
   548     kern_return_t result = KERN_SUCCESS;
   549     recDevice *pDeviceNext = NULL;
   550     if (*ppDevice) {
   551         /* save next device prior to disposing of this device */
   552         pDeviceNext = (*ppDevice)->pNext;
   553 
   554         /* free posible io_service_t */
   555         if ((*ppDevice)->ffservice) {
   556             IOObjectRelease((*ppDevice)->ffservice);
   557             (*ppDevice)->ffservice = 0;
   558         }
   559 
   560         /* free element lists */
   561         HIDDisposeElementList(&(*ppDevice)->firstAxis);
   562         HIDDisposeElementList(&(*ppDevice)->firstButton);
   563         HIDDisposeElementList(&(*ppDevice)->firstHat);
   564 
   565         result = HIDCloseReleaseInterface(*ppDevice);   /* function sanity checks interface value (now application does not own device) */
   566         if (kIOReturnSuccess != result)
   567             HIDReportErrorNum
   568                 ("HIDCloseReleaseInterface failed when trying to dipose device.",
   569                  result);
   570         DisposePtr((Ptr) * ppDevice);
   571         *ppDevice = NULL;
   572     }
   573     return pDeviceNext;
   574 }
   575 
   576 
   577 /* Function to scan the system for joysticks.
   578  * Joystick 0 should be the system default joystick.
   579  * This function should return the number of available joysticks, or -1
   580  * on an unrecoverable fatal error.
   581  */
   582 int
   583 SDL_SYS_JoystickInit(void)
   584 {
   585     IOReturn result = kIOReturnSuccess;
   586     mach_port_t masterPort = 0;
   587     io_iterator_t hidObjectIterator = 0;
   588     CFMutableDictionaryRef hidMatchDictionary = NULL;
   589     recDevice *device, *lastDevice;
   590     io_object_t ioHIDDeviceObject = 0;
   591 
   592     SDL_numjoysticks = 0;
   593 
   594     if (gpDeviceList) {
   595         SDL_SetError("Joystick: Device list already inited.");
   596         return -1;
   597     }
   598 
   599     result = IOMasterPort(bootstrap_port, &masterPort);
   600     if (kIOReturnSuccess != result) {
   601         SDL_SetError("Joystick: IOMasterPort error with bootstrap_port.");
   602         return -1;
   603     }
   604 
   605     /* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */
   606     hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
   607     if (hidMatchDictionary) {
   608         /* Add key for device type (joystick, in this case) to refine the matching dictionary. */
   609 
   610         /* NOTE: we now perform this filtering later
   611            UInt32 usagePage = kHIDPage_GenericDesktop;
   612            UInt32 usage = kHIDUsage_GD_Joystick;
   613            CFNumberRef refUsage = NULL, refUsagePage = NULL;
   614 
   615            refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage);
   616            CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage);
   617            refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage);
   618            CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage);
   619          */
   620     } else {
   621         SDL_SetError
   622             ("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching.");
   623         return -1;
   624     }
   625 
   626     /*/ Now search I/O Registry for matching devices. */
   627     result =
   628         IOServiceGetMatchingServices(masterPort, hidMatchDictionary,
   629                                      &hidObjectIterator);
   630     /* Check for errors */
   631     if (kIOReturnSuccess != result) {
   632         SDL_SetError("Joystick: Couldn't create a HID object iterator.");
   633         return -1;
   634     }
   635     if (!hidObjectIterator) {   /* there are no joysticks */
   636         gpDeviceList = NULL;
   637         SDL_numjoysticks = 0;
   638         return 0;
   639     }
   640     /* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */
   641 
   642     /* build flat linked list of devices from device iterator */
   643 
   644     gpDeviceList = lastDevice = NULL;
   645 
   646     while ((ioHIDDeviceObject = IOIteratorNext(hidObjectIterator))) {
   647         /* build a device record */
   648         device = HIDBuildDevice(ioHIDDeviceObject);
   649         if (!device)
   650             continue;
   651 
   652         /* Filter device list to non-keyboard/mouse stuff */
   653         if ((device->usagePage != kHIDPage_GenericDesktop) ||
   654             ((device->usage != kHIDUsage_GD_Joystick &&
   655               device->usage != kHIDUsage_GD_GamePad &&
   656               device->usage != kHIDUsage_GD_MultiAxisController))) {
   657 
   658             /* release memory for the device */
   659             HIDDisposeDevice(&device);
   660             DisposePtr((Ptr) device);
   661             continue;
   662         }
   663 
   664         /* We have to do some storage of the io_service_t for
   665          * SDL_HapticOpenFromJoystick */
   666         if (FFIsForceFeedback(ioHIDDeviceObject) == FF_OK) {
   667             device->ffservice = ioHIDDeviceObject;
   668         } else {
   669             device->ffservice = 0;
   670         }
   671 
   672         /* Add device to the end of the list */
   673         if (lastDevice)
   674             lastDevice->pNext = device;
   675         else
   676             gpDeviceList = device;
   677         lastDevice = device;
   678     }
   679     result = IOObjectRelease(hidObjectIterator);        /* release the iterator */
   680 
   681     /* Count the total number of devices we found */
   682     device = gpDeviceList;
   683     while (device) {
   684         SDL_numjoysticks++;
   685         device = device->pNext;
   686     }
   687 
   688     return SDL_numjoysticks;
   689 }
   690 
   691 /* Function to get the device-dependent name of a joystick */
   692 const char *
   693 SDL_SYS_JoystickName(int index)
   694 {
   695     recDevice *device = gpDeviceList;
   696 
   697     for (; index > 0; index--)
   698         device = device->pNext;
   699 
   700     return device->product;
   701 }
   702 
   703 /* Function to open a joystick for use.
   704  * The joystick to open is specified by the index field of the joystick.
   705  * This should fill the nbuttons and naxes fields of the joystick structure.
   706  * It returns 0, or -1 if there is an error.
   707  */
   708 int
   709 SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
   710 {
   711     recDevice *device = gpDeviceList;
   712     int index;
   713 
   714     for (index = joystick->index; index > 0; index--)
   715         device = device->pNext;
   716 
   717     joystick->hwdata = device;
   718     joystick->name = device->product;
   719 
   720     joystick->naxes = device->axes;
   721     joystick->nhats = device->hats;
   722     joystick->nballs = 0;
   723     joystick->nbuttons = device->buttons;
   724 
   725     return 0;
   726 }
   727 
   728 /* Function to update the state of a joystick - called as a device poll.
   729  * This function shouldn't update the joystick structure directly,
   730  * but instead should call SDL_PrivateJoystick*() to deliver events
   731  * and update joystick device state.
   732  */
   733 void
   734 SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
   735 {
   736     recDevice *device = joystick->hwdata;
   737     recElement *element;
   738     SInt32 value, range;
   739     int i;
   740 
   741     if (device->removed) {      /* device was unplugged; ignore it. */
   742         if (device->uncentered) {
   743             device->uncentered = 0;
   744 
   745             /* Tell the app that everything is centered/unpressed... */
   746             for (i = 0; i < device->axes; i++)
   747                 SDL_PrivateJoystickAxis(joystick, i, 0);
   748 
   749             for (i = 0; i < device->buttons; i++)
   750                 SDL_PrivateJoystickButton(joystick, i, 0);
   751 
   752             for (i = 0; i < device->hats; i++)
   753                 SDL_PrivateJoystickHat(joystick, i, SDL_HAT_CENTERED);
   754         }
   755 
   756         return;
   757     }
   758 
   759     element = device->firstAxis;
   760     i = 0;
   761     while (element) {
   762         value = HIDScaledCalibratedValue(device, element, -32768, 32767);
   763         if (value != joystick->axes[i])
   764             SDL_PrivateJoystickAxis(joystick, i, value);
   765         element = element->pNext;
   766         ++i;
   767     }
   768 
   769     element = device->firstButton;
   770     i = 0;
   771     while (element) {
   772         value = HIDGetElementValue(device, element);
   773         if (value > 1)          /* handle pressure-sensitive buttons */
   774             value = 1;
   775         if (value != joystick->buttons[i])
   776             SDL_PrivateJoystickButton(joystick, i, value);
   777         element = element->pNext;
   778         ++i;
   779     }
   780 
   781     element = device->firstHat;
   782     i = 0;
   783     while (element) {
   784         Uint8 pos = 0;
   785 
   786         range = (element->max - element->min + 1);
   787         value = HIDGetElementValue(device, element) - element->min;
   788         if (range == 4)         /* 4 position hatswitch - scale up value */
   789             value *= 2;
   790         else if (range != 8)    /* Neither a 4 nor 8 positions - fall back to default position (centered) */
   791             value = -1;
   792         switch (value) {
   793         case 0:
   794             pos = SDL_HAT_UP;
   795             break;
   796         case 1:
   797             pos = SDL_HAT_RIGHTUP;
   798             break;
   799         case 2:
   800             pos = SDL_HAT_RIGHT;
   801             break;
   802         case 3:
   803             pos = SDL_HAT_RIGHTDOWN;
   804             break;
   805         case 4:
   806             pos = SDL_HAT_DOWN;
   807             break;
   808         case 5:
   809             pos = SDL_HAT_LEFTDOWN;
   810             break;
   811         case 6:
   812             pos = SDL_HAT_LEFT;
   813             break;
   814         case 7:
   815             pos = SDL_HAT_LEFTUP;
   816             break;
   817         default:
   818             /* Every other value is mapped to center. We do that because some
   819              * joysticks use 8 and some 15 for this value, and apparently
   820              * there are even more variants out there - so we try to be generous.
   821              */
   822             pos = SDL_HAT_CENTERED;
   823             break;
   824         }
   825         if (pos != joystick->hats[i])
   826             SDL_PrivateJoystickHat(joystick, i, pos);
   827         element = element->pNext;
   828         ++i;
   829     }
   830 
   831     return;
   832 }
   833 
   834 /* Function to close a joystick after use */
   835 void
   836 SDL_SYS_JoystickClose(SDL_Joystick * joystick)
   837 {
   838     /* Should we do anything here? */
   839     return;
   840 }
   841 
   842 /* Function to perform any system-specific joystick related cleanup */
   843 void
   844 SDL_SYS_JoystickQuit(void)
   845 {
   846     while (NULL != gpDeviceList)
   847         gpDeviceList = HIDDisposeDevice(&gpDeviceList);
   848 }
   849 
   850 #endif /* SDL_JOYSTICK_IOKIT */
   851 /* vi: set ts=4 sw=4 expandtab: */