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