2 // NJDeviceController.m
5 // Created by Sam McCall on 4/05/09.
8 #import "NJDeviceController.h"
11 #import "NJMappingsController.h"
15 #import "NJOutputController.h"
17 #import "NJDeviceViewController.h"
19 @implementation NJDeviceController {
20 NJHIDManager *_hidManager;
21 NSTimer *_continuousOutputsTick;
22 NSMutableArray *_continousOutputs;
23 NSMutableArray *_devices;
26 #define NSSTR(e) ((NSString *)CFSTR(e))
29 if ((self = [super init])) {
30 _devices = [[NSMutableArray alloc] initWithCapacity:16];
31 _continousOutputs = [[NSMutableArray alloc] initWithCapacity:32];
33 _hidManager = [[NJHIDManager alloc] initWithCriteria:@[
34 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
35 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_Joystick) },
36 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
37 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_GamePad) },
38 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
39 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_MultiAxisController) }
43 // The HID manager uses 5-10ms per second doing basically
44 // nothing if a noisy device is plugged in (the % of that
45 // spent in input_callback is negligible, so it's not
46 // something we can make faster). I don't really think that's
47 // acceptable, CPU/power wise. So if simulation is disabled
48 // and the window is closed, just switch off the HID manager
49 // entirely. This probably also has some marginal benefits for
50 // compatibility with other applications that want exclusive
52 [NSNotificationCenter.defaultCenter
54 selector:@selector(stopHidIfDisabled:)
55 name:NSApplicationDidResignActiveNotification
57 [NSNotificationCenter.defaultCenter
59 selector:@selector(startHid)
60 name:NSApplicationDidBecomeActiveNotification
67 [NSNotificationCenter.defaultCenter removeObserver:self];
68 [_continuousOutputsTick invalidate];
71 - (void)addRunningOutput:(NJOutput *)output {
72 // Axis events will trigger every small movement, don't keep
73 // re-adding them or they trigger multiple times each time.
74 if (![_continousOutputs containsObject:output])
75 [_continousOutputs addObject:output];
76 if (!_continuousOutputsTick) {
77 _continuousOutputsTick = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0
79 selector:@selector(updateContinuousOutputs:)
85 - (void)runOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
86 NJDevice *dev = [self findDeviceByRef:device];
87 NJInput *mainInput = [dev inputForEvent:value];
88 [mainInput notifyEvent:value];
89 NSArray *children = mainInput.children ? mainInput.children : mainInput ? @[mainInput] : @[];
90 for (NJInput *subInput in children) {
91 NJOutput *output = mappingsController.currentMapping[subInput];
92 output.magnitude = subInput.magnitude;
93 output.running = subInput.active;
94 if ((output.running || output.magnitude) && output.isContinuous)
95 [self addRunningOutput:output];
99 - (void)showOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
100 NJDevice *dev = [self findDeviceByRef:device];
101 NJInput *handler = [dev handlerForEvent:value];
105 [devicesViewController expandAndSelectItem:handler];
106 [outputController focusKey];
109 - (void)hidManager:(NJHIDManager *)manager
110 valueChanged:(IOHIDValueRef)value
111 fromDevice:(IOHIDDeviceRef)device {
112 if (self.simulatingEvents
113 && !NSApplication.sharedApplication.isActive) {
114 [self runOutputForDevice:device value:value];
116 [self showOutputForDevice:device value:value];
120 - (void)hidManager:(NJHIDManager *)manager deviceAdded:(IOHIDDeviceRef)device {
121 NJDevice *match = [[NJDevice alloc] initWithDevice:device];
126 for (NJDevice *used in _devices) {
127 if ([used isEqual:match]) {
132 } while (!available);
134 [_devices addObject:match];
135 [devicesViewController addedDevice:match atIndex:_devices.count - 1];
138 - (NJDevice *)findDeviceByRef:(IOHIDDeviceRef)device {
139 for (NJDevice *dev in _devices)
140 if (dev.device == device)
145 - (void)hidManager:(NJHIDManager *)manager deviceRemoved:(IOHIDDeviceRef)device {
146 NJDevice *match = [self findDeviceByRef:device];
147 IOHIDDeviceRegisterInputValueCallback(device, NULL, NULL);
149 NSInteger idx = [_devices indexOfObjectIdenticalTo:match];
150 [_devices removeObjectAtIndex:idx];
151 [devicesViewController removedDevice:match atIndex:idx];
155 - (void)updateContinuousOutputs:(NSTimer *)timer {
156 self.mouseLoc = [NSEvent mouseLocation];
157 for (NJOutput *output in [_continousOutputs copy]) {
158 if (![output update:self]) {
159 [_continousOutputs removeObject:output];
162 if (!_continousOutputs.count) {
163 [_continuousOutputsTick invalidate];
164 _continuousOutputsTick = nil;
168 - (void)hidManager:(NJHIDManager *)manager didError:(NSError *)error {
169 // Since the error shows the window, it can trigger another attempt
170 // to re-open the HID manager, which will also probably fail and error,
171 // so don't bother repeating ourselves.
172 if (!simulatingEventsButton.window.attachedSheet) {
173 [NSApplication.sharedApplication activateIgnoringOtherApps:YES];
174 [simulatingEventsButton.window makeKeyAndOrderFront:nil];
175 [simulatingEventsButton.window presentError:error
176 modalForWindow:simulatingEventsButton.window
178 didPresentSelector:nil
181 self.simulatingEvents = NO;
184 - (void)hidManagerDidStart:(NJHIDManager *)manager {
185 [devicesViewController hidStarted];
188 - (void)hidManagerDidStop:(NJHIDManager *)manager {
189 [_devices removeAllObjects];
190 [devicesViewController hidStopped];
201 - (NJInput *)selectedInput {
202 return (NJInput *)devicesViewController.selectedHandler;
205 - (void)setSimulatingEvents:(BOOL)simulatingEvents {
206 if (simulatingEvents != _simulatingEvents) {
207 _simulatingEvents = simulatingEvents;
208 NSInteger state = simulatingEvents ? NSOnState : NSOffState;
209 simulatingEventsButton.state = state;
210 NSString *name = simulatingEvents
211 ? NJEventSimulationStarted
212 : NJEventSimulationStopped;
213 [NSNotificationCenter.defaultCenter postNotificationName:name
216 if (!simulatingEvents && !NSApplication.sharedApplication.isActive)
223 - (void)stopHidIfDisabled:(NSNotification *)application {
224 if (!self.simulatingEvents && !NSProcessInfo.processInfo.isBeingDebugged)
228 - (IBAction)simulatingEventsChanged:(NSButton *)sender {
229 self.simulatingEvents = sender.state == NSOnState;
232 - (NSInteger)numberOfDevicesInDeviceList:(NJDeviceViewController *)dvc {
233 return _devices.count;
236 - (NJDevice *)deviceViewController:(NJDeviceViewController *)dvc
237 deviceForIndex:(NSUInteger)idx {
238 return _devices[idx];
241 - (id)deviceViewController:(NJDeviceViewController *)dvc
242 elementForUID:(NSString *)uid {
243 for (NJDevice *dev in _devices) {
244 id item = [dev elementForUID:uid];
251 - (void)deviceViewControllerDidSelectNothing:(NJDeviceViewController *)dvc {
252 [outputController loadCurrent];
255 - (void)deviceViewController:(NJDeviceViewController *)dvc
256 didSelectBranch:(NJInputPathElement *)handler {
257 [outputController loadCurrent];
260 - (void)deviceViewController:(NJDeviceViewController *)dvc
261 didSelectHandler:(NJInputPathElement *)handler {
262 [outputController loadCurrent];
265 - (void)deviceViewController:(NJDeviceViewController *)dvc
266 didSelectDevice:(NJInputPathElement *)device {
267 [outputController loadCurrent];