5 // Created by Sam McCall on 4/05/09.
10 static NSArray *ActionsForElement(IOHIDDeviceRef device, id base) {
11 CFArrayRef elements = IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone);
12 NSMutableArray *children = [NSMutableArray arrayWithCapacity:CFArrayGetCount(elements)];
17 for (int i = 0; i < CFArrayGetCount(elements); i++) {
18 IOHIDElementRef element = (IOHIDElementRef)CFArrayGetValueAtIndex(elements, i);
19 int type = IOHIDElementGetType(element);
20 int usage = IOHIDElementGetUsage(element);
21 int usagePage = IOHIDElementGetUsagePage(element);
22 int max = IOHIDElementGetPhysicalMax(element);
23 int min = IOHIDElementGetPhysicalMin(element);
24 CFStringRef elName = IOHIDElementGetName(element);
26 JSAction *action = nil;
28 if (!(type == kIOHIDElementTypeInput_Misc
29 || type == kIOHIDElementTypeInput_Axis
30 || type == kIOHIDElementTypeInput_Button))
33 if (max - min == 1 || usagePage == kHIDPage_Button || type == kIOHIDElementTypeInput_Button) {
34 action = [[JSActionButton alloc] initWithName:(__bridge NSString *)elName
37 } else if (usage == kHIDUsage_GD_Hatswitch) {
38 action = [[JSActionHat alloc] init];
39 } else if (usage >= kHIDUsage_GD_X && usage <= kHIDUsage_GD_Rz) {
40 // TODO(jfw): Scaling equation doesn't seem right if min != 0.
41 action = [[JSActionAnalog alloc] initWithIndex:++axes
43 scale:2.f / (max - min)];
48 // TODO(jfw): Should be moved into better constructors.
50 action.cookie = IOHIDElementGetCookie(element);
51 [children addObject:action];
56 @implementation Joystick
59 @synthesize productId;
60 @synthesize productName;
65 - (id)initWithDevice:(IOHIDDeviceRef)dev {
66 if ((self = [super init])) {
68 self.productName = (__bridge NSString *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDProductKey));
69 self.vendorId = [(__bridge NSNumber *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDVendorIDKey)) intValue];
70 self.productId = [(__bridge NSNumber *)IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDProductIDKey)) intValue];
71 self.children = ActionsForElement(dev, self);
77 return [NSString stringWithFormat:@"%@ #%d", productName, index];
85 return [NSString stringWithFormat: @"%d:%d:%d", vendorId, productId, index];
88 - (JSAction *)findActionByCookie:(void *)cookie {
89 for (JSAction *child in children)
90 if (child.cookie == cookie)
95 - (id)handlerForEvent:(IOHIDValueRef) value {
96 JSAction *mainAction = [self actionForEvent:value];
97 return [mainAction findSubActionForValue:value];
100 - (JSAction *)actionForEvent:(IOHIDValueRef)value {
101 IOHIDElementRef elt = IOHIDValueGetElement(value);
102 void *cookie = IOHIDElementGetCookie(elt);
103 return [self findActionByCookie:cookie];