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