X-Git-Url: https://git.yukkurigames.com/?p=enjoyable.git;a=blobdiff_plain;f=Classes%2FNJDeviceController.m;h=1b64aaf3f694e5dd26eb3c8324ebf0de77c82e04;hp=2a1546c974c8ce7a64b352fe5eec2ecdc8a35d17;hb=6cee2033d1c0fc0dacf444064305b9e7e87672a9;hpb=8fa589c4e6be7272402952c4f929f81763700212 diff --git a/Classes/NJDeviceController.m b/Classes/NJDeviceController.m index 2a1546c..1b64aaf 100644 --- a/Classes/NJDeviceController.m +++ b/Classes/NJDeviceController.m @@ -12,53 +12,49 @@ #import "NJDevice.h" #import "NJInput.h" #import "NJOutput.h" -#import "NJOutputController.h" #import "NJEvents.h" @implementation NJDeviceController { - IOHIDManagerRef _hidManager; + NJHIDManager *_hidManager; NSTimer *_continuousOutputsTick; NSMutableArray *_continousOutputs; NSMutableArray *_devices; - NSMutableArray *_expanded; } -#define EXPANDED_MEMORY_MAX_SIZE 100 +#define NSSTR(e) ((NSString *)CFSTR(e)) - (id)init { if ((self = [super init])) { _devices = [[NSMutableArray alloc] initWithCapacity:16]; _continousOutputs = [[NSMutableArray alloc] initWithCapacity:32]; - NSArray *expanded = [NSUserDefaults.standardUserDefaults objectForKey:@"expanded rows"]; - if (![expanded isKindOfClass:NSArray.class]) - expanded = @[]; - _expanded = [[NSMutableArray alloc] initWithCapacity:MAX(16, _expanded.count)]; - [_expanded addObjectsFromArray:expanded]; + _hidManager = [[NJHIDManager alloc] initWithCriteria:@[ + @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop), + NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_Joystick) }, + @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop), + NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_GamePad) }, + @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop), + NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_MultiAxisController) } + ] + delegate:self]; - [NSNotificationCenter.defaultCenter - addObserver:self - selector:@selector(applicationDidFinishLaunching:) - name:NSApplicationDidFinishLaunchingNotification - object:nil]; - // The HID manager uses 5-10ms per second doing basically // nothing if a noisy device is plugged in (the % of that // spent in input_callback is negligible, so it's not // something we can make faster). I don't really think that's - // acceptable, CPU/power wise. So if translation is disabled + // acceptable, CPU/power wise. So if simulation is disabled // and the window is closed, just switch off the HID manager // entirely. This probably also has some marginal benefits for // compatibility with other applications that want exclusive // grabs. [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(closeHidIfDisabled:) + selector:@selector(stopHidIfDisabled:) name:NSApplicationDidResignActiveNotification object:nil]; [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(openHid) + selector:@selector(startHid) name:NSApplicationDidBecomeActiveNotification object:nil]; } @@ -68,27 +64,14 @@ - (void)dealloc { [NSNotificationCenter.defaultCenter removeObserver:self]; [_continuousOutputsTick invalidate]; - [self closeHid]; } -- (void)expandRecursive:(id )pathElement { - if (pathElement) { - [self expandRecursive:pathElement.base]; - [outlineView expandItem:pathElement]; - } -} - -- (id)elementForUID:(NSString *)uid { - for (NJDevice *dev in _devices) { - id item = [dev elementForUID:uid]; - if (item) - return item; - } - return nil; +- (NJDevice *)objectAtIndexedSubscript:(NSUInteger)idx { + return idx < _devices.count ? _devices[idx] : nil; } -- (void)expandRecursiveByUID:(NSString *)uid { - [self expandRecursive:[self elementForUID:uid]]; +- (NSUInteger)count { + return _devices.count; } - (void)addRunningOutput:(NJOutput *)output { @@ -125,51 +108,39 @@ if (!handler) return; - [self expandRecursive:handler]; - [outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[outlineView rowForItem:handler]] - byExtendingSelection: NO]; - [outputController focusKey]; + [self.delegate deviceController:self didInput:handler]; } -static void input_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDValueRef value) { - NJDeviceController *controller = (__bridge NJDeviceController *)ctx; - IOHIDDeviceRef device = IOHIDQueueGetDevice(inSender); - - if (controller.translatingEvents) { - [controller runOutputForDevice:device value:value]; - } else if ([NSApplication sharedApplication].mainWindow.isVisible) { - [controller showOutputForDevice:device value:value]; +- (void)hidManager:(NJHIDManager *)manager + valueChanged:(IOHIDValueRef)value + fromDevice:(IOHIDDeviceRef)device { + if (self.simulatingEvents + && !NSApplication.sharedApplication.isActive) { + [self runOutputForDevice:device value:value]; + } else { + [self showOutputForDevice:device value:value]; } } -static int findAvailableIndex(NSArray *list, NJDevice *dev) { - for (int index = 1; ; index++) { - BOOL available = YES; - for (NJDevice *used in list) { - if ([used.productName isEqualToString:dev.productName] && used.index == index) { +- (void)addDevice:(NJDevice *)device { + BOOL available; + do { + available = YES; + for (NJDevice *used in _devices) { + if ([used isEqual:device]) { + device.index += 1; available = NO; - break; } } - if (available) - return index; - } -} - -- (void)addDeviceForDevice:(IOHIDDeviceRef)device { - IOHIDDeviceRegisterInputValueCallback(device, input_callback, (__bridge void *)self); - NJDevice *dev = [[NJDevice alloc] initWithDevice:device]; - dev.index = findAvailableIndex(_devices, dev); - [_devices addObject:dev]; - [outlineView reloadData]; - [self reexpandAll]; - hidSleepingPrompt.hidden = YES; - connectDevicePrompt.hidden = !!_devices.count; + } while (!available); + + [_devices addObject:device]; } -static void add_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) { - NJDeviceController *controller = (__bridge NJDeviceController *)ctx; - [controller addDeviceForDevice:device]; +- (void)hidManager:(NJHIDManager *)manager deviceAdded:(IOHIDDeviceRef)device { + NJDevice *match = [[NJDevice alloc] initWithDevice:device]; + [self addDevice:match]; + [self.delegate deviceController:self didAddDevice:match]; } - (NJDevice *)findDeviceByRef:(IOHIDDeviceRef)device { @@ -179,22 +150,13 @@ static void add_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDDevi return nil; } -static void remove_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDDeviceRef device) { - NJDeviceController *controller = (__bridge NJDeviceController *)ctx; - [controller removeDeviceForDevice:device]; -} - -- (void)removeDeviceForDevice:(IOHIDDeviceRef)device { +- (void)hidManager:(NJHIDManager *)manager deviceRemoved:(IOHIDDeviceRef)device { NJDevice *match = [self findDeviceByRef:device]; - IOHIDDeviceRegisterInputValueCallback(device, NULL, NULL); if (match) { - [_devices removeObject:match]; - [outlineView reloadData]; - connectDevicePrompt.hidden = !!_devices.count; - hidSleepingPrompt.hidden = YES; + NSInteger idx = [_devices indexOfObjectIdenticalTo:match]; + [_devices removeObjectAtIndex:idx]; + [self.delegate deviceController:self didRemoveDeviceAtIndex:idx]; } - if (_devices.count == 1) - [outlineView expandItem:_devices[0]]; } - (void)updateContinuousOutputs:(NSTimer *)timer { @@ -210,165 +172,56 @@ static void remove_callback(void *ctx, IOReturn inResult, void *inSender, IOHIDD } } -#define NSSTR(e) ((NSString *)CFSTR(e)) - -- (void)openHid { - if (_hidManager) - return; - NSLog(@"Opening HID manager."); - _hidManager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - IOHIDManagerScheduleWithRunLoop(_hidManager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - NSArray *criteria = @[ @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop), - NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_Joystick) }, - @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop), - NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_GamePad) }, - @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop), - NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_MultiAxisController) } - ]; - IOHIDManagerSetDeviceMatchingMultiple(_hidManager, (__bridge CFArrayRef)criteria); - IOReturn ret = IOHIDManagerOpen(_hidManager, kIOHIDOptionsTypeNone); - if (ret != kIOReturnSuccess) { - [[NSAlert alertWithMessageText:NSLocalizedString(@"input devices unavailable", - @"error title when devices can't be read") - defaultButton:nil - alternateButton:nil - otherButton:nil - informativeTextWithFormat:NSLocalizedString(@"input error 0x%08x occurred", - @"message containing IOReturn failure code when devices can't be read"), ret] - beginSheetModalForWindow:outlineView.window - modalDelegate:nil - didEndSelector:nil - contextInfo:nil]; - [self closeHid]; - } else { - IOHIDManagerRegisterDeviceMatchingCallback(_hidManager, add_callback, (__bridge void *)self); - IOHIDManagerRegisterDeviceRemovalCallback(_hidManager, remove_callback, (__bridge void *)self); - hidSleepingPrompt.hidden = YES; - connectDevicePrompt.hidden = !!_devices.count; - } +- (void)hidManager:(NJHIDManager *)manager didError:(NSError *)error { + [self.delegate deviceController:self didError:error]; + self.simulatingEvents = NO; } -- (void)closeHid { - if (_hidManager) { - NSLog(@"Closing HID manager."); - IOHIDManagerUnscheduleFromRunLoop(_hidManager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - IOHIDManagerClose(_hidManager, kIOHIDOptionsTypeNone); - CFRelease(_hidManager); - _hidManager = NULL; - } - [_devices removeAllObjects]; - [outlineView reloadData]; - hidSleepingPrompt.hidden = NO; - connectDevicePrompt.hidden = YES; +- (void)hidManagerDidStart:(NJHIDManager *)manager { + [self.delegate deviceControllerDidStartHID:self]; } -- (NJInput *)selectedInput { - id item = [outlineView itemAtRow:outlineView.selectedRow]; - return (!item.children && item.base) ? item : nil; -} - -- (NSInteger)outlineView:(NSOutlineView *)outlineView - numberOfChildrenOfItem:(id )item { - return item ? item.children.count : _devices.count; -} - -- (BOOL)outlineView:(NSOutlineView *)outlineView - isItemExpandable:(id )item { - return item ? [[item children] count] > 0: YES; -} - -- (id)outlineView:(NSOutlineView *)outlineView - child:(NSInteger)index - ofItem:(id )item { - return item ? item.children[index] : _devices[index]; -} - -- (id)outlineView:(NSOutlineView *)outlineView -objectValueForTableColumn:(NSTableColumn *)tableColumn - byItem:(id )item { - return item ? item.name : @"root"; -} - -- (void)outlineViewSelectionDidChange:(NSNotification *)notification { - id item = [outlineView itemAtRow:outlineView.selectedRow]; - if (item) - [NSUserDefaults.standardUserDefaults setObject:item.uid - forKey:@"selected input"]; - [outputController loadCurrent]; -} - -- (BOOL)outlineView:(NSOutlineView *)outlineView - isGroupItem:(id )item { - return [item isKindOfClass:NJDevice.class]; -} - -- (BOOL)outlineView:(NSOutlineView *)outlineView_ - shouldSelectItem:(id )item { - return ![self outlineView:outlineView_ isGroupItem:item]; +- (void)hidManagerDidStop:(NJHIDManager *)manager { + [_devices removeAllObjects]; + [self.delegate deviceControllerDidStopHID:self]; } -- (void)outlineViewItemDidExpand:(NSNotification *)notification { - id item = notification.userInfo[@"NSObject"]; - NSString *uid = item.uid; - if (![_expanded containsObject:uid]) - [_expanded addObject:uid]; - while (_expanded.count > EXPANDED_MEMORY_MAX_SIZE) - [_expanded removeObjectAtIndex:0]; - [NSUserDefaults.standardUserDefaults setObject:_expanded - forKey:@"expanded rows"]; +- (void)startHid { + [_hidManager start]; } -- (void)outlineViewItemDidCollapse:(NSNotification *)notification { - id item = notification.userInfo[@"NSObject"]; - [_expanded removeObject:item.uid]; - [NSUserDefaults.standardUserDefaults setObject:_expanded - forKey:@"expanded rows"]; +- (void)stopHid { + [_hidManager stop]; } -- (void)setTranslatingEvents:(BOOL)translatingEvents { - if (translatingEvents != _translatingEvents) { - _translatingEvents = translatingEvents; - NSInteger state = translatingEvents ? NSOnState : NSOffState; - translatingEventsButton.state = state; - NSString *name = translatingEvents - ? NJEventTranslationActivated - : NJEventTranslationDeactivated; +- (void)setSimulatingEvents:(BOOL)simulatingEvents { + if (simulatingEvents != _simulatingEvents) { + _simulatingEvents = simulatingEvents; + NSString *name = simulatingEvents + ? NJEventSimulationStarted + : NJEventSimulationStopped; [NSNotificationCenter.defaultCenter postNotificationName:name object:self]; - if (!translatingEvents && !NSApplication.sharedApplication.isActive) - [self closeHid]; - else if (translatingEvents || NSApplication.sharedApplication.isActive) - [self openHid]; + if (!simulatingEvents && !NSApplication.sharedApplication.isActive) + [self stopHid]; + else + [self startHid]; } } -- (void)reexpandAll { - for (NSString *uid in [_expanded copy]) - [self expandRecursiveByUID:uid]; - if (outlineView.selectedRow == -1) { - NSString *selectedUid = [NSUserDefaults.standardUserDefaults objectForKey:@"selected input"]; - id item = [self elementForUID:selectedUid]; - NSInteger row = [outlineView rowForItem:item]; - if (row >= 0) - [outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO]; - } -} - -- (void)closeHidIfDisabled:(NSNotification *)application { - if (!self.translatingEvents) - [self closeHid]; -} - -- (void)applicationDidFinishLaunching:(NSNotification *)application { - // NSApplicationWillBecomeActiveNotification occurs just slightly - // too late - there's one tick where the UI is showing "No - // devices" even with a device plugged in. - [self openHid]; +- (void)stopHidIfDisabled:(NSNotification *)application { + if (!self.simulatingEvents && !NSProcessInfo.processInfo.isBeingDebugged) + [self stopHid]; } -- (IBAction)translatingEventsChanged:(NSButton *)sender { - self.translatingEvents = sender.state == NSOnState; +- (NJInputPathElement *)objectForKeyedSubscript:(NSString *)uid { + for (NJDevice *dev in _devices) { + id item = [dev elementForUID:uid]; + if (item) + return item; + } + return nil; } @end