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