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