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