src/joystick/darwin/SDL_sysjoystick.c
author Sam Lantinga <slouken@libsdl.org>
Mon, 26 Nov 2012 22:27:49 -0800
changeset 6698 28ab2ef7bfc9
parent 6693 3c98e4ec2180
child 6707 70eeb7e3ec2f
permissions -rw-r--r--
Completed adding new hotplug stubs for the joystick implementations
slouken@172
     1
/*
slouken@5535
     2
  Simple DirectMedia Layer
slouken@6138
     3
  Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
slouken@172
     4
slouken@5535
     5
  This software is provided 'as-is', without any express or implied
slouken@5535
     6
  warranty.  In no event will the authors be held liable for any damages
slouken@5535
     7
  arising from the use of this software.
slouken@172
     8
slouken@5535
     9
  Permission is granted to anyone to use this software for any purpose,
slouken@5535
    10
  including commercial applications, and to alter it and redistribute it
slouken@5535
    11
  freely, subject to the following restrictions:
slouken@172
    12
slouken@5535
    13
  1. The origin of this software must not be misrepresented; you must not
slouken@5535
    14
     claim that you wrote the original software. If you use this software
slouken@5535
    15
     in a product, an acknowledgment in the product documentation would be
slouken@5535
    16
     appreciated but is not required.
slouken@5535
    17
  2. Altered source versions must be plainly marked as such, and must not be
slouken@5535
    18
     misrepresented as being the original software.
slouken@5535
    19
  3. This notice may not be removed or altered from any source distribution.
slouken@172
    20
*/
slouken@1402
    21
#include "SDL_config.h"
slouken@172
    22
slouken@1635
    23
#ifdef SDL_JOYSTICK_IOKIT
slouken@1635
    24
slouken@1621
    25
/* SDL joystick driver for Darwin / Mac OS X, based on the IOKit HID API */
slouken@172
    26
/* Written 2001 by Max Horn */
slouken@172
    27
slouken@172
    28
#include <unistd.h>
slouken@172
    29
#include <ctype.h>
slouken@172
    30
#include <sysexits.h>
slouken@172
    31
#include <mach/mach.h>
slouken@172
    32
#include <mach/mach_error.h>
slouken@172
    33
#include <IOKit/IOKitLib.h>
slouken@172
    34
#include <IOKit/IOCFPlugIn.h>
slouken@209
    35
#ifdef MACOS_10_0_4
slouken@209
    36
#include <IOKit/hidsystem/IOHIDUsageTables.h>
slouken@209
    37
#else
slouken@1621
    38
/* The header was moved here in Mac OS X 10.1 */
slouken@208
    39
#include <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
slouken@209
    40
#endif
slouken@172
    41
#include <IOKit/hid/IOHIDLib.h>
slouken@172
    42
#include <IOKit/hid/IOHIDKeys.h>
slouken@172
    43
#include <CoreFoundation/CoreFoundation.h>
slouken@1895
    44
#include <Carbon/Carbon.h>      /* for NewPtrClear, DisposePtr */
slouken@6690
    45
#include <IOKit/IOMessage.h>
slouken@172
    46
slouken@2713
    47
/* For force feedback testing. */
slouken@2713
    48
#include <ForceFeedback/ForceFeedback.h>
slouken@2713
    49
#include <ForceFeedback/ForceFeedbackConstants.h>
slouken@2713
    50
slouken@172
    51
#include "SDL_joystick.h"
slouken@1361
    52
#include "../SDL_sysjoystick.h"
slouken@1361
    53
#include "../SDL_joystick_c.h"
slouken@2713
    54
#include "SDL_sysjoystick_c.h"
slouken@6690
    55
#include "SDL_events.h"
slouken@6690
    56
#if !SDL_EVENTS_DISABLED
slouken@6690
    57
#include "../../events/SDL_events_c.h"
slouken@6690
    58
#endif
slouken@172
    59
slouken@172
    60
slouken@172
    61
/* Linked list of all available devices */
slouken@172
    62
static recDevice *gpDeviceList = NULL;
slouken@6690
    63
/* OSX reference to the notification object that tells us about device insertion/removal */
slouken@6690
    64
IONotificationPortRef notificationPort = 0;
slouken@6690
    65
/* if 1 then a device was added since the last update call */
slouken@6690
    66
Uint8 s_bDeviceAdded = 0;
slouken@172
    67
slouken@6690
    68
/* static incrementing counter for new joystick devices seen on the system. Devices should start with index 0 */
slouken@6690
    69
static int s_joystick_instance_id = -1;
slouken@172
    70
slouken@1895
    71
static void
slouken@1895
    72
HIDReportErrorNum(char *strError, long numError)
slouken@172
    73
{
slouken@1895
    74
    SDL_SetError(strError);
slouken@172
    75
}
slouken@172
    76
slouken@1895
    77
static void HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
slouken@1895
    78
                                     recDevice * pDevice);
slouken@172
    79
slouken@172
    80
/* returns current value for element, polling element
slouken@172
    81
 * will return 0 on error conditions which should be accounted for by application
slouken@172
    82
 */
slouken@172
    83
slouken@1895
    84
static SInt32
slouken@1895
    85
HIDGetElementValue(recDevice * pDevice, recElement * pElement)
slouken@172
    86
{
slouken@1895
    87
    IOReturn result = kIOReturnSuccess;
slouken@1895
    88
    IOHIDEventStruct hidEvent;
slouken@1895
    89
    hidEvent.value = 0;
slouken@172
    90
slouken@1895
    91
    if (NULL != pDevice && NULL != pElement && NULL != pDevice->interface) {
slouken@1895
    92
        result =
slouken@1895
    93
            (*(pDevice->interface))->getElementValue(pDevice->interface,
slouken@1895
    94
                                                     pElement->cookie,
slouken@1895
    95
                                                     &hidEvent);
slouken@1895
    96
        if (kIOReturnSuccess == result) {
slouken@1895
    97
            /* record min and max for auto calibration */
slouken@1895
    98
            if (hidEvent.value < pElement->minReport)
slouken@1895
    99
                pElement->minReport = hidEvent.value;
slouken@1895
   100
            if (hidEvent.value > pElement->maxReport)
slouken@1895
   101
                pElement->maxReport = hidEvent.value;
slouken@1895
   102
        }
slouken@1895
   103
    }
slouken@1895
   104
slouken@1895
   105
    /* auto user scale */
slouken@1895
   106
    return hidEvent.value;
slouken@172
   107
}
slouken@172
   108
slouken@1895
   109
static SInt32
slouken@1895
   110
HIDScaledCalibratedValue(recDevice * pDevice, recElement * pElement,
slouken@1895
   111
                         long min, long max)
slouken@172
   112
{
slouken@1895
   113
    float deviceScale = max - min;
slouken@1895
   114
    float readScale = pElement->maxReport - pElement->minReport;
slouken@1895
   115
    SInt32 value = HIDGetElementValue(pDevice, pElement);
slouken@1895
   116
    if (readScale == 0)
slouken@1895
   117
        return value;           /* no scaling at all */
slouken@1895
   118
    else
slouken@1895
   119
        return ((value - pElement->minReport) * deviceScale / readScale) +
slouken@1895
   120
            min;
slouken@172
   121
}
slouken@172
   122
slouken@858
   123
slouken@1895
   124
static void
slouken@1895
   125
HIDRemovalCallback(void *target, IOReturn result, void *refcon, void *sender)
slouken@858
   126
{
slouken@1895
   127
    recDevice *device = (recDevice *) refcon;
slouken@1895
   128
    device->removed = 1;
slouken@858
   129
}
slouken@858
   130
slouken@858
   131
slouken@6690
   132
/* Called by the io port notifier on removal of this device
slouken@6690
   133
 */
slouken@6690
   134
void JoystickDeviceWasRemovedCallback( void * refcon, io_service_t service, natural_t messageType, void * messageArgument )
slouken@6690
   135
{
slouken@6690
   136
    if( messageType == kIOMessageServiceIsTerminated && refcon )
slouken@6690
   137
    {
slouken@6690
   138
		recDevice *device = (recDevice *) refcon;
slouken@6690
   139
		device->removed = 1;
slouken@6690
   140
	}
slouken@6690
   141
}
slouken@6690
   142
slouken@858
   143
slouken@172
   144
/* Create and open an interface to device, required prior to extracting values or building queues.
slouken@172
   145
 * Note: appliction now owns the device and must close and release it prior to exiting
slouken@172
   146
 */
slouken@172
   147
slouken@1895
   148
static IOReturn
slouken@1895
   149
HIDCreateOpenDeviceInterface(io_object_t hidDevice, recDevice * pDevice)
slouken@172
   150
{
slouken@1895
   151
    IOReturn result = kIOReturnSuccess;
slouken@1895
   152
    HRESULT plugInResult = S_OK;
slouken@1895
   153
    SInt32 score = 0;
slouken@1895
   154
    IOCFPlugInInterface **ppPlugInInterface = NULL;
slouken@858
   155
slouken@1895
   156
    if (NULL == pDevice->interface) {
slouken@1895
   157
        result =
slouken@1895
   158
            IOCreatePlugInInterfaceForService(hidDevice,
slouken@1895
   159
                                              kIOHIDDeviceUserClientTypeID,
slouken@1895
   160
                                              kIOCFPlugInInterfaceID,
slouken@1895
   161
                                              &ppPlugInInterface, &score);
slouken@1895
   162
        if (kIOReturnSuccess == result) {
slouken@1895
   163
            /* Call a method of the intermediate plug-in to create the device interface */
slouken@1895
   164
            plugInResult =
slouken@1895
   165
                (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
slouken@1895
   166
                                                     CFUUIDGetUUIDBytes
slouken@1895
   167
                                                     (kIOHIDDeviceInterfaceID),
slouken@2735
   168
                                                     (void *)
slouken@2735
   169
                                                     &(pDevice->interface));
slouken@1895
   170
            if (S_OK != plugInResult)
slouken@1895
   171
                HIDReportErrorNum
slouken@1895
   172
                    ("CouldnŐt query HID class device interface from plugInInterface",
slouken@1895
   173
                     plugInResult);
slouken@1895
   174
            (*ppPlugInInterface)->Release(ppPlugInInterface);
slouken@1895
   175
        } else
slouken@1895
   176
            HIDReportErrorNum
slouken@1895
   177
                ("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.",
slouken@1895
   178
                 result);
slouken@1895
   179
    }
slouken@1895
   180
    if (NULL != pDevice->interface) {
slouken@1895
   181
        result = (*(pDevice->interface))->open(pDevice->interface, 0);
slouken@1895
   182
        if (kIOReturnSuccess != result)
slouken@1895
   183
            HIDReportErrorNum
slouken@1895
   184
                ("Failed to open pDevice->interface via open.", result);
slouken@1895
   185
        else
slouken@6690
   186
		{
slouken@6690
   187
			pDevice->portIterator = 0;
slouken@6690
   188
slouken@6690
   189
			// It's okay if this fails, we have another detection method below
slouken@1895
   190
            (*(pDevice->interface))->setRemovalCallback(pDevice->interface,
slouken@1895
   191
                                                        HIDRemovalCallback,
slouken@1895
   192
                                                        pDevice, pDevice);
slouken@6690
   193
			
slouken@6690
   194
			/* now connect notification for new devices */
slouken@6690
   195
			pDevice->notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
slouken@6690
   196
			
slouken@6690
   197
			CFRunLoopAddSource(CFRunLoopGetCurrent(), 
slouken@6690
   198
							   IONotificationPortGetRunLoopSource(pDevice->notificationPort), 
slouken@6690
   199
							   kCFRunLoopDefaultMode);
slouken@6690
   200
			
slouken@6690
   201
			// Register for notifications when a serial port is added to the system
slouken@6690
   202
			result = IOServiceAddInterestNotification(pDevice->notificationPort,
slouken@6690
   203
													  hidDevice,
slouken@6690
   204
													  kIOGeneralInterest,
slouken@6690
   205
													  JoystickDeviceWasRemovedCallback,
slouken@6690
   206
													  pDevice,           
slouken@6690
   207
													  &pDevice->portIterator);
slouken@6690
   208
        	if (kIOReturnSuccess != result) {
slouken@6690
   209
            	HIDReportErrorNum
slouken@6690
   210
                	("Failed to register for removal callback.", result);		
slouken@6690
   211
			}	
slouken@6690
   212
		}
slouken@1895
   213
slouken@1895
   214
    }
slouken@1895
   215
    return result;
slouken@172
   216
}
slouken@172
   217
slouken@172
   218
/* Closes and releases interface to device, should be done prior to exting application
slouken@172
   219
 * Note: will have no affect if device or interface do not exist
slouken@172
   220
 * application will "own" the device if interface is not closed
slouken@172
   221
 * (device may have to be plug and re-plugged in different location to get it working again without a restart)
slouken@172
   222
 */
slouken@172
   223
slouken@1895
   224
static IOReturn
slouken@1895
   225
HIDCloseReleaseInterface(recDevice * pDevice)
slouken@172
   226
{
slouken@1895
   227
    IOReturn result = kIOReturnSuccess;
slouken@1895
   228
slouken@1895
   229
    if ((NULL != pDevice) && (NULL != pDevice->interface)) {
slouken@1895
   230
        /* close the interface */
slouken@1895
   231
        result = (*(pDevice->interface))->close(pDevice->interface);
slouken@1895
   232
        if (kIOReturnNotOpen == result) {
slouken@1895
   233
            /* do nothing as device was not opened, thus can't be closed */
slouken@1895
   234
        } else if (kIOReturnSuccess != result)
slouken@1895
   235
            HIDReportErrorNum("Failed to close IOHIDDeviceInterface.",
slouken@1895
   236
                              result);
slouken@1895
   237
        /* release the interface */
slouken@1895
   238
        result = (*(pDevice->interface))->Release(pDevice->interface);
slouken@1895
   239
        if (kIOReturnSuccess != result)
slouken@1895
   240
            HIDReportErrorNum("Failed to release IOHIDDeviceInterface.",
slouken@1895
   241
                              result);
slouken@1895
   242
        pDevice->interface = NULL;
slouken@6690
   243
		
slouken@6690
   244
		if ( pDevice->portIterator )
slouken@6690
   245
		{
slouken@6690
   246
			IOObjectRelease( pDevice->portIterator );
slouken@6690
   247
			pDevice->portIterator = 0;
slouken@6690
   248
		}
slouken@1895
   249
    }
slouken@1895
   250
    return result;
slouken@172
   251
}
slouken@172
   252
slouken@172
   253
/* extracts actual specific element information from each element CF dictionary entry */
slouken@172
   254
slouken@1895
   255
static void
slouken@1895
   256
HIDGetElementInfo(CFTypeRef refElement, recElement * pElement)
slouken@172
   257
{
slouken@1895
   258
    long number;
slouken@1895
   259
    CFTypeRef refType;
slouken@172
   260
slouken@1895
   261
    refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementCookieKey));
slouken@1895
   262
    if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
slouken@1895
   263
        pElement->cookie = (IOHIDElementCookie) number;
slouken@1895
   264
    refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMinKey));
slouken@1895
   265
    if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
icculus@2109
   266
        pElement->minReport = pElement->min = number;
slouken@1895
   267
    pElement->maxReport = pElement->min;
slouken@1895
   268
    refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMaxKey));
slouken@1895
   269
    if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
icculus@2109
   270
        pElement->maxReport = pElement->max = number;
slouken@172
   271
/*
slouken@172
   272
	TODO: maybe should handle the following stuff somehow?
slouken@172
   273
slouken@172
   274
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
slouken@172
   275
	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
slouken@172
   276
		pElement->scaledMin = number;
slouken@172
   277
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
slouken@172
   278
	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
slouken@172
   279
		pElement->scaledMax = number;
slouken@172
   280
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
slouken@172
   281
	if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
slouken@172
   282
		pElement->size = number;
slouken@172
   283
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
slouken@172
   284
	if (refType)
slouken@172
   285
		pElement->relative = CFBooleanGetValue (refType);
slouken@172
   286
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
slouken@172
   287
	if (refType)
slouken@172
   288
		pElement->wrapping = CFBooleanGetValue (refType);
slouken@172
   289
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
slouken@172
   290
	if (refType)
slouken@172
   291
		pElement->nonLinear = CFBooleanGetValue (refType);
slouken@172
   292
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
slouken@172
   293
	if (refType)
slouken@172
   294
		pElement->preferredState = CFBooleanGetValue (refType);
slouken@172
   295
	refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
slouken@172
   296
	if (refType)
slouken@172
   297
		pElement->nullState = CFBooleanGetValue (refType);
slouken@172
   298
*/
slouken@1895
   299
}
slouken@172
   300
slouken@172
   301
/* examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements
slouken@172
   302
 * if element of interest allocate storage, add to list and retrieve element specific info
slouken@172
   303
 * if collection then pass on to deconstruction collection into additional individual elements
slouken@172
   304
 */
slouken@172
   305
slouken@1895
   306
static void
slouken@1895
   307
HIDAddElement(CFTypeRef refElement, recDevice * pDevice)
slouken@172
   308
{
slouken@1895
   309
    recElement *element = NULL;
slouken@1895
   310
    recElement **headElement = NULL;
slouken@1895
   311
    long elementType, usagePage, usage;
slouken@1895
   312
    CFTypeRef refElementType =
slouken@1895
   313
        CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementTypeKey));
slouken@1895
   314
    CFTypeRef refUsagePage =
slouken@1895
   315
        CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsagePageKey));
slouken@1895
   316
    CFTypeRef refUsage =
slouken@1895
   317
        CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsageKey));
slouken@172
   318
slouken@172
   319
slouken@1895
   320
    if ((refElementType)
slouken@1895
   321
        &&
slouken@1895
   322
        (CFNumberGetValue(refElementType, kCFNumberLongType, &elementType))) {
slouken@1895
   323
        /* look at types of interest */
slouken@1895
   324
        if ((elementType == kIOHIDElementTypeInput_Misc)
slouken@1895
   325
            || (elementType == kIOHIDElementTypeInput_Button)
slouken@1895
   326
            || (elementType == kIOHIDElementTypeInput_Axis)) {
slouken@1895
   327
            if (refUsagePage
slouken@1895
   328
                && CFNumberGetValue(refUsagePage, kCFNumberLongType,
slouken@1895
   329
                                    &usagePage) && refUsage
slouken@1895
   330
                && CFNumberGetValue(refUsage, kCFNumberLongType, &usage)) {
slouken@1895
   331
                switch (usagePage) {    /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */
slouken@1895
   332
                case kHIDPage_GenericDesktop:
slouken@1895
   333
                    {
slouken@1895
   334
                        switch (usage) {        /* look at usage to determine function */
slouken@1895
   335
                        case kHIDUsage_GD_X:
slouken@1895
   336
                        case kHIDUsage_GD_Y:
slouken@1895
   337
                        case kHIDUsage_GD_Z:
slouken@1895
   338
                        case kHIDUsage_GD_Rx:
slouken@1895
   339
                        case kHIDUsage_GD_Ry:
slouken@1895
   340
                        case kHIDUsage_GD_Rz:
slouken@1895
   341
                        case kHIDUsage_GD_Slider:
slouken@1895
   342
                        case kHIDUsage_GD_Dial:
slouken@1895
   343
                        case kHIDUsage_GD_Wheel:
slouken@1895
   344
                            element = (recElement *)
slouken@1895
   345
                                NewPtrClear(sizeof(recElement));
slouken@1895
   346
                            if (element) {
slouken@1895
   347
                                pDevice->axes++;
slouken@1895
   348
                                headElement = &(pDevice->firstAxis);
slouken@1895
   349
                            }
slouken@1895
   350
                            break;
slouken@1895
   351
                        case kHIDUsage_GD_Hatswitch:
slouken@1895
   352
                            element = (recElement *)
slouken@1895
   353
                                NewPtrClear(sizeof(recElement));
slouken@1895
   354
                            if (element) {
slouken@1895
   355
                                pDevice->hats++;
slouken@1895
   356
                                headElement = &(pDevice->firstHat);
slouken@1895
   357
                            }
slouken@1895
   358
                            break;
slouken@1895
   359
                        }
slouken@1895
   360
                    }
slouken@1895
   361
                    break;
slouken@1895
   362
                case kHIDPage_Button:
slouken@1895
   363
                    element = (recElement *)
slouken@1895
   364
                        NewPtrClear(sizeof(recElement));
slouken@1895
   365
                    if (element) {
slouken@1895
   366
                        pDevice->buttons++;
slouken@1895
   367
                        headElement = &(pDevice->firstButton);
slouken@1895
   368
                    }
slouken@1895
   369
                    break;
slouken@1895
   370
                default:
slouken@1895
   371
                    break;
slouken@1895
   372
                }
slouken@1895
   373
            }
slouken@1895
   374
        } else if (kIOHIDElementTypeCollection == elementType)
slouken@1895
   375
            HIDGetCollectionElements((CFMutableDictionaryRef) refElement,
slouken@1895
   376
                                     pDevice);
slouken@1895
   377
    }
slouken@172
   378
slouken@1895
   379
    if (element && headElement) {       /* add to list */
slouken@2776
   380
        recElement *elementPrevious = NULL;
slouken@2776
   381
        recElement *elementCurrent = *headElement;
slouken@2776
   382
        while (elementCurrent && usage >= elementCurrent->usage) {
slouken@2776
   383
            elementPrevious = elementCurrent;
slouken@2776
   384
            elementCurrent = elementCurrent->pNext;
slouken@2776
   385
        }
slouken@2776
   386
        if (elementPrevious) {
slouken@2776
   387
            elementPrevious->pNext = element;
slouken@2776
   388
        } else {
slouken@2776
   389
            *headElement = element;
slouken@2776
   390
        }
slouken@2776
   391
        element->usagePage = usagePage;
slouken@2776
   392
        element->usage = usage;
slouken@2776
   393
        element->pNext = elementCurrent;
slouken@2776
   394
        HIDGetElementInfo(refElement, element);
slouken@1895
   395
        pDevice->elements++;
slouken@1895
   396
    }
slouken@172
   397
}
slouken@172
   398
slouken@172
   399
/* collects information from each array member in device element list (each array memeber = element) */
slouken@172
   400
slouken@1895
   401
static void
slouken@1895
   402
HIDGetElementsCFArrayHandler(const void *value, void *parameter)
slouken@172
   403
{
slouken@1895
   404
    if (CFGetTypeID(value) == CFDictionaryGetTypeID())
slouken@1895
   405
        HIDAddElement((CFTypeRef) value, (recDevice *) parameter);
slouken@172
   406
}
slouken@172
   407
slouken@172
   408
/* handles retrieval of element information from arrays of elements in device IO registry information */
slouken@172
   409
slouken@1895
   410
static void
slouken@1895
   411
HIDGetElements(CFTypeRef refElementCurrent, recDevice * pDevice)
slouken@172
   412
{
slouken@1895
   413
    CFTypeID type = CFGetTypeID(refElementCurrent);
slouken@1895
   414
    if (type == CFArrayGetTypeID()) {   /* if element is an array */
slouken@1895
   415
        CFRange range = { 0, CFArrayGetCount(refElementCurrent) };
slouken@1895
   416
        /* CountElementsCFArrayHandler called for each array member */
slouken@1895
   417
        CFArrayApplyFunction(refElementCurrent, range,
slouken@1895
   418
                             HIDGetElementsCFArrayHandler, pDevice);
slouken@1895
   419
    }
slouken@1895
   420
}
slouken@172
   421
slouken@172
   422
/* handles extracting element information from element collection CF types
slouken@172
   423
 * used from top level element decoding and hierarchy deconstruction to flatten device element list
slouken@172
   424
 */
slouken@172
   425
slouken@1895
   426
static void
slouken@1895
   427
HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
slouken@1895
   428
                         recDevice * pDevice)
slouken@172
   429
{
slouken@1895
   430
    CFTypeRef refElementTop =
slouken@1895
   431
        CFDictionaryGetValue(deviceProperties, CFSTR(kIOHIDElementKey));
slouken@1895
   432
    if (refElementTop)
slouken@1895
   433
        HIDGetElements(refElementTop, pDevice);
slouken@172
   434
}
slouken@172
   435
slouken@172
   436
/* use top level element usage page and usage to discern device usage page and usage setting appropriate vlaues in device record */
slouken@172
   437
slouken@1895
   438
static void
slouken@1895
   439
HIDTopLevelElementHandler(const void *value, void *parameter)
slouken@172
   440
{
slouken@1895
   441
    CFTypeRef refCF = 0;
slouken@1895
   442
    if (CFGetTypeID(value) != CFDictionaryGetTypeID())
slouken@1895
   443
        return;
slouken@1895
   444
    refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsagePageKey));
slouken@1895
   445
    if (!CFNumberGetValue
slouken@1895
   446
        (refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage))
slouken@1895
   447
        SDL_SetError("CFNumberGetValue error retrieving pDevice->usagePage.");
slouken@1895
   448
    refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsageKey));
slouken@1895
   449
    if (!CFNumberGetValue
slouken@1895
   450
        (refCF, kCFNumberLongType, &((recDevice *) parameter)->usage))
slouken@1895
   451
        SDL_SetError("CFNumberGetValue error retrieving pDevice->usage.");
slouken@172
   452
}
slouken@172
   453
slouken@172
   454
/* extracts device info from CF dictionary records in IO registry */
slouken@172
   455
slouken@1895
   456
static void
slouken@1895
   457
HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties,
slouken@1895
   458
                 recDevice * pDevice)
slouken@172
   459
{
slouken@1895
   460
    CFMutableDictionaryRef usbProperties = 0;
slouken@1895
   461
    io_registry_entry_t parent1, parent2;
slouken@172
   462
slouken@1895
   463
    /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
slouken@1895
   464
     * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
slouken@1895
   465
     */
slouken@1895
   466
    if ((KERN_SUCCESS ==
slouken@1895
   467
         IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1))
slouken@1895
   468
        && (KERN_SUCCESS ==
slouken@1895
   469
            IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))
slouken@1895
   470
        && (KERN_SUCCESS ==
slouken@1895
   471
            IORegistryEntryCreateCFProperties(parent2, &usbProperties,
slouken@1895
   472
                                              kCFAllocatorDefault,
slouken@1895
   473
                                              kNilOptions))) {
slouken@1895
   474
        if (usbProperties) {
slouken@1895
   475
            CFTypeRef refCF = 0;
slouken@1895
   476
            /* get device info
slouken@1895
   477
             * try hid dictionary first, if fail then go to usb dictionary
slouken@1895
   478
             */
slouken@172
   479
slouken@172
   480
slouken@1895
   481
            /* get product name */
slouken@1895
   482
            refCF =
slouken@1895
   483
                CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey));
slouken@1895
   484
            if (!refCF)
slouken@1895
   485
                refCF =
slouken@1895
   486
                    CFDictionaryGetValue(usbProperties,
slouken@1895
   487
                                         CFSTR("USB Product Name"));
slouken@1895
   488
            if (refCF) {
slouken@1895
   489
                if (!CFStringGetCString
slouken@1895
   490
                    (refCF, pDevice->product, 256,
slouken@1895
   491
                     CFStringGetSystemEncoding()))
slouken@1895
   492
                    SDL_SetError
slouken@1895
   493
                        ("CFStringGetCString error retrieving pDevice->product.");
slouken@1895
   494
            }
slouken@1895
   495
slouken@1895
   496
            /* get usage page and usage */
slouken@1895
   497
            refCF =
slouken@1895
   498
                CFDictionaryGetValue(hidProperties,
slouken@1895
   499
                                     CFSTR(kIOHIDPrimaryUsagePageKey));
slouken@1895
   500
            if (refCF) {
slouken@1895
   501
                if (!CFNumberGetValue
slouken@1895
   502
                    (refCF, kCFNumberLongType, &pDevice->usagePage))
slouken@1895
   503
                    SDL_SetError
slouken@1895
   504
                        ("CFNumberGetValue error retrieving pDevice->usagePage.");
slouken@1895
   505
                refCF =
slouken@1895
   506
                    CFDictionaryGetValue(hidProperties,
slouken@1895
   507
                                         CFSTR(kIOHIDPrimaryUsageKey));
slouken@1895
   508
                if (refCF)
slouken@1895
   509
                    if (!CFNumberGetValue
slouken@1895
   510
                        (refCF, kCFNumberLongType, &pDevice->usage))
slouken@1895
   511
                        SDL_SetError
slouken@1895
   512
                            ("CFNumberGetValue error retrieving pDevice->usage.");
slouken@1895
   513
            }
slouken@1895
   514
slouken@6690
   515
			refCF =
slouken@6690
   516
			CFDictionaryGetValue(hidProperties,
slouken@6690
   517
								 CFSTR(kIOHIDVendorIDKey));
slouken@6690
   518
            if (refCF) {
slouken@6690
   519
                if (!CFNumberGetValue
slouken@6690
   520
                    (refCF, kCFNumberLongType, &pDevice->guid.data[0]))
slouken@6690
   521
                    SDL_SetError
slouken@6690
   522
					("CFNumberGetValue error retrieving pDevice->guid.");
slouken@6690
   523
            }
slouken@6690
   524
			refCF =
slouken@6690
   525
			CFDictionaryGetValue(hidProperties,
slouken@6690
   526
								 CFSTR(kIOHIDProductIDKey));
slouken@6690
   527
            if (refCF) {
slouken@6690
   528
                if (!CFNumberGetValue
slouken@6690
   529
                    (refCF, kCFNumberLongType, &pDevice->guid.data[8]))
slouken@6690
   530
                    SDL_SetError
slouken@6690
   531
					("CFNumberGetValue error retrieving pDevice->guid[8].");
slouken@6690
   532
            }
slouken@6690
   533
slouken@6690
   534
			
slouken@1895
   535
            if (NULL == refCF) {        /* get top level element HID usage page or usage */
slouken@1895
   536
                /* use top level element instead */
slouken@1895
   537
                CFTypeRef refCFTopElement = 0;
slouken@1895
   538
                refCFTopElement =
slouken@1895
   539
                    CFDictionaryGetValue(hidProperties,
slouken@1895
   540
                                         CFSTR(kIOHIDElementKey));
slouken@1895
   541
                {
slouken@1895
   542
                    /* refCFTopElement points to an array of element dictionaries */
slouken@1895
   543
                    CFRange range = { 0, CFArrayGetCount(refCFTopElement) };
slouken@1895
   544
                    CFArrayApplyFunction(refCFTopElement, range,
slouken@1895
   545
                                         HIDTopLevelElementHandler, pDevice);
slouken@1895
   546
                }
slouken@1895
   547
            }
slouken@1895
   548
slouken@1895
   549
            CFRelease(usbProperties);
slouken@1895
   550
        } else
slouken@1895
   551
            SDL_SetError
slouken@1895
   552
                ("IORegistryEntryCreateCFProperties failed to create usbProperties.");
slouken@1895
   553
slouken@1895
   554
        if (kIOReturnSuccess != IOObjectRelease(parent2))
slouken@1895
   555
            SDL_SetError("IOObjectRelease error with parent2.");
slouken@1895
   556
        if (kIOReturnSuccess != IOObjectRelease(parent1))
slouken@1895
   557
            SDL_SetError("IOObjectRelease error with parent1.");
slouken@1895
   558
    }
slouken@172
   559
}
slouken@172
   560
slouken@172
   561
slouken@1895
   562
static recDevice *
slouken@1895
   563
HIDBuildDevice(io_object_t hidDevice)
slouken@172
   564
{
slouken@1895
   565
    recDevice *pDevice = (recDevice *) NewPtrClear(sizeof(recDevice));
slouken@1895
   566
    if (pDevice) {
slouken@1895
   567
        /* get dictionary for HID properties */
slouken@1895
   568
        CFMutableDictionaryRef hidProperties = 0;
slouken@1895
   569
        kern_return_t result =
slouken@1895
   570
            IORegistryEntryCreateCFProperties(hidDevice, &hidProperties,
slouken@1895
   571
                                              kCFAllocatorDefault,
slouken@1895
   572
                                              kNilOptions);
slouken@1895
   573
        if ((result == KERN_SUCCESS) && hidProperties) {
slouken@1895
   574
            /* create device interface */
slouken@1895
   575
            result = HIDCreateOpenDeviceInterface(hidDevice, pDevice);
slouken@1895
   576
            if (kIOReturnSuccess == result) {
slouken@1895
   577
                HIDGetDeviceInfo(hidDevice, hidProperties, pDevice);    /* hidDevice used to find parents in registry tree */
slouken@1895
   578
                HIDGetCollectionElements(hidProperties, pDevice);
slouken@6690
   579
				pDevice->instance_id = ++s_joystick_instance_id;
slouken@1895
   580
            } else {
slouken@1895
   581
                DisposePtr((Ptr) pDevice);
slouken@1895
   582
                pDevice = NULL;
slouken@1895
   583
            }
slouken@1895
   584
            CFRelease(hidProperties);
slouken@1895
   585
        } else {
slouken@1895
   586
            DisposePtr((Ptr) pDevice);
slouken@1895
   587
            pDevice = NULL;
slouken@1895
   588
        }
slouken@1895
   589
    }
slouken@1895
   590
    return pDevice;
slouken@172
   591
}
slouken@172
   592
slouken@172
   593
/* disposes of the element list associated with a device and the memory associated with the list
slouken@172
   594
 */
slouken@172
   595
slouken@1895
   596
static void
slouken@1895
   597
HIDDisposeElementList(recElement ** elementList)
slouken@172
   598
{
slouken@1895
   599
    recElement *pElement = *elementList;
slouken@1895
   600
    while (pElement) {
slouken@1895
   601
        recElement *pElementNext = pElement->pNext;
slouken@1895
   602
        DisposePtr((Ptr) pElement);
slouken@1895
   603
        pElement = pElementNext;
slouken@1895
   604
    }
slouken@1895
   605
    *elementList = NULL;
slouken@172
   606
}
slouken@172
   607
slouken@172
   608
/* disposes of a single device, closing and releaseing interface, freeing memory fro device and elements, setting device pointer to NULL
slouken@172
   609
 * all your device no longer belong to us... (i.e., you do not 'own' the device anymore)
slouken@172
   610
 */
slouken@172
   611
slouken@1895
   612
static recDevice *
slouken@1895
   613
HIDDisposeDevice(recDevice ** ppDevice)
slouken@172
   614
{
slouken@1895
   615
    kern_return_t result = KERN_SUCCESS;
slouken@1895
   616
    recDevice *pDeviceNext = NULL;
slouken@1895
   617
    if (*ppDevice) {
slouken@1895
   618
        /* save next device prior to disposing of this device */
slouken@1895
   619
        pDeviceNext = (*ppDevice)->pNext;
slouken@1895
   620
slouken@2713
   621
        /* free posible io_service_t */
slouken@2713
   622
        if ((*ppDevice)->ffservice) {
slouken@2713
   623
            IOObjectRelease((*ppDevice)->ffservice);
slouken@2713
   624
            (*ppDevice)->ffservice = 0;
slouken@2713
   625
        }
slouken@2713
   626
slouken@1895
   627
        /* free element lists */
slouken@1895
   628
        HIDDisposeElementList(&(*ppDevice)->firstAxis);
slouken@1895
   629
        HIDDisposeElementList(&(*ppDevice)->firstButton);
slouken@1895
   630
        HIDDisposeElementList(&(*ppDevice)->firstHat);
slouken@1895
   631
slouken@1895
   632
        result = HIDCloseReleaseInterface(*ppDevice);   /* function sanity checks interface value (now application does not own device) */
slouken@1895
   633
        if (kIOReturnSuccess != result)
slouken@1895
   634
            HIDReportErrorNum
slouken@1895
   635
                ("HIDCloseReleaseInterface failed when trying to dipose device.",
slouken@1895
   636
                 result);
slouken@1895
   637
        DisposePtr((Ptr) * ppDevice);
slouken@1895
   638
        *ppDevice = NULL;
slouken@1895
   639
    }
slouken@1895
   640
    return pDeviceNext;
slouken@172
   641
}
slouken@172
   642
slouken@172
   643
slouken@6690
   644
/* Given an io_object_t from OSX adds a joystick device to our list if appropriate
slouken@6690
   645
 */
slouken@6690
   646
int 
slouken@6690
   647
AddDeviceHelper( io_object_t ioHIDDeviceObject )
slouken@6690
   648
{
slouken@6690
   649
    recDevice *device;
slouken@6690
   650
	
slouken@6690
   651
	/* build a device record */
slouken@6690
   652
	device = HIDBuildDevice(ioHIDDeviceObject);
slouken@6690
   653
	if (!device)
slouken@6690
   654
		return 0;
slouken@6690
   655
	
slouken@6690
   656
	/* Filter device list to non-keyboard/mouse stuff */
slouken@6690
   657
	if ((device->usagePage != kHIDPage_GenericDesktop) ||
slouken@6690
   658
		((device->usage != kHIDUsage_GD_Joystick &&
slouken@6690
   659
		  device->usage != kHIDUsage_GD_GamePad &&
slouken@6690
   660
		  device->usage != kHIDUsage_GD_MultiAxisController))) {
slouken@6690
   661
		
slouken@6690
   662
		/* release memory for the device */
slouken@6690
   663
		HIDDisposeDevice(&device);
slouken@6690
   664
		DisposePtr((Ptr) device);
slouken@6690
   665
		return 0;
slouken@6690
   666
	}
slouken@6690
   667
	
slouken@6690
   668
	/* We have to do some storage of the io_service_t for
slouken@6690
   669
	 * SDL_HapticOpenFromJoystick */
slouken@6690
   670
	if (FFIsForceFeedback(ioHIDDeviceObject) == FF_OK) {
slouken@6690
   671
		device->ffservice = ioHIDDeviceObject;
slouken@6690
   672
	} else {
slouken@6690
   673
		device->ffservice = 0;
slouken@6690
   674
	}
slouken@6690
   675
	
slouken@6690
   676
	device->send_open_event = 1;
slouken@6690
   677
	s_bDeviceAdded = 1;
slouken@6690
   678
	
slouken@6690
   679
	/* Add device to the end of the list */
slouken@6690
   680
	if ( !gpDeviceList )
slouken@6690
   681
	{
slouken@6690
   682
		gpDeviceList = device;
slouken@6690
   683
	}
slouken@6690
   684
	else
slouken@6690
   685
	{
slouken@6690
   686
		recDevice *curdevice;
slouken@6690
   687
		
slouken@6690
   688
		curdevice = gpDeviceList;
slouken@6690
   689
		while ( curdevice->pNext )
slouken@6690
   690
		{
slouken@6690
   691
			curdevice = curdevice->pNext;
slouken@6690
   692
		}
slouken@6690
   693
		curdevice->pNext = device;
slouken@6690
   694
	}
slouken@6690
   695
	
slouken@6690
   696
	return 1;
slouken@6690
   697
}
slouken@6690
   698
slouken@6690
   699
slouken@6690
   700
/* Called by our IO port notifier on the master port when a HID device is inserted, we iterate
slouken@6690
   701
 *  and check for new joysticks
slouken@6690
   702
 */
slouken@6690
   703
void JoystickDeviceWasAddedCallback( void *refcon, io_iterator_t iterator )
slouken@6690
   704
{
slouken@6690
   705
    io_object_t ioHIDDeviceObject = 0;
slouken@6690
   706
	
slouken@6690
   707
	while ( ( ioHIDDeviceObject = IOIteratorNext(iterator) ) )
slouken@6690
   708
	{
slouken@6690
   709
		if ( ioHIDDeviceObject )
slouken@6690
   710
		{
slouken@6690
   711
			AddDeviceHelper( ioHIDDeviceObject );			
slouken@6690
   712
		}
slouken@6690
   713
	}
slouken@6690
   714
}
slouken@6690
   715
				
slouken@6690
   716
slouken@172
   717
/* Function to scan the system for joysticks.
slouken@172
   718
 * Joystick 0 should be the system default joystick.
slouken@172
   719
 * This function should return the number of available joysticks, or -1
slouken@172
   720
 * on an unrecoverable fatal error.
slouken@172
   721
 */
slouken@1895
   722
int
slouken@1895
   723
SDL_SYS_JoystickInit(void)
slouken@172
   724
{
slouken@1895
   725
    IOReturn result = kIOReturnSuccess;
slouken@1895
   726
    mach_port_t masterPort = 0;
slouken@1895
   727
    io_iterator_t hidObjectIterator = 0;
slouken@1895
   728
    CFMutableDictionaryRef hidMatchDictionary = NULL;
slouken@1895
   729
    io_object_t ioHIDDeviceObject = 0;
slouken@6690
   730
	io_iterator_t portIterator = 0;
slouken@172
   731
slouken@1895
   732
    if (gpDeviceList) {
slouken@1895
   733
        SDL_SetError("Joystick: Device list already inited.");
slouken@1895
   734
        return -1;
slouken@1895
   735
    }
slouken@172
   736
slouken@1895
   737
    result = IOMasterPort(bootstrap_port, &masterPort);
slouken@1895
   738
    if (kIOReturnSuccess != result) {
slouken@1895
   739
        SDL_SetError("Joystick: IOMasterPort error with bootstrap_port.");
slouken@1895
   740
        return -1;
slouken@1895
   741
    }
slouken@172
   742
slouken@1895
   743
    /* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */
slouken@1895
   744
    hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
slouken@1895
   745
    if (hidMatchDictionary) {
slouken@1895
   746
        /* Add key for device type (joystick, in this case) to refine the matching dictionary. */
slouken@172
   747
slouken@1895
   748
        /* NOTE: we now perform this filtering later
slouken@1895
   749
           UInt32 usagePage = kHIDPage_GenericDesktop;
slouken@1895
   750
           UInt32 usage = kHIDUsage_GD_Joystick;
slouken@1895
   751
           CFNumberRef refUsage = NULL, refUsagePage = NULL;
slouken@1895
   752
slouken@1895
   753
           refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage);
slouken@1895
   754
           CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage);
slouken@1895
   755
           refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage);
slouken@1895
   756
           CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage);
slouken@1895
   757
         */
slouken@1895
   758
    } else {
slouken@1895
   759
        SDL_SetError
slouken@1895
   760
            ("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching.");
slouken@1895
   761
        return -1;
slouken@1895
   762
    }
slouken@1895
   763
slouken@1895
   764
    /*/ Now search I/O Registry for matching devices. */
slouken@1895
   765
    result =
slouken@1895
   766
        IOServiceGetMatchingServices(masterPort, hidMatchDictionary,
slouken@1895
   767
                                     &hidObjectIterator);
slouken@1895
   768
    /* Check for errors */
slouken@1895
   769
    if (kIOReturnSuccess != result) {
slouken@1895
   770
        SDL_SetError("Joystick: Couldn't create a HID object iterator.");
slouken@1895
   771
        return -1;
slouken@1895
   772
    }
slouken@1895
   773
    if (!hidObjectIterator) {   /* there are no joysticks */
slouken@1895
   774
        gpDeviceList = NULL;
slouken@1895
   775
        return 0;
slouken@1895
   776
    }
slouken@1895
   777
    /* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */
slouken@1895
   778
slouken@1895
   779
    /* build flat linked list of devices from device iterator */
slouken@1895
   780
slouken@6690
   781
    gpDeviceList = NULL;
slouken@1895
   782
slouken@1895
   783
    while ((ioHIDDeviceObject = IOIteratorNext(hidObjectIterator))) {
slouken@6690
   784
		AddDeviceHelper( ioHIDDeviceObject );
slouken@1895
   785
    }
slouken@1895
   786
    result = IOObjectRelease(hidObjectIterator);        /* release the iterator */
slouken@6690
   787
	
slouken@6690
   788
	/* now connect notification for new devices */
slouken@6690
   789
	notificationPort = IONotificationPortCreate(masterPort);
slouken@6690
   790
	hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
slouken@1895
   791
slouken@6690
   792
	CFRunLoopAddSource(CFRunLoopGetCurrent(), 
slouken@6690
   793
					   IONotificationPortGetRunLoopSource(notificationPort), 
slouken@6690
   794
					   kCFRunLoopDefaultMode);
slouken@6690
   795
	
slouken@6690
   796
	// Register for notifications when a serial port is added to the system
slouken@6690
   797
	result = IOServiceAddMatchingNotification(notificationPort,
slouken@6690
   798
															kIOFirstMatchNotification,
slouken@6690
   799
															hidMatchDictionary,
slouken@6690
   800
															JoystickDeviceWasAddedCallback,
slouken@6690
   801
															NULL,           
slouken@6690
   802
															&portIterator);
slouken@6690
   803
	while (IOIteratorNext(portIterator)) {}; // Run out the iterator or notifications won't start (you can also use it to iterate the available devices).
slouken@1895
   804
slouken@6690
   805
    return SDL_SYS_NumJoysticks();
slouken@172
   806
}
slouken@172
   807
slouken@172
   808
/* Function to get the device-dependent name of a joystick */
slouken@1895
   809
const char *
slouken@6690
   810
SDL_SYS_JoystickNameForIndex(int index)
slouken@172
   811
{
slouken@1895
   812
    recDevice *device = gpDeviceList;
slouken@172
   813
slouken@1895
   814
    for (; index > 0; index--)
slouken@1895
   815
        device = device->pNext;
slouken@1895
   816
slouken@6690
   817
	return device->product;
slouken@172
   818
}
slouken@172
   819
slouken@172
   820
/* Function to open a joystick for use.
slouken@172
   821
 * The joystick to open is specified by the index field of the joystick.
slouken@172
   822
 * This should fill the nbuttons and naxes fields of the joystick structure.
slouken@172
   823
 * It returns 0, or -1 if there is an error.
slouken@172
   824
 */
slouken@1895
   825
int
slouken@6690
   826
SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
slouken@172
   827
{
slouken@1895
   828
    recDevice *device = gpDeviceList;
slouken@1895
   829
    int index;
slouken@172
   830
slouken@6690
   831
    for (index = device_index; index > 0; index--)
slouken@1895
   832
        device = device->pNext;
slouken@172
   833
slouken@6698
   834
	joystick->instance_id = device->instance_id;
slouken@1895
   835
    joystick->hwdata = device;
slouken@6690
   836
	joystick->name = device->product;
slouken@172
   837
slouken@6690
   838
	joystick->naxes = device->axes;
slouken@6690
   839
	joystick->nhats = device->hats;
slouken@6690
   840
	joystick->nballs = 0;
slouken@6690
   841
	joystick->nbuttons = device->buttons;
slouken@1895
   842
    return 0;
slouken@172
   843
}
slouken@172
   844
slouken@6690
   845
slouken@6690
   846
/* Function to return the instance id of the joystick at device_index
slouken@6690
   847
 */
slouken@6690
   848
SDL_JoystickID
slouken@6690
   849
SDL_SYS_GetInstanceIdOfDeviceIndex( int device_index )
slouken@6690
   850
{
slouken@6690
   851
    recDevice *device = gpDeviceList;
slouken@6690
   852
    int index;
slouken@6690
   853
	
slouken@6690
   854
    for (index = device_index; index > 0; index--)
slouken@6690
   855
        device = device->pNext;
slouken@6690
   856
slouken@6690
   857
	return device->instance_id;
slouken@6690
   858
}
slouken@6690
   859
slouken@6690
   860
slouken@6690
   861
/* Function to cause any queued joystick insertions to be processed
slouken@6690
   862
 */
slouken@6690
   863
void
slouken@6690
   864
SDL_SYS_JoystickDetect()
slouken@6690
   865
{
slouken@6690
   866
	if ( s_bDeviceAdded )
slouken@6690
   867
	{
slouken@6690
   868
		recDevice *device = gpDeviceList;
slouken@6690
   869
		s_bDeviceAdded = 0;
slouken@6690
   870
		int device_index = 0;
slouken@6690
   871
		// send notifications
slouken@6690
   872
		while ( device )
slouken@6690
   873
		{
slouken@6690
   874
			if ( device->send_open_event )
slouken@6690
   875
			{
slouken@6690
   876
				device->send_open_event = 0;
slouken@6690
   877
#if !SDL_EVENTS_DISABLED
slouken@6690
   878
				SDL_Event event;
slouken@6690
   879
				event.type = SDL_JOYDEVICEADDED;
slouken@6690
   880
				
slouken@6690
   881
				if (SDL_GetEventState(event.type) == SDL_ENABLE) {
slouken@6690
   882
					event.jdevice.which = device_index;
slouken@6690
   883
					if ((SDL_EventOK == NULL)
slouken@6690
   884
						|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
slouken@6690
   885
						SDL_PushEvent(&event);
slouken@6690
   886
					}
slouken@6690
   887
				}
slouken@6690
   888
#endif /* !SDL_EVENTS_DISABLED */
slouken@6690
   889
			}
slouken@6690
   890
			device_index++;
slouken@6690
   891
			device = device->pNext;
slouken@6690
   892
		}
slouken@6690
   893
	}
slouken@6690
   894
}
slouken@6690
   895
slouken@6690
   896
slouken@172
   897
/* Function to update the state of a joystick - called as a device poll.
slouken@172
   898
 * This function shouldn't update the joystick structure directly,
slouken@172
   899
 * but instead should call SDL_PrivateJoystick*() to deliver events
slouken@172
   900
 * and update joystick device state.
slouken@172
   901
 */
slouken@1895
   902
void
slouken@1895
   903
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
slouken@172
   904
{
slouken@6690
   905
	recDevice *device = joystick->hwdata;
slouken@1895
   906
    recElement *element;
slouken@2287
   907
    SInt32 value, range;
slouken@1895
   908
    int i;
slouken@858
   909
slouken@6690
   910
	if ( !device )
slouken@6690
   911
		return;
slouken@6690
   912
slouken@1895
   913
    if (device->removed) {      /* device was unplugged; ignore it. */
slouken@6690
   914
		recDevice *devicelist = gpDeviceList;
slouken@6690
   915
		joystick->closed = 1;
slouken@6690
   916
		joystick->uncentered = 1;
slouken@6690
   917
		
slouken@6690
   918
		if ( devicelist == device )
slouken@6690
   919
		{
slouken@6690
   920
			gpDeviceList = device->pNext;
slouken@6690
   921
		}
slouken@6690
   922
		else
slouken@6690
   923
		{
slouken@6690
   924
			while ( devicelist->pNext != device )
slouken@6690
   925
			{
slouken@6690
   926
				devicelist = devicelist->pNext;
slouken@6690
   927
			}
slouken@6690
   928
			
slouken@6690
   929
			devicelist->pNext = device->pNext;
slouken@6690
   930
		}
slouken@6690
   931
		
slouken@6690
   932
		DisposePtr((Ptr) device);
slouken@6690
   933
		joystick->hwdata = NULL;
slouken@858
   934
slouken@6690
   935
#if !SDL_EVENTS_DISABLED
slouken@6690
   936
		SDL_Event event;
slouken@6690
   937
		event.type = SDL_JOYDEVICEREMOVED;
slouken@6690
   938
		
slouken@6690
   939
		if (SDL_GetEventState(event.type) == SDL_ENABLE) {
slouken@6690
   940
			event.jdevice.which = joystick->instance_id;
slouken@6690
   941
			if ((SDL_EventOK == NULL)
slouken@6690
   942
				|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
slouken@6690
   943
				SDL_PushEvent(&event);
slouken@6690
   944
			}
slouken@6690
   945
		}
slouken@6690
   946
#endif /* !SDL_EVENTS_DISABLED */
slouken@6690
   947
		
slouken@1895
   948
        return;
slouken@1895
   949
    }
slouken@858
   950
slouken@1895
   951
    element = device->firstAxis;
slouken@1895
   952
    i = 0;
slouken@1895
   953
    while (element) {
slouken@1895
   954
        value = HIDScaledCalibratedValue(device, element, -32768, 32767);
slouken@1895
   955
        if (value != joystick->axes[i])
slouken@1895
   956
            SDL_PrivateJoystickAxis(joystick, i, value);
slouken@1895
   957
        element = element->pNext;
slouken@1895
   958
        ++i;
slouken@1895
   959
    }
slouken@1895
   960
slouken@1895
   961
    element = device->firstButton;
slouken@1895
   962
    i = 0;
slouken@1895
   963
    while (element) {
slouken@1895
   964
        value = HIDGetElementValue(device, element);
slouken@1895
   965
        if (value > 1)          /* handle pressure-sensitive buttons */
slouken@629
   966
            value = 1;
slouken@1895
   967
        if (value != joystick->buttons[i])
slouken@1895
   968
            SDL_PrivateJoystickButton(joystick, i, value);
slouken@1895
   969
        element = element->pNext;
slouken@1895
   970
        ++i;
slouken@1895
   971
    }
slouken@172
   972
slouken@1895
   973
    element = device->firstHat;
slouken@1895
   974
    i = 0;
slouken@1895
   975
    while (element) {
slouken@1895
   976
        Uint8 pos = 0;
slouken@1895
   977
slouken@2287
   978
        range = (element->max - element->min + 1);
slouken@2287
   979
        value = HIDGetElementValue(device, element) - element->min;
bob@2295
   980
        if (range == 4)         /* 4 position hatswitch - scale up value */
slouken@1895
   981
            value *= 2;
bob@2295
   982
        else if (range != 8)    /* Neither a 4 nor 8 positions - fall back to default position (centered) */
slouken@1895
   983
            value = -1;
slouken@1895
   984
        switch (value) {
slouken@1895
   985
        case 0:
slouken@1895
   986
            pos = SDL_HAT_UP;
slouken@1895
   987
            break;
slouken@1895
   988
        case 1:
slouken@1895
   989
            pos = SDL_HAT_RIGHTUP;
slouken@1895
   990
            break;
slouken@1895
   991
        case 2:
slouken@1895
   992
            pos = SDL_HAT_RIGHT;
slouken@1895
   993
            break;
slouken@1895
   994
        case 3:
slouken@1895
   995
            pos = SDL_HAT_RIGHTDOWN;
slouken@1895
   996
            break;
slouken@1895
   997
        case 4:
slouken@1895
   998
            pos = SDL_HAT_DOWN;
slouken@1895
   999
            break;
slouken@1895
  1000
        case 5:
slouken@1895
  1001
            pos = SDL_HAT_LEFTDOWN;
slouken@1895
  1002
            break;
slouken@1895
  1003
        case 6:
slouken@1895
  1004
            pos = SDL_HAT_LEFT;
slouken@1895
  1005
            break;
slouken@1895
  1006
        case 7:
slouken@1895
  1007
            pos = SDL_HAT_LEFTUP;
slouken@1895
  1008
            break;
slouken@1895
  1009
        default:
slouken@1895
  1010
            /* Every other value is mapped to center. We do that because some
slouken@1895
  1011
             * joysticks use 8 and some 15 for this value, and apparently
slouken@1895
  1012
             * there are even more variants out there - so we try to be generous.
slouken@1895
  1013
             */
slouken@1895
  1014
            pos = SDL_HAT_CENTERED;
slouken@1895
  1015
            break;
slouken@1895
  1016
        }
slouken@1895
  1017
        if (pos != joystick->hats[i])
slouken@1895
  1018
            SDL_PrivateJoystickHat(joystick, i, pos);
slouken@1895
  1019
        element = element->pNext;
slouken@1895
  1020
        ++i;
slouken@1895
  1021
    }
slouken@1895
  1022
slouken@1895
  1023
    return;
slouken@172
  1024
}
slouken@172
  1025
slouken@6690
  1026
slouken@6690
  1027
/* Function to query if the joystick is currently attached
slouken@6690
  1028
 *   It returns 1 if attached, 0 otherwise.
slouken@6690
  1029
 */
slouken@6690
  1030
int
slouken@6690
  1031
SDL_SYS_JoystickAttached(SDL_Joystick * joystick)
slouken@6690
  1032
{
slouken@6690
  1033
	recDevice *device = gpDeviceList;
slouken@6690
  1034
    int index;
slouken@6690
  1035
	
slouken@6690
  1036
	while ( device )
slouken@6690
  1037
	{
slouken@6690
  1038
		if ( joystick->instance_id == device->instance_id )
slouken@6690
  1039
			return (1);
slouken@6690
  1040
		
slouken@6690
  1041
        device = device->pNext;
slouken@6690
  1042
	}
slouken@6690
  1043
	
slouken@6690
  1044
	return 0;
slouken@6690
  1045
}
slouken@6690
  1046
slouken@6690
  1047
slouken@172
  1048
/* Function to close a joystick after use */
slouken@1895
  1049
void
slouken@1895
  1050
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
slouken@6690
  1051
{	
slouken@6690
  1052
	joystick->closed = 1;
slouken@172
  1053
}
slouken@172
  1054
slouken@172
  1055
/* Function to perform any system-specific joystick related cleanup */
slouken@1895
  1056
void
slouken@1895
  1057
SDL_SYS_JoystickQuit(void)
slouken@172
  1058
{
slouken@1895
  1059
    while (NULL != gpDeviceList)
slouken@1895
  1060
        gpDeviceList = HIDDisposeDevice(&gpDeviceList);
slouken@6690
  1061
	
slouken@6690
  1062
	if ( notificationPort )
slouken@6690
  1063
	{
slouken@6690
  1064
		IONotificationPortDestroy( notificationPort );
slouken@6690
  1065
		notificationPort = 0;
slouken@6690
  1066
	}
slouken@6690
  1067
}
slouken@6690
  1068
slouken@6690
  1069
slouken@6690
  1070
/* Function to return the number of joystick devices plugged in right now*/
slouken@6690
  1071
int
slouken@6690
  1072
SDL_SYS_NumJoysticks()
slouken@6690
  1073
{
slouken@6690
  1074
	recDevice *device = gpDeviceList;
slouken@6690
  1075
    int nJoySticks = 0;
slouken@6690
  1076
	
slouken@6690
  1077
	while ( device )
slouken@6690
  1078
	{
slouken@6690
  1079
		nJoySticks++;
slouken@6690
  1080
        device = device->pNext;
slouken@6690
  1081
	}
slouken@6690
  1082
slouken@6690
  1083
	return nJoySticks;
slouken@6690
  1084
}
slouken@6690
  1085
slouken@6690
  1086
int
slouken@6690
  1087
SDL_SYS_JoystickNeedsPolling()
slouken@6690
  1088
{
slouken@6690
  1089
	return s_bDeviceAdded;
slouken@6690
  1090
}
slouken@6690
  1091
slouken@6693
  1092
JoystickGUID SDL_SYS_PrivateJoystickGetDeviceGUID( int device_index )
slouken@6690
  1093
{
slouken@6690
  1094
    recDevice *device = gpDeviceList;
slouken@6690
  1095
    int index;
slouken@6690
  1096
	
slouken@6690
  1097
    for (index = device_index; index > 0; index--)
slouken@6690
  1098
        device = device->pNext;
slouken@6690
  1099
	
slouken@6690
  1100
	return device->guid;	
slouken@6690
  1101
}
slouken@6690
  1102
slouken@6690
  1103
JoystickGUID SDL_SYS_PrivateJoystickGetGUID(SDL_Joystick *joystick)
slouken@6690
  1104
{
slouken@6690
  1105
	return joystick->hwdata->guid;
slouken@172
  1106
}
slouken@1635
  1107
slouken@1635
  1108
#endif /* SDL_JOYSTICK_IOKIT */
slouken@1895
  1109
/* vi: set ts=4 sw=4 expandtab: */