000df5f60a4f4d6be91dd8f1e391b02bc2423de7
[enjoyable.git] / Classes / NJDeviceController.m
1 //
2 // NJDeviceController.m
3 // Enjoy
4 //
5 // Created by Sam McCall on 4/05/09.
6 //
7
8 #import "NJDeviceController.h"
9
10 #import "NJMapping.h"
11 #import "NJMappingsController.h"
12 #import "NJDevice.h"
13 #import "NJInput.h"
14 #import "NJOutput.h"
15 #import "NJOutputController.h"
16 #import "NJEvents.h"
17 #import "NJDeviceViewController.h"
18
19 @implementation NJDeviceController {
20 NJHIDManager *_hidManager;
21 NSTimer *_continuousOutputsTick;
22 NSMutableArray *_continousOutputs;
23 NSMutableArray *_devices;
24 }
25
26 #define NSSTR(e) ((NSString *)CFSTR(e))
27
28 - (id)init {
29 if ((self = [super init])) {
30 _devices = [[NSMutableArray alloc] initWithCapacity:16];
31 _continousOutputs = [[NSMutableArray alloc] initWithCapacity:32];
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) }
40 ]
41 delegate:self];
42
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
51 // grabs.
52 [NSNotificationCenter.defaultCenter
53 addObserver:self
54 selector:@selector(stopHidIfDisabled:)
55 name:NSApplicationDidResignActiveNotification
56 object:nil];
57 [NSNotificationCenter.defaultCenter
58 addObserver:self
59 selector:@selector(startHid)
60 name:NSApplicationDidBecomeActiveNotification
61 object:nil];
62 }
63 return self;
64 }
65
66 - (void)dealloc {
67 [NSNotificationCenter.defaultCenter removeObserver:self];
68 [_continuousOutputsTick invalidate];
69 }
70
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
78 target:self
79 selector:@selector(updateContinuousOutputs:)
80 userInfo:nil
81 repeats:YES];
82 }
83 }
84
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];
96 }
97 }
98
99 - (void)showOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
100 NJDevice *dev = [self findDeviceByRef:device];
101 NJInput *handler = [dev handlerForEvent:value];
102 if (!handler)
103 return;
104
105 [devicesViewController expandAndSelectItem:handler];
106 [outputController focusKey];
107 }
108
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];
115 } else {
116 [self showOutputForDevice:device value:value];
117 }
118 }
119
120 - (void)hidManager:(NJHIDManager *)manager deviceAdded:(IOHIDDeviceRef)device {
121 NJDevice *match = [[NJDevice alloc] initWithDevice:device];
122 match.index = 1;
123 BOOL available;
124 do {
125 available = YES;
126 for (NJDevice *used in _devices) {
127 if ([used isEqual:match]) {
128 match.index += 1;
129 available = NO;
130 }
131 }
132 } while (!available);
133
134 [_devices addObject:match];
135 [devicesViewController addedDevice:match atIndex:_devices.count - 1];
136 }
137
138 - (NJDevice *)findDeviceByRef:(IOHIDDeviceRef)device {
139 for (NJDevice *dev in _devices)
140 if (dev.device == device)
141 return dev;
142 return nil;
143 }
144
145 - (void)hidManager:(NJHIDManager *)manager deviceRemoved:(IOHIDDeviceRef)device {
146 NJDevice *match = [self findDeviceByRef:device];
147 IOHIDDeviceRegisterInputValueCallback(device, NULL, NULL);
148 if (match) {
149 NSInteger idx = [_devices indexOfObjectIdenticalTo:match];
150 [_devices removeObjectAtIndex:idx];
151 [devicesViewController removedDevice:match atIndex:idx];
152 }
153 }
154
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];
160 }
161 }
162 if (!_continousOutputs.count) {
163 [_continuousOutputsTick invalidate];
164 _continuousOutputsTick = nil;
165 }
166 }
167
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
177 delegate:nil
178 didPresentSelector:nil
179 contextInfo:nil];
180 }
181 self.simulatingEvents = NO;
182 }
183
184 - (void)hidManagerDidStart:(NJHIDManager *)manager {
185 [devicesViewController hidStarted];
186 }
187
188 - (void)hidManagerDidStop:(NJHIDManager *)manager {
189 [_devices removeAllObjects];
190 [devicesViewController hidStopped];
191 }
192
193 - (void)startHid {
194 [_hidManager start];
195 }
196
197 - (void)stopHid {
198 [_hidManager stop];
199 }
200
201 - (NJInput *)selectedInput {
202 return (NJInput *)devicesViewController.selectedHandler;
203 }
204
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
214 object:self];
215
216 if (!simulatingEvents && !NSApplication.sharedApplication.isActive)
217 [self stopHid];
218 else
219 [self startHid];
220 }
221 }
222
223 - (void)stopHidIfDisabled:(NSNotification *)application {
224 if (!self.simulatingEvents && !NSProcessInfo.processInfo.isBeingDebugged)
225 [self stopHid];
226 }
227
228 - (IBAction)simulatingEventsChanged:(NSButton *)sender {
229 self.simulatingEvents = sender.state == NSOnState;
230 }
231
232 - (NSInteger)numberOfDevicesInDeviceList:(NJDeviceViewController *)dvc {
233 return _devices.count;
234 }
235
236 - (NJDevice *)deviceViewController:(NJDeviceViewController *)dvc
237 deviceForIndex:(NSUInteger)idx {
238 return _devices[idx];
239 }
240
241 - (id)deviceViewController:(NJDeviceViewController *)dvc
242 elementForUID:(NSString *)uid {
243 for (NJDevice *dev in _devices) {
244 id item = [dev elementForUID:uid];
245 if (item)
246 return item;
247 }
248 return nil;
249 }
250
251 - (void)deviceViewControllerDidSelectNothing:(NJDeviceViewController *)dvc {
252 [outputController loadCurrent];
253 }
254
255 - (void)deviceViewController:(NJDeviceViewController *)dvc
256 didSelectBranch:(NJInputPathElement *)handler {
257 [outputController loadCurrent];
258 }
259
260 - (void)deviceViewController:(NJDeviceViewController *)dvc
261 didSelectHandler:(NJInputPathElement *)handler {
262 [outputController loadCurrent];
263 }
264
265 - (void)deviceViewController:(NJDeviceViewController *)dvc
266 didSelectDevice:(NJInputPathElement *)device {
267 [outputController loadCurrent];
268 }
269
270 @end