a708d82aab8f19bc33b7b87cb0c3e7ee76558ad1
[enjoyable.git] / NJInputController.m
1 //
2 // NJInputController.h
3 // Enjoy
4 //
5 // Created by Sam McCall on 4/05/09.
6 //
7
8 #import "NJInputController.h"
9
10 #import "NJMapping.h"
11 #import "NJMappingsController.h"
12 #import "NJDevice.h"
13 #import "NJInput.h"
14 #import "Target.h"
15 #import "TargetController.h"
16 #import "NJEvents.h"
17
18 @implementation NJInputController {
19 IOHIDManagerRef hidManager;
20 NSTimer *continuousTimer;
21 NSMutableArray *runningTargets;
22 NSMutableArray *_joysticks;
23 }
24
25 - (id)init {
26 if ((self = [super init])) {
27 _joysticks = [[NSMutableArray alloc] initWithCapacity:16];
28 runningTargets = [[NSMutableArray alloc] initWithCapacity:32];
29 }
30 return self;
31 }
32
33 - (void)dealloc {
34 [continuousTimer invalidate];
35 IOHIDManagerClose(hidManager, kIOHIDOptionsTypeNone);
36 CFRelease(hidManager);
37 }
38
39 - (void)expandRecursive:(id <NJInputPathElement>)pathElement {
40 if (pathElement) {
41 [self expandRecursive:pathElement.base];
42 [outlineView expandItem:pathElement];
43 }
44 }
45
46 - (void)addRunningTarget:(Target *)target {
47 if (![runningTargets containsObject:target]) {
48 [runningTargets addObject:target];
49 }
50 if (!continuousTimer) {
51 continuousTimer = [NSTimer scheduledTimerWithTimeInterval:1.f/60.f
52 target:self
53 selector:@selector(updateContinuousInputs:)
54 userInfo:nil
55 repeats:YES];
56 NSLog(@"Scheduled continuous target timer.");
57 }
58 }
59
60 - (void)runTargetForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
61 NJDevice *dev = [self findJoystickByRef:device];
62 NJInput *mainInput = [dev inputForEvent:value];
63 [mainInput notifyEvent:value];
64 NSArray *children = mainInput.children ? mainInput.children : mainInput ? @[mainInput] : @[];
65 for (NJInput *subInput in children) {
66 Target *target = mappingsController.currentMapping[subInput];
67 target.magnitude = mainInput.magnitude;
68 target.running = subInput.active;
69 if (target.running && target.isContinuous)
70 [self addRunningTarget:target];
71 }
72 }
73
74 - (void)showTargetForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
75 NJDevice *dev = [self findJoystickByRef:device];
76 NJInput *handler = [dev handlerForEvent:value];
77 if (!handler)
78 return;
79
80 [self expandRecursive:handler];
81 [outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[outlineView rowForItem:handler]] byExtendingSelection: NO];
82 [targetController focusKey];
83 }
84
85 static void input_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDValueRef value) {
86 NJInputController *controller = (__bridge NJInputController *)ctx;
87 IOHIDDeviceRef device = IOHIDQueueGetDevice(inSender);
88
89 if (controller.translatingEvents) {
90 [controller runTargetForDevice:device value:value];
91 } else if ([NSApplication sharedApplication].mainWindow.isVisible) {
92 [controller showTargetForDevice:device value:value];
93 }
94 }
95
96 static int findAvailableIndex(NSArray *list, NJDevice *dev) {
97 for (int index = 1; ; index++) {
98 BOOL available = YES;
99 for (NJDevice *used in list) {
100 if ([used.productName isEqualToString:dev.productName] && used.index == index) {
101 available = NO;
102 break;
103 }
104 }
105 if (available)
106 return index;
107 }
108 }
109
110 - (void)addJoystickForDevice:(IOHIDDeviceRef)device {
111 IOHIDDeviceRegisterInputValueCallback(device, input_callback, (__bridge void*)self);
112 NJDevice *dev = [[NJDevice alloc] initWithDevice:device];
113 dev.index = findAvailableIndex(_joysticks, dev);
114 [_joysticks addObject:dev];
115 [outlineView reloadData];
116 }
117
118 static void add_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
119 NJInputController *controller = (__bridge NJInputController *)ctx;
120 [controller addJoystickForDevice:device];
121 }
122
123 - (NJDevice *)findJoystickByRef:(IOHIDDeviceRef)device {
124 for (NJDevice *dev in _joysticks)
125 if (dev.device == device)
126 return dev;
127 return nil;
128 }
129
130 static void remove_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
131 NJInputController *controller = (__bridge NJInputController *)ctx;
132 [controller removeJoystickForDevice:device];
133 }
134
135 - (void)removeJoystickForDevice:(IOHIDDeviceRef)device {
136 NJDevice *match = [self findJoystickByRef:device];
137 IOHIDDeviceRegisterInputValueCallback(device, NULL, NULL);
138 if (match) {
139 [_joysticks removeObject:match];
140 [outlineView reloadData];
141 }
142
143 }
144
145 - (void)updateContinuousInputs:(NSTimer *)timer {
146 self.mouseLoc = [NSEvent mouseLocation];
147 for (Target *target in [runningTargets copy]) {
148 if (![target update:self]) {
149 [runningTargets removeObject:target];
150 }
151 }
152 if (!runningTargets.count) {
153 [continuousTimer invalidate];
154 continuousTimer = nil;
155 NSLog(@"Unscheduled continuous target timer.");
156 }
157 }
158
159 #define NSSTR(e) ((NSString *)CFSTR(e))
160
161 - (void)setup {
162 hidManager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
163 NSArray *criteria = @[ @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
164 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_Joystick) },
165 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
166 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_GamePad) },
167 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
168 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_MultiAxisController) }
169 ];
170 IOHIDManagerSetDeviceMatchingMultiple(hidManager, (__bridge CFArrayRef)criteria);
171
172 IOHIDManagerScheduleWithRunLoop(hidManager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
173 IOReturn ret = IOHIDManagerOpen(hidManager, kIOHIDOptionsTypeNone);
174 if (ret != kIOReturnSuccess) {
175 [[NSAlert alertWithMessageText:@"Input devices are unavailable"
176 defaultButton:nil
177 alternateButton:nil
178 otherButton:nil
179 informativeTextWithFormat:@"Error 0x%08x occured trying to access your devices. "
180 @"Input may not be correctly detected or mapped.",
181 ret]
182 beginSheetModalForWindow:outlineView.window
183 modalDelegate:nil
184 didEndSelector:nil
185 contextInfo:nil];
186 }
187
188 IOHIDManagerRegisterDeviceMatchingCallback(hidManager, add_callback, (__bridge void *)self);
189 IOHIDManagerRegisterDeviceRemovalCallback(hidManager, remove_callback, (__bridge void *)self);
190 }
191
192 - (NJInput *)selectedInput {
193 id <NJInputPathElement> item = [outlineView itemAtRow:outlineView.selectedRow];
194 return (!item.children && item.base) ? item : nil;
195 }
196
197 - (NSInteger)outlineView:(NSOutlineView *)outlineView
198 numberOfChildrenOfItem:(id <NJInputPathElement>)item {
199 return item ? item.children.count : _joysticks.count;
200 }
201
202 - (BOOL)outlineView:(NSOutlineView *)outlineView
203 isItemExpandable:(id <NJInputPathElement>)item {
204 return item ? [[item children] count] > 0: YES;
205 }
206
207 - (id)outlineView:(NSOutlineView *)outlineView
208 child:(NSInteger)index
209 ofItem:(id <NJInputPathElement>)item {
210 return item ? item.children[index] : _joysticks[index];
211 }
212
213 - (id)outlineView:(NSOutlineView *)outlineView
214 objectValueForTableColumn:(NSTableColumn *)tableColumn
215 byItem:(id <NJInputPathElement>)item {
216 return item ? item.name : @"root";
217 }
218
219 - (void)outlineViewSelectionDidChange:(NSNotification *)notification {
220
221 [targetController loadCurrent];
222 }
223
224 - (void)setTranslatingEvents:(BOOL)translatingEvents {
225 if (translatingEvents != _translatingEvents) {
226 _translatingEvents = translatingEvents;
227 NSString *name = translatingEvents
228 ? NJEventTranslationActivated
229 : NJEventTranslationDeactivated;
230 [NSNotificationCenter.defaultCenter postNotificationName:name
231 object:self];
232 }
233 }
234
235 @end