2 // NJDeviceController.m
5 // Created by Sam McCall on 4/05/09.
8 #import "NJDeviceController.h"
11 #import "NJMappingsController.h"
15 #import "NJOutputController.h"
18 @implementation NJDeviceController {
19 IOHIDManagerRef _hidManager;
20 NSTimer *_continuousOutputsTick;
21 NSMutableArray *_continousOutputs;
22 NSMutableArray *_devices;
26 if ((self = [super init])) {
27 _devices = [[NSMutableArray alloc] initWithCapacity:16];
28 _continousOutputs = [[NSMutableArray alloc] initWithCapacity:32];
34 [_continuousOutputsTick invalidate];
35 IOHIDManagerClose(_hidManager, kIOHIDOptionsTypeNone);
36 CFRelease(_hidManager);
39 - (void)expandRecursive:(id <NJInputPathElement>)pathElement {
41 [self expandRecursive:pathElement.base];
42 [outlineView expandItem:pathElement];
46 - (void)addRunningOutput:(NJOutput *)output {
47 [_continousOutputs addObject:output];
48 if (!_continuousOutputsTick) {
49 _continuousOutputsTick = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0
51 selector:@selector(updateContinuousOutputs:)
57 - (void)runOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
58 NJDevice *dev = [self findDeviceByRef:device];
59 NJInput *mainInput = [dev inputForEvent:value];
60 [mainInput notifyEvent:value];
61 NSArray *children = mainInput.children ? mainInput.children : mainInput ? @[mainInput] : @[];
62 for (NJInput *subInput in children) {
63 NJOutput *output = mappingsController.currentMapping[subInput];
64 output.magnitude = subInput.magnitude;
65 output.running = subInput.active;
66 if ((output.running || output.magnitude) && output.isContinuous)
67 [self addRunningOutput:output];
71 - (void)showOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
72 NJDevice *dev = [self findDeviceByRef:device];
73 NJInput *handler = [dev handlerForEvent:value];
77 [self expandRecursive:handler];
78 [outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[outlineView rowForItem:handler]]
79 byExtendingSelection: NO];
80 [outputController focusKey];
83 static void input_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDValueRef value) {
84 NJDeviceController *controller = (__bridge NJDeviceController *)ctx;
85 IOHIDDeviceRef device = IOHIDQueueGetDevice(inSender);
87 if (controller.translatingEvents) {
88 [controller runOutputForDevice:device value:value];
89 } else if ([NSApplication sharedApplication].mainWindow.isVisible) {
90 [controller showOutputForDevice:device value:value];
94 static int findAvailableIndex(NSArray *list, NJDevice *dev) {
95 for (int index = 1; ; index++) {
97 for (NJDevice *used in list) {
98 if ([used.productName isEqualToString:dev.productName] && used.index == index) {
108 - (void)addDeviceForDevice:(IOHIDDeviceRef)device {
109 IOHIDDeviceRegisterInputValueCallback(device, input_callback, (__bridge void *)self);
110 NJDevice *dev = [[NJDevice alloc] initWithDevice:device];
111 dev.index = findAvailableIndex(_devices, dev);
112 [_devices addObject:dev];
113 [outlineView reloadData];
114 connectDevicePrompt.hidden = !!_devices.count;
117 static void add_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
118 NJDeviceController *controller = (__bridge NJDeviceController *)ctx;
119 [controller addDeviceForDevice:device];
122 - (NJDevice *)findDeviceByRef:(IOHIDDeviceRef)device {
123 for (NJDevice *dev in _devices)
124 if (dev.device == device)
129 static void remove_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
130 NJDeviceController *controller = (__bridge NJDeviceController *)ctx;
131 [controller removeDeviceForDevice:device];
134 - (void)removeDeviceForDevice:(IOHIDDeviceRef)device {
135 NJDevice *match = [self findDeviceByRef:device];
136 IOHIDDeviceRegisterInputValueCallback(device, NULL, NULL);
138 [_devices removeObject:match];
139 [outlineView reloadData];
140 connectDevicePrompt.hidden = !!_devices.count;
142 if (_devices.count == 1)
143 [outlineView expandItem:_devices[0]];
146 - (void)updateContinuousOutputs:(NSTimer *)timer {
147 self.mouseLoc = [NSEvent mouseLocation];
148 for (NJOutput *output in [_continousOutputs copy]) {
149 if (![output update:self]) {
150 [_continousOutputs removeObject:output];
153 if (!_continousOutputs.count) {
154 [_continuousOutputsTick invalidate];
155 _continuousOutputsTick = nil;
159 #define NSSTR(e) ((NSString *)CFSTR(e))
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) }
170 IOHIDManagerSetDeviceMatchingMultiple(_hidManager, (__bridge CFArrayRef)criteria);
172 IOHIDManagerScheduleWithRunLoop(_hidManager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
173 IOReturn ret = IOHIDManagerOpen(_hidManager, kIOHIDOptionsTypeNone);
174 if (ret != kIOReturnSuccess) {
175 [[NSAlert alertWithMessageText:@"Input devices are unavailable"
179 informativeTextWithFormat:@"Error 0x%08x occured trying to access your devices. "
180 @"Input may not be correctly detected or mapped.",
182 beginSheetModalForWindow:outlineView.window
188 IOHIDManagerRegisterDeviceMatchingCallback(_hidManager, add_callback, (__bridge void *)self);
189 IOHIDManagerRegisterDeviceRemovalCallback(_hidManager, remove_callback, (__bridge void *)self);
192 - (NJInput *)selectedInput {
193 id <NJInputPathElement> item = [outlineView itemAtRow:outlineView.selectedRow];
194 return (!item.children && item.base) ? item : nil;
197 - (NSInteger)outlineView:(NSOutlineView *)outlineView
198 numberOfChildrenOfItem:(id <NJInputPathElement>)item {
199 return item ? item.children.count : _devices.count;
202 - (BOOL)outlineView:(NSOutlineView *)outlineView
203 isItemExpandable:(id <NJInputPathElement>)item {
204 return item ? [[item children] count] > 0: YES;
207 - (id)outlineView:(NSOutlineView *)outlineView
208 child:(NSInteger)index
209 ofItem:(id <NJInputPathElement>)item {
210 return item ? item.children[index] : _devices[index];
213 - (id)outlineView:(NSOutlineView *)outlineView
214 objectValueForTableColumn:(NSTableColumn *)tableColumn
215 byItem:(id <NJInputPathElement>)item {
216 return item ? item.name : @"root";
219 - (void)outlineViewSelectionDidChange:(NSNotification *)notification {
220 [outputController loadCurrent];
223 - (BOOL)outlineView:(NSOutlineView *)outlineView
224 isGroupItem:(id <NJInputPathElement>)item {
225 return [item isKindOfClass:NJDevice.class];
228 - (BOOL)outlineView:(NSOutlineView *)outlineView_
229 shouldSelectItem:(id <NJInputPathElement>)item {
230 return ![self outlineView:outlineView_ isGroupItem:item];
233 - (void)setTranslatingEvents:(BOOL)translatingEvents {
234 if (translatingEvents != _translatingEvents) {
235 _translatingEvents = translatingEvents;
236 NSInteger state = translatingEvents ? NSOnState : NSOffState;
237 translatingEventsButton.state = state;
238 translatingEventsMenu.title = translatingEvents ? @"Disable" : @"Enable";
239 NSString *name = translatingEvents
240 ? NJEventTranslationActivated
241 : NJEventTranslationDeactivated;
242 [NSNotificationCenter.defaultCenter postNotificationName:name
247 - (IBAction)translatingEventsChanged:(NSButton *)sender {
248 self.translatingEvents = sender.state == NSOnState;