Remove Sparkle, code signing failed me for the last time.
[enjoyable.git] / Classes / NJInputController.m
1 //
2 // NJInputController.m
3 // Enjoyable
4 //
5
6 #import "NJInputController.h"
7
8 #import "NJMapping.h"
9 #import "NJDevice.h"
10 #import "NJInput.h"
11 #import "NJOutput.h"
12 #import "NJEvents.h"
13
14 #import <CoreVideo/CoreVideo.h>
15
16 @interface NJInputController ()
17
18 - (void)updateContinuousOutputs;
19
20 @end
21
22 static CVReturn _updateDL(CVDisplayLinkRef displayLink,
23 const CVTimeStamp *inNow,
24 const CVTimeStamp *inOutputTime,
25 CVOptionFlags flagsIn,
26 CVOptionFlags *flagsOut,
27 void *ctxManager) {
28 NJInputController *manager = (__bridge NJInputController *)ctxManager;
29 [manager performSelectorOnMainThread:@selector(updateContinuousOutputs)
30 withObject:nil
31 waitUntilDone:NO];
32 return kCVReturnSuccess;
33 }
34
35 @implementation NJInputController {
36 NJHIDManager *_HIDManager;
37 NSMutableArray *_continousOutputs;
38 NSMutableArray *_devices;
39 NSMutableArray *_mappings;
40 NJMapping *_manualMapping;
41 CVDisplayLinkRef _displayLink;
42 }
43
44 #define NSSTR(e) ((NSString *)CFSTR(e))
45
46 - (id)init {
47 if ((self = [super init])) {
48 _devices = [[NSMutableArray alloc] initWithCapacity:16];
49 _continousOutputs = [[NSMutableArray alloc] initWithCapacity:32];
50
51 CVReturn cvErr = CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink);
52 if (cvErr) {
53 NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
54 code:cvErr
55 userInfo:nil];
56 [self.delegate inputController:self didError:error];
57 NSLog(@"DisplayLink failed creation with error: %@", error);
58 _displayLink = NULL;
59 }
60 CVDisplayLinkSetOutputCallback(_displayLink, _updateDL, (__bridge void *)self);
61
62 _HIDManager = [[NJHIDManager alloc] initWithCriteria:@[
63 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
64 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_Joystick) },
65 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
66 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_GamePad) },
67 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
68 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_MultiAxisController) }
69 ]
70 delegate:self];
71
72 _mappings = [[NSMutableArray alloc] init];
73 _currentMapping = [[NJMapping alloc] initWithName:
74 NSLocalizedString(@"(default)", @"default name for first the mapping")];
75 _manualMapping = _currentMapping;
76 [_mappings addObject:_currentMapping];
77
78 // The HID manager uses 5-10ms per second doing basically
79 // nothing if a noisy device is plugged in (the % of that
80 // spent in input_callback is negligible, so it's not
81 // something we can make faster). I don't really think that's
82 // acceptable, CPU/power wise. So if simulation is disabled
83 // and the window is closed, just switch off the HID manager
84 // entirely. This probably also has some marginal benefits for
85 // compatibility with other applications that want exclusive
86 // grabs.
87 [NSNotificationCenter.defaultCenter
88 addObserver:self
89 selector:@selector(stopHidIfDisabled:)
90 name:NSApplicationDidResignActiveNotification
91 object:nil];
92 [NSNotificationCenter.defaultCenter
93 addObserver:self
94 selector:@selector(startHid)
95 name:NSApplicationDidBecomeActiveNotification
96 object:nil];
97 }
98 return self;
99 }
100
101 - (void)dealloc {
102 [NSNotificationCenter.defaultCenter removeObserver:self];
103 if (_displayLink) {
104 CVDisplayLinkStop(_displayLink);
105 CVDisplayLinkRelease(_displayLink);
106 }
107 }
108
109 - (void)addRunningOutput:(NJOutput *)output {
110 // Axis events will trigger every small movement, don't keep
111 // re-adding them or they trigger multiple times each time.
112 if (![_continousOutputs containsObject:output])
113 [_continousOutputs addObject:output];
114 if (_displayLink && !CVDisplayLinkIsRunning(_displayLink))
115 CVDisplayLinkStart(_displayLink);
116 }
117
118 - (void)runOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
119 NJDevice *dev = [self findDeviceByRef:device];
120 NJInput *mainInput = [dev inputForEvent:value];
121 [mainInput notifyEvent:value];
122 NSArray *children = mainInput.children ? mainInput.children : mainInput ? @[mainInput] : @[];
123 for (NJInput *subInput in children) {
124 NJOutput *output = self.currentMapping[subInput];
125 output.magnitude = subInput.magnitude;
126 output.running = subInput.active;
127 if ((output.running || output.magnitude) && output.isContinuous)
128 [self addRunningOutput:output];
129 }
130 }
131
132 - (void)showOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
133 NJDevice *dev = [self findDeviceByRef:device];
134 NJInput *handler = [dev handlerForEvent:value];
135 if (!handler)
136 return;
137
138 [self.delegate inputController:self didInput:handler];
139 }
140
141 - (void)HIDManager:(NJHIDManager *)manager
142 valueChanged:(IOHIDValueRef)value
143 fromDevice:(IOHIDDeviceRef)device {
144 if (self.simulatingEvents
145 && !NSApplication.sharedApplication.isActive) {
146 [self runOutputForDevice:device value:value];
147 } else {
148 [self showOutputForDevice:device value:value];
149 }
150 }
151
152 - (void)addDevice:(NJDevice *)device {
153 BOOL available;
154 do {
155 available = YES;
156 for (NJDevice *used in _devices) {
157 if ([used isEqual:device]) {
158 device.index += 1;
159 available = NO;
160 }
161 }
162 } while (!available);
163
164 [_devices addObject:device];
165 }
166
167 - (void)HIDManager:(NJHIDManager *)manager deviceAdded:(IOHIDDeviceRef)device {
168 NJDevice *match = [[NJDevice alloc] initWithDevice:device];
169 [self addDevice:match];
170 [self.delegate inputController:self didAddDevice:match];
171 }
172
173 - (NJDevice *)findDeviceByRef:(IOHIDDeviceRef)device {
174 for (NJDevice *dev in _devices)
175 if (dev.device == device)
176 return dev;
177 return nil;
178 }
179
180 - (void)HIDManager:(NJHIDManager *)manager deviceRemoved:(IOHIDDeviceRef)device {
181 NJDevice *match = [self findDeviceByRef:device];
182 if (match) {
183 NSInteger idx = [_devices indexOfObjectIdenticalTo:match];
184 [_devices removeObjectAtIndex:idx];
185 [self.delegate inputController:self didRemoveDeviceAtIndex:idx];
186 }
187 }
188
189 - (void)updateContinuousOutputs {
190 self.mouseLoc = [NSEvent mouseLocation];
191 for (NJOutput *output in [_continousOutputs copy]) {
192 if (![output update:self]) {
193 [_continousOutputs removeObject:output];
194 }
195 }
196 if (!_continousOutputs.count && _displayLink) {
197 CVDisplayLinkStop(_displayLink);
198 }
199 }
200
201 - (void)HIDManager:(NJHIDManager *)manager didError:(NSError *)error {
202 [self.delegate inputController:self didError:error];
203 self.simulatingEvents = NO;
204 if (_displayLink)
205 CVDisplayLinkStop(_displayLink);
206 }
207
208 - (void)HIDManagerDidStart:(NJHIDManager *)manager {
209 [self.delegate inputControllerDidStartHID:self];
210 }
211
212 - (void)HIDManagerDidStop:(NJHIDManager *)manager {
213 [_devices removeAllObjects];
214 if (_displayLink)
215 CVDisplayLinkStop(_displayLink);
216 [self.delegate inputControllerDidStopHID:self];
217 }
218
219 - (void)startHid {
220 [_HIDManager start];
221 }
222
223 - (void)stopHid {
224 [_HIDManager stop];
225 }
226
227 - (void)setSimulatingEvents:(BOOL)simulatingEvents {
228 if (simulatingEvents != _simulatingEvents) {
229 _simulatingEvents = simulatingEvents;
230 NSString *name = simulatingEvents
231 ? NJEventSimulationStarted
232 : NJEventSimulationStopped;
233 [NSNotificationCenter.defaultCenter postNotificationName:name
234 object:self];
235
236 if (!simulatingEvents && !NSApplication.sharedApplication.isActive)
237 [self stopHid];
238 else
239 [self startHid];
240 }
241 }
242
243 - (void)stopHidIfDisabled:(NSNotification *)application {
244 if (!self.simulatingEvents && !NSProcessInfo.processInfo.isBeingDebugged)
245 [self stopHid];
246 }
247
248 - (NJInputPathElement *)elementForUID:(NSString *)uid {
249 for (NJDevice *dev in _devices) {
250 id item = [dev elementForUID:uid];
251 if (item)
252 return item;
253 }
254 return nil;
255 }
256
257 - (NJMapping *)mappingForKey:(NSString *)name {
258 for (NJMapping *mapping in _mappings)
259 if ([name isEqualToString:mapping.name])
260 return mapping;
261 return nil;
262 }
263
264 - (void)mappingsSet {
265 [self postLoadProcess];
266 [NSNotificationCenter.defaultCenter
267 postNotificationName:NJEventMappingListChanged
268 object:self
269 userInfo:@{ NJMappingListKey: _mappings,
270 NJMappingKey: _currentMapping }];
271 }
272
273 - (void)mappingsChanged {
274 [self save];
275 [self mappingsSet];
276 }
277
278 - (void)activateMappingForProcess:(NSRunningApplication *)app {
279 NJMapping *oldMapping = _manualMapping;
280 NSArray *names = app.possibleMappingNames;
281 BOOL found = NO;
282 for (NSString *name in names) {
283 NJMapping *mapping = [self mappingForKey:name];
284 if (mapping) {
285 [self activateMapping:mapping];
286 found = YES;
287 break;
288 }
289 }
290
291 if (!found) {
292 [self activateMapping:oldMapping];
293 if ([oldMapping.name.lowercaseString isEqualToString:@"@application"]
294 || [oldMapping.name.lowercaseString isEqualToString:
295 NSLocalizedString(@"@Application", nil).lowercaseString]) {
296 [self renameMapping:oldMapping to:app.bestMappingName];
297 }
298 }
299 _manualMapping = oldMapping;
300 }
301
302 - (void)activateMappingForcibly:(NJMapping *)mapping {
303 NSLog(@"Switching to mapping %@.", mapping.name);
304 _currentMapping = mapping;
305 NSUInteger idx = [self indexOfMapping:_currentMapping];
306 [NSNotificationCenter.defaultCenter
307 postNotificationName:NJEventMappingChanged
308 object:self
309 userInfo:@{ NJMappingKey : _currentMapping,
310 NJMappingIndexKey: @(idx) }];
311 }
312
313 - (void)activateMapping:(NJMapping *)mapping {
314 if (!mapping)
315 mapping = _manualMapping;
316 if (mapping == _currentMapping)
317 return;
318 _manualMapping = mapping;
319 [self activateMappingForcibly:mapping];
320 }
321
322 - (void)save {
323 NSLog(@"Saving mappings to defaults.");
324 NSMutableArray *ary = [[NSMutableArray alloc] initWithCapacity:_mappings.count];
325 for (NJMapping *mapping in _mappings)
326 [ary addObject:[mapping serialize]];
327 [NSUserDefaults.standardUserDefaults setObject:ary forKey:@"mappings"];
328 }
329
330 - (void)postLoadProcess {
331 for (NJMapping *mapping in self.mappings)
332 [mapping postLoadProcess:self.mappings];
333 }
334
335 - (void)load {
336 NSUInteger selected = [NSUserDefaults.standardUserDefaults integerForKey:@"selected"];
337 NSArray *storedMappings = [NSUserDefaults.standardUserDefaults arrayForKey:@"mappings"];
338 NSMutableArray* newMappings = [[NSMutableArray alloc] initWithCapacity:storedMappings.count];
339
340 for (NSDictionary *serialization in storedMappings)
341 [newMappings addObject:
342 [[NJMapping alloc] initWithSerialization:serialization]];
343
344 if (newMappings.count) {
345 _mappings = newMappings;
346 if (selected >= newMappings.count)
347 selected = 0;
348 [self activateMapping:_mappings[selected]];
349 [self mappingsSet];
350 }
351 }
352
353 - (NSInteger)indexOfMapping:(NJMapping *)mapping {
354 return [_mappings indexOfObjectIdenticalTo:mapping];
355 }
356
357 - (void)mergeMapping:(NJMapping *)mapping intoMapping:(NJMapping *)existing {
358 [existing mergeEntriesFrom:mapping];
359 [self mappingsChanged];
360 if (existing == _currentMapping)
361 [self activateMappingForcibly:mapping];
362 }
363
364 - (void)renameMapping:(NJMapping *)mapping to:(NSString *)name {
365 mapping.name = name;
366 [self mappingsChanged];
367 if (mapping == _currentMapping)
368 [self activateMappingForcibly:mapping];
369 }
370
371 - (void)addMapping:(NJMapping *)mapping {
372 [self insertMapping:mapping atIndex:_mappings.count];
373 }
374
375 - (void)insertMapping:(NJMapping *)mapping atIndex:(NSInteger)idx {
376 [_mappings insertObject:mapping atIndex:idx];
377 [self mappingsChanged];
378 }
379
380 - (void)removeMappingAtIndex:(NSInteger)idx {
381 NSInteger currentIdx = [self indexOfMapping:_currentMapping];
382 [_mappings removeObjectAtIndex:idx];
383 NSInteger activeIdx = MIN(currentIdx, (NSInteger)_mappings.count - 1);
384 [self activateMapping:self.mappings[activeIdx]];
385 [self mappingsChanged];
386 }
387
388 - (void)moveMoveMappingFromIndex:(NSInteger)fromIdx toIndex:(NSInteger)toIdx {
389 [_mappings moveObjectAtIndex:fromIdx toIndex:toIdx];
390 [self mappingsChanged];
391 }
392
393 @end