src/joystick/darwin/SDL_sysjoystick.c
author Sam Lantinga <slouken@libsdl.org>
Tue, 27 Nov 2012 00:58:12 -0800
changeset 6707 70eeb7e3ec2f
parent 6698 28ab2ef7bfc9
child 6718 918ba414168b
permissions -rw-r--r--
Organized joystick hotplug code a bit.
Cleaned up names, return types, etc.
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@6707
    66
static SDL_bool s_bDeviceAdded = SDL_FALSE;
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@6707
   677
	s_bDeviceAdded = SDL_TRUE;
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@6707
   808
/* Function to return the number of joystick devices plugged in right now */
slouken@6707
   809
int
slouken@6707
   810
SDL_SYS_NumJoysticks()
slouken@6707
   811
{
slouken@6707
   812
	recDevice *device = gpDeviceList;
slouken@6707
   813
    int nJoySticks = 0;
slouken@6707
   814
	
slouken@6707
   815
	while ( device )
slouken@6707
   816
	{
slouken@6707
   817
		nJoySticks++;
slouken@6707
   818
        device = device->pNext;
slouken@6707
   819
	}
slouken@6707
   820
slouken@6707
   821
	return nJoySticks;
slouken@6707
   822
}
slouken@6707
   823
slouken@6707
   824
/* Function to cause any queued joystick insertions to be processed
slouken@6707
   825
 */
slouken@6707
   826
void
slouken@6707
   827
SDL_SYS_JoystickDetect()
slouken@6707
   828
{
slouken@6707
   829
	if ( s_bDeviceAdded )
slouken@6707
   830
	{
slouken@6707
   831
		recDevice *device = gpDeviceList;
slouken@6707
   832
		s_bDeviceAdded = SDL_FALSE;
slouken@6707
   833
		int device_index = 0;
slouken@6707
   834
		// send notifications
slouken@6707
   835
		while ( device )
slouken@6707
   836
		{
slouken@6707
   837
			if ( device->send_open_event )
slouken@6707
   838
			{
slouken@6707
   839
				device->send_open_event = 0;
slouken@6707
   840
#if !SDL_EVENTS_DISABLED
slouken@6707
   841
				SDL_Event event;
slouken@6707
   842
				event.type = SDL_JOYDEVICEADDED;
slouken@6707
   843
				
slouken@6707
   844
				if (SDL_GetEventState(event.type) == SDL_ENABLE) {
slouken@6707
   845
					event.jdevice.which = device_index;
slouken@6707
   846
					if ((SDL_EventOK == NULL)
slouken@6707
   847
						|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
slouken@6707
   848
						SDL_PushEvent(&event);
slouken@6707
   849
					}
slouken@6707
   850
				}
slouken@6707
   851
#endif /* !SDL_EVENTS_DISABLED */
slouken@6707
   852
			}
slouken@6707
   853
			device_index++;
slouken@6707
   854
			device = device->pNext;
slouken@6707
   855
		}
slouken@6707
   856
	}
slouken@6707
   857
}
slouken@6707
   858
slouken@6707
   859
SDL_bool
slouken@6707
   860
SDL_SYS_JoystickNeedsPolling()
slouken@6707
   861
{
slouken@6707
   862
	return s_bDeviceAdded;
slouken@6707
   863
}
slouken@6707
   864
slouken@172
   865
/* Function to get the device-dependent name of a joystick */
slouken@1895
   866
const char *
slouken@6707
   867
SDL_SYS_JoystickNameForDeviceIndex(int device_index)
slouken@172
   868
{
slouken@1895
   869
    recDevice *device = gpDeviceList;
slouken@172
   870
slouken@6707
   871
    for (; device_index > 0; device_index--)
slouken@1895
   872
        device = device->pNext;
slouken@1895
   873
slouken@6690
   874
	return device->product;
slouken@172
   875
}
slouken@172
   876
slouken@6707
   877
/* Function to return the instance id of the joystick at device_index
slouken@6707
   878
 */
slouken@6707
   879
SDL_JoystickID
slouken@6707
   880
SDL_SYS_GetInstanceIdOfDeviceIndex(int device_index)
slouken@6707
   881
{
slouken@6707
   882
    recDevice *device = gpDeviceList;
slouken@6707
   883
    int index;
slouken@6707
   884
	
slouken@6707
   885
    for (index = device_index; index > 0; index--)
slouken@6707
   886
        device = device->pNext;
slouken@6707
   887
slouken@6707
   888
	return device->instance_id;
slouken@6707
   889
}
slouken@6707
   890
slouken@172
   891
/* Function to open a joystick for use.
slouken@172
   892
 * The joystick to open is specified by the index field of the joystick.
slouken@172
   893
 * This should fill the nbuttons and naxes fields of the joystick structure.
slouken@172
   894
 * It returns 0, or -1 if there is an error.
slouken@172
   895
 */
slouken@1895
   896
int
slouken@6690
   897
SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
slouken@172
   898
{
slouken@1895
   899
    recDevice *device = gpDeviceList;
slouken@1895
   900
    int index;
slouken@172
   901
slouken@6690
   902
    for (index = device_index; index > 0; index--)
slouken@1895
   903
        device = device->pNext;
slouken@172
   904
slouken@6698
   905
	joystick->instance_id = device->instance_id;
slouken@1895
   906
    joystick->hwdata = device;
slouken@6690
   907
	joystick->name = device->product;
slouken@172
   908
slouken@6690
   909
	joystick->naxes = device->axes;
slouken@6690
   910
	joystick->nhats = device->hats;
slouken@6690
   911
	joystick->nballs = 0;
slouken@6690
   912
	joystick->nbuttons = device->buttons;
slouken@1895
   913
    return 0;
slouken@172
   914
}
slouken@172
   915
slouken@6707
   916
/* Function to query if the joystick is currently attached
slouken@6707
   917
 *   It returns 1 if attached, 0 otherwise.
slouken@6690
   918
 */
slouken@6707
   919
SDL_bool
slouken@6707
   920
SDL_SYS_JoystickAttached(SDL_Joystick * joystick)
slouken@6690
   921
{
slouken@6707
   922
	recDevice *device = gpDeviceList;
slouken@6690
   923
    int index;
slouken@6690
   924
	
slouken@6707
   925
	while ( device )
slouken@6707
   926
	{
slouken@6707
   927
		if ( joystick->instance_id == device->instance_id )
slouken@6707
   928
			return SDL_TRUE;
slouken@6707
   929
slouken@6690
   930
        device = device->pNext;
slouken@6707
   931
	}
slouken@6707
   932
	
slouken@6707
   933
	return SDL_FALSE;
slouken@6690
   934
}
slouken@6690
   935
slouken@172
   936
/* Function to update the state of a joystick - called as a device poll.
slouken@172
   937
 * This function shouldn't update the joystick structure directly,
slouken@172
   938
 * but instead should call SDL_PrivateJoystick*() to deliver events
slouken@172
   939
 * and update joystick device state.
slouken@172
   940
 */
slouken@1895
   941
void
slouken@1895
   942
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
slouken@172
   943
{
slouken@6690
   944
	recDevice *device = joystick->hwdata;
slouken@1895
   945
    recElement *element;
slouken@2287
   946
    SInt32 value, range;
slouken@1895
   947
    int i;
slouken@858
   948
slouken@6690
   949
	if ( !device )
slouken@6690
   950
		return;
slouken@6690
   951
slouken@1895
   952
    if (device->removed) {      /* device was unplugged; ignore it. */
slouken@6690
   953
		recDevice *devicelist = gpDeviceList;
slouken@6690
   954
		joystick->closed = 1;
slouken@6690
   955
		joystick->uncentered = 1;
slouken@6690
   956
		
slouken@6690
   957
		if ( devicelist == device )
slouken@6690
   958
		{
slouken@6690
   959
			gpDeviceList = device->pNext;
slouken@6690
   960
		}
slouken@6690
   961
		else
slouken@6690
   962
		{
slouken@6690
   963
			while ( devicelist->pNext != device )
slouken@6690
   964
			{
slouken@6690
   965
				devicelist = devicelist->pNext;
slouken@6690
   966
			}
slouken@6690
   967
			
slouken@6690
   968
			devicelist->pNext = device->pNext;
slouken@6690
   969
		}
slouken@6690
   970
		
slouken@6690
   971
		DisposePtr((Ptr) device);
slouken@6690
   972
		joystick->hwdata = NULL;
slouken@858
   973
slouken@6690
   974
#if !SDL_EVENTS_DISABLED
slouken@6690
   975
		SDL_Event event;
slouken@6690
   976
		event.type = SDL_JOYDEVICEREMOVED;
slouken@6690
   977
		
slouken@6690
   978
		if (SDL_GetEventState(event.type) == SDL_ENABLE) {
slouken@6690
   979
			event.jdevice.which = joystick->instance_id;
slouken@6690
   980
			if ((SDL_EventOK == NULL)
slouken@6690
   981
				|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
slouken@6690
   982
				SDL_PushEvent(&event);
slouken@6690
   983
			}
slouken@6690
   984
		}
slouken@6690
   985
#endif /* !SDL_EVENTS_DISABLED */
slouken@6690
   986
		
slouken@1895
   987
        return;
slouken@1895
   988
    }
slouken@858
   989
slouken@1895
   990
    element = device->firstAxis;
slouken@1895
   991
    i = 0;
slouken@1895
   992
    while (element) {
slouken@1895
   993
        value = HIDScaledCalibratedValue(device, element, -32768, 32767);
slouken@1895
   994
        if (value != joystick->axes[i])
slouken@1895
   995
            SDL_PrivateJoystickAxis(joystick, i, value);
slouken@1895
   996
        element = element->pNext;
slouken@1895
   997
        ++i;
slouken@1895
   998
    }
slouken@1895
   999
slouken@1895
  1000
    element = device->firstButton;
slouken@1895
  1001
    i = 0;
slouken@1895
  1002
    while (element) {
slouken@1895
  1003
        value = HIDGetElementValue(device, element);
slouken@1895
  1004
        if (value > 1)          /* handle pressure-sensitive buttons */
slouken@629
  1005
            value = 1;
slouken@1895
  1006
        if (value != joystick->buttons[i])
slouken@1895
  1007
            SDL_PrivateJoystickButton(joystick, i, value);
slouken@1895
  1008
        element = element->pNext;
slouken@1895
  1009
        ++i;
slouken@1895
  1010
    }
slouken@172
  1011
slouken@1895
  1012
    element = device->firstHat;
slouken@1895
  1013
    i = 0;
slouken@1895
  1014
    while (element) {
slouken@1895
  1015
        Uint8 pos = 0;
slouken@1895
  1016
slouken@2287
  1017
        range = (element->max - element->min + 1);
slouken@2287
  1018
        value = HIDGetElementValue(device, element) - element->min;
bob@2295
  1019
        if (range == 4)         /* 4 position hatswitch - scale up value */
slouken@1895
  1020
            value *= 2;
bob@2295
  1021
        else if (range != 8)    /* Neither a 4 nor 8 positions - fall back to default position (centered) */
slouken@1895
  1022
            value = -1;
slouken@1895
  1023
        switch (value) {
slouken@1895
  1024
        case 0:
slouken@1895
  1025
            pos = SDL_HAT_UP;
slouken@1895
  1026
            break;
slouken@1895
  1027
        case 1:
slouken@1895
  1028
            pos = SDL_HAT_RIGHTUP;
slouken@1895
  1029
            break;
slouken@1895
  1030
        case 2:
slouken@1895
  1031
            pos = SDL_HAT_RIGHT;
slouken@1895
  1032
            break;
slouken@1895
  1033
        case 3:
slouken@1895
  1034
            pos = SDL_HAT_RIGHTDOWN;
slouken@1895
  1035
            break;
slouken@1895
  1036
        case 4:
slouken@1895
  1037
            pos = SDL_HAT_DOWN;
slouken@1895
  1038
            break;
slouken@1895
  1039
        case 5:
slouken@1895
  1040
            pos = SDL_HAT_LEFTDOWN;
slouken@1895
  1041
            break;
slouken@1895
  1042
        case 6:
slouken@1895
  1043
            pos = SDL_HAT_LEFT;
slouken@1895
  1044
            break;
slouken@1895
  1045
        case 7:
slouken@1895
  1046
            pos = SDL_HAT_LEFTUP;
slouken@1895
  1047
            break;
slouken@1895
  1048
        default:
slouken@1895
  1049
            /* Every other value is mapped to center. We do that because some
slouken@1895
  1050
             * joysticks use 8 and some 15 for this value, and apparently
slouken@1895
  1051
             * there are even more variants out there - so we try to be generous.
slouken@1895
  1052
             */
slouken@1895
  1053
            pos = SDL_HAT_CENTERED;
slouken@1895
  1054
            break;
slouken@1895
  1055
        }
slouken@1895
  1056
        if (pos != joystick->hats[i])
slouken@1895
  1057
            SDL_PrivateJoystickHat(joystick, i, pos);
slouken@1895
  1058
        element = element->pNext;
slouken@1895
  1059
        ++i;
slouken@1895
  1060
    }
slouken@1895
  1061
slouken@1895
  1062
    return;
slouken@172
  1063
}
slouken@172
  1064
slouken@172
  1065
/* Function to close a joystick after use */
slouken@1895
  1066
void
slouken@1895
  1067
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
slouken@6690
  1068
{	
slouken@6690
  1069
	joystick->closed = 1;
slouken@172
  1070
}
slouken@172
  1071
slouken@172
  1072
/* Function to perform any system-specific joystick related cleanup */
slouken@1895
  1073
void
slouken@1895
  1074
SDL_SYS_JoystickQuit(void)
slouken@172
  1075
{
slouken@1895
  1076
    while (NULL != gpDeviceList)
slouken@1895
  1077
        gpDeviceList = HIDDisposeDevice(&gpDeviceList);
slouken@6690
  1078
	
slouken@6690
  1079
	if ( notificationPort )
slouken@6690
  1080
	{
slouken@6690
  1081
		IONotificationPortDestroy( notificationPort );
slouken@6690
  1082
		notificationPort = 0;
slouken@6690
  1083
	}
slouken@6690
  1084
}
slouken@6690
  1085
slouken@6690
  1086
slouken@6707
  1087
JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
slouken@6690
  1088
{
slouken@6690
  1089
    recDevice *device = gpDeviceList;
slouken@6690
  1090
    int index;
slouken@6690
  1091
	
slouken@6690
  1092
    for (index = device_index; index > 0; index--)
slouken@6690
  1093
        device = device->pNext;
slouken@6690
  1094
	
slouken@6690
  1095
	return device->guid;	
slouken@6690
  1096
}
slouken@6690
  1097
slouken@6707
  1098
JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick *joystick)
slouken@6690
  1099
{
slouken@6690
  1100
	return joystick->hwdata->guid;
slouken@172
  1101
}
slouken@1635
  1102
slouken@1635
  1103
#endif /* SDL_JOYSTICK_IOKIT */
slouken@1895
  1104
/* vi: set ts=4 sw=4 expandtab: */