src/joystick/darwin/SDL_sysjoystick.c
author Edgar Simo <bobbens@gmail.com>
Sun, 10 Aug 2008 19:45:38 +0000
branchgsoc2008_force_feedback
changeset 2637 2f826c229d77
parent 2632 9e7f58b1b255
child 2638 db93456d4b26
permissions -rw-r--r--
First draft of darwin haptic<->joystick stuff.
     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 #include "SDL_joystick.h"
    52 #include "../SDL_sysjoystick.h"
    53 #include "../SDL_joystick_c.h"
    54 #include "SDL_sysjoystick_c.h"
    55 
    56 
    57 /* Linked list of all available devices */
    58 static recDevice *gpDeviceList = NULL;
    59 
    60 
    61 static void
    62 HIDReportErrorNum(char *strError, long numError)
    63 {
    64     SDL_SetError(strError);
    65 }
    66 
    67 static void HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
    68                                      recDevice * pDevice);
    69 
    70 /* returns current value for element, polling element
    71  * will return 0 on error conditions which should be accounted for by application
    72  */
    73 
    74 static SInt32
    75 HIDGetElementValue(recDevice * pDevice, recElement * pElement)
    76 {
    77     IOReturn result = kIOReturnSuccess;
    78     IOHIDEventStruct hidEvent;
    79     hidEvent.value = 0;
    80 
    81     if (NULL != pDevice && NULL != pElement && NULL != pDevice->interface) {
    82         result =
    83             (*(pDevice->interface))->getElementValue(pDevice->interface,
    84                                                      pElement->cookie,
    85                                                      &hidEvent);
    86         if (kIOReturnSuccess == result) {
    87             /* record min and max for auto calibration */
    88             if (hidEvent.value < pElement->minReport)
    89                 pElement->minReport = hidEvent.value;
    90             if (hidEvent.value > pElement->maxReport)
    91                 pElement->maxReport = hidEvent.value;
    92         }
    93     }
    94 
    95     /* auto user scale */
    96     return hidEvent.value;
    97 }
    98 
    99 static SInt32
   100 HIDScaledCalibratedValue(recDevice * pDevice, recElement * pElement,
   101                          long min, long max)
   102 {
   103     float deviceScale = max - min;
   104     float readScale = pElement->maxReport - pElement->minReport;
   105     SInt32 value = HIDGetElementValue(pDevice, pElement);
   106     if (readScale == 0)
   107         return value;           /* no scaling at all */
   108     else
   109         return ((value - pElement->minReport) * deviceScale / readScale) +
   110             min;
   111 }
   112 
   113 
   114 static void
   115 HIDRemovalCallback(void *target, IOReturn result, void *refcon, void *sender)
   116 {
   117     recDevice *device = (recDevice *) refcon;
   118     device->removed = 1;
   119     device->uncentered = 1;
   120 }
   121 
   122 
   123 
   124 /* Create and open an interface to device, required prior to extracting values or building queues.
   125  * Note: appliction now owns the device and must close and release it prior to exiting
   126  */
   127 
   128 static IOReturn
   129 HIDCreateOpenDeviceInterface(io_object_t hidDevice, recDevice * pDevice)
   130 {
   131     IOReturn result = kIOReturnSuccess;
   132     HRESULT plugInResult = S_OK;
   133     SInt32 score = 0;
   134     IOCFPlugInInterface **ppPlugInInterface = NULL;
   135 
   136     if (NULL == pDevice->interface) {
   137         result =
   138             IOCreatePlugInInterfaceForService(hidDevice,
   139                                               kIOHIDDeviceUserClientTypeID,
   140                                               kIOCFPlugInInterfaceID,
   141                                               &ppPlugInInterface, &score);
   142         if (kIOReturnSuccess == result) {
   143             /* Call a method of the intermediate plug-in to create the device interface */
   144             plugInResult =
   145                 (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
   146                                                      CFUUIDGetUUIDBytes
   147                                                      (kIOHIDDeviceInterfaceID),
   148                                                      (void *) &(pDevice->
   149                                                                 interface));
   150             if (S_OK != plugInResult)
   151                 HIDReportErrorNum
   152                     ("CouldnŐt query HID class device interface from plugInInterface",
   153                      plugInResult);
   154             (*ppPlugInInterface)->Release(ppPlugInInterface);
   155         } else
   156             HIDReportErrorNum
   157                 ("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.",
   158                  result);
   159     }
   160     if (NULL != pDevice->interface) {
   161         result = (*(pDevice->interface))->open(pDevice->interface, 0);
   162         if (kIOReturnSuccess != result)
   163             HIDReportErrorNum
   164                 ("Failed to open pDevice->interface via open.", result);
   165         else
   166             (*(pDevice->interface))->setRemovalCallback(pDevice->interface,
   167                                                         HIDRemovalCallback,
   168                                                         pDevice, pDevice);
   169 
   170     }
   171     return result;
   172 }
   173 
   174 /* Closes and releases interface to device, should be done prior to exting application
   175  * Note: will have no affect if device or interface do not exist
   176  * application will "own" the device if interface is not closed
   177  * (device may have to be plug and re-plugged in different location to get it working again without a restart)
   178  */
   179 
   180 static IOReturn
   181 HIDCloseReleaseInterface(recDevice * pDevice)
   182 {
   183     IOReturn result = kIOReturnSuccess;
   184 
   185     if ((NULL != pDevice) && (NULL != pDevice->interface)) {
   186         /* close the interface */
   187         result = (*(pDevice->interface))->close(pDevice->interface);
   188         if (kIOReturnNotOpen == result) {
   189             /* do nothing as device was not opened, thus can't be closed */
   190         } else if (kIOReturnSuccess != result)
   191             HIDReportErrorNum("Failed to close IOHIDDeviceInterface.",
   192                               result);
   193         /* release the interface */
   194         result = (*(pDevice->interface))->Release(pDevice->interface);
   195         if (kIOReturnSuccess != result)
   196             HIDReportErrorNum("Failed to release IOHIDDeviceInterface.",
   197                               result);
   198         pDevice->interface = NULL;
   199     }
   200     return result;
   201 }
   202 
   203 /* extracts actual specific element information from each element CF dictionary entry */
   204 
   205 static void
   206 HIDGetElementInfo(CFTypeRef refElement, recElement * pElement)
   207 {
   208     long number;
   209     CFTypeRef refType;
   210 
   211     refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementCookieKey));
   212     if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
   213         pElement->cookie = (IOHIDElementCookie) number;
   214     refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMinKey));
   215     if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
   216         pElement->minReport = pElement->min = number;
   217     pElement->maxReport = pElement->min;
   218     refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMaxKey));
   219     if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
   220         pElement->maxReport = pElement->max = number;
   221 /*
   222 	TODO: maybe should handle the following stuff somehow?
   223 
   224 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
   225 	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
   226 		pElement->scaledMin = number;
   227 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
   228 	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
   229 		pElement->scaledMax = number;
   230 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
   231 	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
   232 		pElement->size = number;
   233 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
   234 	if (refType)
   235 		pElement->relative = CFBooleanGetValue (refType);
   236 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
   237 	if (refType)
   238 		pElement->wrapping = CFBooleanGetValue (refType);
   239 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
   240 	if (refType)
   241 		pElement->nonLinear = CFBooleanGetValue (refType);
   242 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
   243 	if (refType)
   244 		pElement->preferredState = CFBooleanGetValue (refType);
   245 	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
   246 	if (refType)
   247 		pElement->nullState = CFBooleanGetValue (refType);
   248 */
   249 }
   250 
   251 /* examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements
   252  * if element of interest allocate storage, add to list and retrieve element specific info
   253  * if collection then pass on to deconstruction collection into additional individual elements
   254  */
   255 
   256 static void
   257 HIDAddElement(CFTypeRef refElement, recDevice * pDevice)
   258 {
   259     recElement *element = NULL;
   260     recElement **headElement = NULL;
   261     long elementType, usagePage, usage;
   262     CFTypeRef refElementType =
   263         CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementTypeKey));
   264     CFTypeRef refUsagePage =
   265         CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsagePageKey));
   266     CFTypeRef refUsage =
   267         CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsageKey));
   268 
   269 
   270     if ((refElementType)
   271         &&
   272         (CFNumberGetValue(refElementType, kCFNumberLongType, &elementType))) {
   273         /* look at types of interest */
   274         if ((elementType == kIOHIDElementTypeInput_Misc)
   275             || (elementType == kIOHIDElementTypeInput_Button)
   276             || (elementType == kIOHIDElementTypeInput_Axis)) {
   277             if (refUsagePage
   278                 && CFNumberGetValue(refUsagePage, kCFNumberLongType,
   279                                     &usagePage) && refUsage
   280                 && CFNumberGetValue(refUsage, kCFNumberLongType, &usage)) {
   281                 switch (usagePage) {    /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */
   282                 case kHIDPage_GenericDesktop:
   283                     {
   284                         switch (usage) {        /* look at usage to determine function */
   285                         case kHIDUsage_GD_X:
   286                         case kHIDUsage_GD_Y:
   287                         case kHIDUsage_GD_Z:
   288                         case kHIDUsage_GD_Rx:
   289                         case kHIDUsage_GD_Ry:
   290                         case kHIDUsage_GD_Rz:
   291                         case kHIDUsage_GD_Slider:
   292                         case kHIDUsage_GD_Dial:
   293                         case kHIDUsage_GD_Wheel:
   294                             element = (recElement *)
   295                                 NewPtrClear(sizeof(recElement));
   296                             if (element) {
   297                                 pDevice->axes++;
   298                                 headElement = &(pDevice->firstAxis);
   299                             }
   300                             break;
   301                         case kHIDUsage_GD_Hatswitch:
   302                             element = (recElement *)
   303                                 NewPtrClear(sizeof(recElement));
   304                             if (element) {
   305                                 pDevice->hats++;
   306                                 headElement = &(pDevice->firstHat);
   307                             }
   308                             break;
   309                         }
   310                     }
   311                     break;
   312                 case kHIDPage_Button:
   313                     element = (recElement *)
   314                         NewPtrClear(sizeof(recElement));
   315                     if (element) {
   316                         pDevice->buttons++;
   317                         headElement = &(pDevice->firstButton);
   318                     }
   319                     break;
   320                 default:
   321                     break;
   322                 }
   323             }
   324         } else if (kIOHIDElementTypeCollection == elementType)
   325             HIDGetCollectionElements((CFMutableDictionaryRef) refElement,
   326                                      pDevice);
   327     }
   328 
   329     if (element && headElement) {       /* add to list */
   330         pDevice->elements++;
   331         if (NULL == *headElement)
   332             *headElement = element;
   333         else {
   334             recElement *elementPrevious, *elementCurrent;
   335             elementCurrent = *headElement;
   336             while (elementCurrent) {
   337                 elementPrevious = elementCurrent;
   338                 elementCurrent = elementPrevious->pNext;
   339             }
   340             elementPrevious->pNext = element;
   341         }
   342         element->pNext = NULL;
   343         HIDGetElementInfo(refElement, element);
   344     }
   345 }
   346 
   347 /* collects information from each array member in device element list (each array memeber = element) */
   348 
   349 static void
   350 HIDGetElementsCFArrayHandler(const void *value, void *parameter)
   351 {
   352     if (CFGetTypeID(value) == CFDictionaryGetTypeID())
   353         HIDAddElement((CFTypeRef) value, (recDevice *) parameter);
   354 }
   355 
   356 /* handles retrieval of element information from arrays of elements in device IO registry information */
   357 
   358 static void
   359 HIDGetElements(CFTypeRef refElementCurrent, recDevice * pDevice)
   360 {
   361     CFTypeID type = CFGetTypeID(refElementCurrent);
   362     if (type == CFArrayGetTypeID()) {   /* if element is an array */
   363         CFRange range = { 0, CFArrayGetCount(refElementCurrent) };
   364         /* CountElementsCFArrayHandler called for each array member */
   365         CFArrayApplyFunction(refElementCurrent, range,
   366                              HIDGetElementsCFArrayHandler, pDevice);
   367     }
   368 }
   369 
   370 /* handles extracting element information from element collection CF types
   371  * used from top level element decoding and hierarchy deconstruction to flatten device element list
   372  */
   373 
   374 static void
   375 HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
   376                          recDevice * pDevice)
   377 {
   378     CFTypeRef refElementTop =
   379         CFDictionaryGetValue(deviceProperties, CFSTR(kIOHIDElementKey));
   380     if (refElementTop)
   381         HIDGetElements(refElementTop, pDevice);
   382 }
   383 
   384 /* use top level element usage page and usage to discern device usage page and usage setting appropriate vlaues in device record */
   385 
   386 static void
   387 HIDTopLevelElementHandler(const void *value, void *parameter)
   388 {
   389     CFTypeRef refCF = 0;
   390     if (CFGetTypeID(value) != CFDictionaryGetTypeID())
   391         return;
   392     refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsagePageKey));
   393     if (!CFNumberGetValue
   394         (refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage))
   395         SDL_SetError("CFNumberGetValue error retrieving pDevice->usagePage.");
   396     refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsageKey));
   397     if (!CFNumberGetValue
   398         (refCF, kCFNumberLongType, &((recDevice *) parameter)->usage))
   399         SDL_SetError("CFNumberGetValue error retrieving pDevice->usage.");
   400 }
   401 
   402 /* extracts device info from CF dictionary records in IO registry */
   403 
   404 static void
   405 HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties,
   406                  recDevice * pDevice)
   407 {
   408     CFMutableDictionaryRef usbProperties = 0;
   409     io_registry_entry_t parent1, parent2;
   410 
   411     /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
   412      * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
   413      */
   414     if ((KERN_SUCCESS ==
   415          IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1))
   416         && (KERN_SUCCESS ==
   417             IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))
   418         && (KERN_SUCCESS ==
   419             IORegistryEntryCreateCFProperties(parent2, &usbProperties,
   420                                               kCFAllocatorDefault,
   421                                               kNilOptions))) {
   422         if (usbProperties) {
   423             CFTypeRef refCF = 0;
   424             /* get device info
   425              * try hid dictionary first, if fail then go to usb dictionary
   426              */
   427 
   428 
   429             /* get product name */
   430             refCF =
   431                 CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey));
   432             if (!refCF)
   433                 refCF =
   434                     CFDictionaryGetValue(usbProperties,
   435                                          CFSTR("USB Product Name"));
   436             if (refCF) {
   437                 if (!CFStringGetCString
   438                     (refCF, pDevice->product, 256,
   439                      CFStringGetSystemEncoding()))
   440                     SDL_SetError
   441                         ("CFStringGetCString error retrieving pDevice->product.");
   442             }
   443 
   444             /* get usage page and usage */
   445             refCF =
   446                 CFDictionaryGetValue(hidProperties,
   447                                      CFSTR(kIOHIDPrimaryUsagePageKey));
   448             if (refCF) {
   449                 if (!CFNumberGetValue
   450                     (refCF, kCFNumberLongType, &pDevice->usagePage))
   451                     SDL_SetError
   452                         ("CFNumberGetValue error retrieving pDevice->usagePage.");
   453                 refCF =
   454                     CFDictionaryGetValue(hidProperties,
   455                                          CFSTR(kIOHIDPrimaryUsageKey));
   456                 if (refCF)
   457                     if (!CFNumberGetValue
   458                         (refCF, kCFNumberLongType, &pDevice->usage))
   459                         SDL_SetError
   460                             ("CFNumberGetValue error retrieving pDevice->usage.");
   461             }
   462 
   463             if (NULL == refCF) {        /* get top level element HID usage page or usage */
   464                 /* use top level element instead */
   465                 CFTypeRef refCFTopElement = 0;
   466                 refCFTopElement =
   467                     CFDictionaryGetValue(hidProperties,
   468                                          CFSTR(kIOHIDElementKey));
   469                 {
   470                     /* refCFTopElement points to an array of element dictionaries */
   471                     CFRange range = { 0, CFArrayGetCount(refCFTopElement) };
   472                     CFArrayApplyFunction(refCFTopElement, range,
   473                                          HIDTopLevelElementHandler, pDevice);
   474                 }
   475             }
   476 
   477             CFRelease(usbProperties);
   478         } else
   479             SDL_SetError
   480                 ("IORegistryEntryCreateCFProperties failed to create usbProperties.");
   481 
   482         if (kIOReturnSuccess != IOObjectRelease(parent2))
   483             SDL_SetError("IOObjectRelease error with parent2.");
   484         if (kIOReturnSuccess != IOObjectRelease(parent1))
   485             SDL_SetError("IOObjectRelease error with parent1.");
   486     }
   487 }
   488 
   489 
   490 static recDevice *
   491 HIDBuildDevice(io_object_t hidDevice)
   492 {
   493     recDevice *pDevice = (recDevice *) NewPtrClear(sizeof(recDevice));
   494     if (pDevice) {
   495         /* get dictionary for HID properties */
   496         CFMutableDictionaryRef hidProperties = 0;
   497         kern_return_t result =
   498             IORegistryEntryCreateCFProperties(hidDevice, &hidProperties,
   499                                               kCFAllocatorDefault,
   500                                               kNilOptions);
   501         if ((result == KERN_SUCCESS) && hidProperties) {
   502             /* create device interface */
   503             result = HIDCreateOpenDeviceInterface(hidDevice, pDevice);
   504             if (kIOReturnSuccess == result) {
   505                 HIDGetDeviceInfo(hidDevice, hidProperties, pDevice);    /* hidDevice used to find parents in registry tree */
   506                 HIDGetCollectionElements(hidProperties, pDevice);
   507             } else {
   508                 DisposePtr((Ptr) pDevice);
   509                 pDevice = NULL;
   510             }
   511             CFRelease(hidProperties);
   512         } else {
   513             DisposePtr((Ptr) pDevice);
   514             pDevice = NULL;
   515         }
   516     }
   517     return pDevice;
   518 }
   519 
   520 /* disposes of the element list associated with a device and the memory associated with the list
   521  */
   522 
   523 static void
   524 HIDDisposeElementList(recElement ** elementList)
   525 {
   526     recElement *pElement = *elementList;
   527     while (pElement) {
   528         recElement *pElementNext = pElement->pNext;
   529         DisposePtr((Ptr) pElement);
   530         pElement = pElementNext;
   531     }
   532     *elementList = NULL;
   533 }
   534 
   535 /* disposes of a single device, closing and releaseing interface, freeing memory fro device and elements, setting device pointer to NULL
   536  * all your device no longer belong to us... (i.e., you do not 'own' the device anymore)
   537  */
   538 
   539 static recDevice *
   540 HIDDisposeDevice(recDevice ** ppDevice)
   541 {
   542     kern_return_t result = KERN_SUCCESS;
   543     recDevice *pDeviceNext = NULL;
   544     if (*ppDevice) {
   545         /* save next device prior to disposing of this device */
   546         pDeviceNext = (*ppDevice)->pNext;
   547 
   548         /* free posible io_service_t */
   549         if ((*ppDevice)->ffservice) {
   550             IOObjectRelease((*ppDevice)->ffservice);
   551             (*ppDevice)->ffservice = 0;
   552         }
   553 
   554         /* free element lists */
   555         HIDDisposeElementList(&(*ppDevice)->firstAxis);
   556         HIDDisposeElementList(&(*ppDevice)->firstButton);
   557         HIDDisposeElementList(&(*ppDevice)->firstHat);
   558 
   559         result = HIDCloseReleaseInterface(*ppDevice);   /* function sanity checks interface value (now application does not own device) */
   560         if (kIOReturnSuccess != result)
   561             HIDReportErrorNum
   562                 ("HIDCloseReleaseInterface failed when trying to dipose device.",
   563                  result);
   564         DisposePtr((Ptr) * ppDevice);
   565         *ppDevice = NULL;
   566     }
   567     return pDeviceNext;
   568 }
   569 
   570 
   571 /* Function to scan the system for joysticks.
   572  * Joystick 0 should be the system default joystick.
   573  * This function should return the number of available joysticks, or -1
   574  * on an unrecoverable fatal error.
   575  */
   576 int
   577 SDL_SYS_JoystickInit(void)
   578 {
   579     IOReturn result = kIOReturnSuccess;
   580     mach_port_t masterPort = 0;
   581     io_iterator_t hidObjectIterator = 0;
   582     CFMutableDictionaryRef hidMatchDictionary = NULL;
   583     recDevice *device, *lastDevice;
   584     io_object_t ioHIDDeviceObject = 0;
   585 
   586     SDL_numjoysticks = 0;
   587 
   588     if (gpDeviceList) {
   589         SDL_SetError("Joystick: Device list already inited.");
   590         return -1;
   591     }
   592 
   593     result = IOMasterPort(bootstrap_port, &masterPort);
   594     if (kIOReturnSuccess != result) {
   595         SDL_SetError("Joystick: IOMasterPort error with bootstrap_port.");
   596         return -1;
   597     }
   598 
   599     /* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */
   600     hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
   601     if (hidMatchDictionary) {
   602         /* Add key for device type (joystick, in this case) to refine the matching dictionary. */
   603 
   604         /* NOTE: we now perform this filtering later
   605            UInt32 usagePage = kHIDPage_GenericDesktop;
   606            UInt32 usage = kHIDUsage_GD_Joystick;
   607            CFNumberRef refUsage = NULL, refUsagePage = NULL;
   608 
   609            refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage);
   610            CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage);
   611            refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage);
   612            CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage);
   613          */
   614     } else {
   615         SDL_SetError
   616             ("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching.");
   617         return -1;
   618     }
   619 
   620     /*/ Now search I/O Registry for matching devices. */
   621     result =
   622         IOServiceGetMatchingServices(masterPort, hidMatchDictionary,
   623                                      &hidObjectIterator);
   624     /* Check for errors */
   625     if (kIOReturnSuccess != result) {
   626         SDL_SetError("Joystick: Couldn't create a HID object iterator.");
   627         return -1;
   628     }
   629     if (!hidObjectIterator) {   /* there are no joysticks */
   630         gpDeviceList = NULL;
   631         SDL_numjoysticks = 0;
   632         return 0;
   633     }
   634     /* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */
   635 
   636     /* build flat linked list of devices from device iterator */
   637 
   638     gpDeviceList = lastDevice = NULL;
   639 
   640     while ((ioHIDDeviceObject = IOIteratorNext(hidObjectIterator))) {
   641         /* build a device record */
   642         device = HIDBuildDevice(ioHIDDeviceObject);
   643         if (!device)
   644             continue;
   645 
   646         /* We have to do some storage of the io_service_t for
   647          * SDL_HapticOpenFromJoystick */
   648         if (FFIsForceFeedback(device) == FF_OK) {
   649            device->ffservice = ioHIDDeviceObject;
   650         }
   651         else {
   652            device->ffservice = 0;
   653            /* dump device object, it is no longer needed */
   654            result = IOObjectRelease(ioHIDDeviceObject);
   655         }
   656 /*		if (KERN_SUCCESS != result)
   657 			HIDReportErrorNum ("IOObjectRelease error with ioHIDDeviceObject.", result);
   658 */
   659 
   660         /* Filter device list to non-keyboard/mouse stuff */
   661         if ((device->usagePage != kHIDPage_GenericDesktop) ||
   662             ((device->usage != kHIDUsage_GD_Joystick &&
   663               device->usage != kHIDUsage_GD_GamePad &&
   664               device->usage != kHIDUsage_GD_MultiAxisController))) {
   665 
   666             /* release memory for the device */
   667             HIDDisposeDevice(&device);
   668             DisposePtr((Ptr) device);
   669             continue;
   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: */