5 // Created by Sam McCall on 4/05/09.
11 #import "JSActionAnalog.h"
12 #import "JSActionButton.h"
13 #import "JSActionHat.h"
15 static NSArray *ActionsForElement(IOHIDDeviceRef device, id base) {
16 CFArrayRef elements = IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone);
17 NSMutableArray *children = [NSMutableArray arrayWithCapacity:CFArrayGetCount(elements)];
23 for (int i = 0; i < CFArrayGetCount(elements); i++) {
24 IOHIDElementRef element = (IOHIDElementRef)CFArrayGetValueAtIndex(elements, i);
25 int type = IOHIDElementGetType(element);
26 int usage = IOHIDElementGetUsage(element);
27 int usagePage = IOHIDElementGetUsagePage(element);
28 int max = IOHIDElementGetPhysicalMax(element);
29 int min = IOHIDElementGetPhysicalMin(element);
30 CFStringRef elName = IOHIDElementGetName(element);
32 JSAction *action = nil;
34 if (!(type == kIOHIDElementTypeInput_Misc
35 || type == kIOHIDElementTypeInput_Axis
36 || type == kIOHIDElementTypeInput_Button))
39 if (max - min == 1 || usagePage == kHIDPage_Button || type == kIOHIDElementTypeInput_Button) {
40 action = [[JSActionButton alloc] initWithName:(__bridge NSString *)elName
43 } else if (usage == kHIDUsage_GD_Hatswitch) {
44 action = [[JSActionHat alloc] initWithIndex:++hats];
45 } else if (usage >= kHIDUsage_GD_X && usage <= kHIDUsage_GD_Rz) {
46 action = [[JSActionAnalog alloc] initWithIndex:++axes
53 // TODO(jfw): Should be moved into better constructors.
55 action.cookie = IOHIDElementGetCookie(element);
56 [children addObject:action];
63 @implementation Joystick
66 @synthesize productId;
67 @synthesize productName;
72 - (id)initWithDevice:(IOHIDDeviceRef)dev {
73 if ((self = [super init])) {
75 self.productName = (__bridge NSString *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDProductKey));
76 self.vendorId = [(__bridge NSNumber *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDVendorIDKey)) intValue];
77 self.productId = [(__bridge NSNumber *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDProductIDKey)) intValue];
78 self.children = ActionsForElement(dev, self);
84 return [NSString stringWithFormat:@"%@ #%d", productName, index];
92 return [NSString stringWithFormat: @"%d:%d:%d", vendorId, productId, index];
95 - (JSAction *)findActionByCookie:(void *)cookie {
96 for (JSAction *child in children)
97 if (child.cookie == cookie)
102 - (id)handlerForEvent:(IOHIDValueRef) value {
103 JSAction *mainAction = [self actionForEvent:value];
104 return [mainAction findSubActionForValue:value];
107 - (JSAction *)actionForEvent:(IOHIDValueRef)value {
108 IOHIDElementRef elt = IOHIDValueGetElement(value);
109 void *cookie = IOHIDElementGetCookie(elt);
110 return [self findActionByCookie:cookie];