6 #import "NJInputController.h"
14 @implementation NJInputController {
15 NJHIDManager *_hidManager;
16 NSTimer *_continuousOutputsTick;
17 NSMutableArray *_continousOutputs;
18 NSMutableArray *_devices;
19 NSMutableArray *_mappings;
20 NJMapping *_manualMapping;
24 #define NSSTR(e) ((NSString *)CFSTR(e))
27 if ((self = [super init])) {
28 _devices = [[NSMutableArray alloc] initWithCapacity:16];
29 _continousOutputs = [[NSMutableArray alloc] initWithCapacity:32];
31 _hidManager = [[NJHIDManager alloc] initWithCriteria:@[
32 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
33 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_Joystick) },
34 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
35 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_GamePad) },
36 @{ NSSTR(kIOHIDDeviceUsagePageKey) : @(kHIDPage_GenericDesktop),
37 NSSTR(kIOHIDDeviceUsageKey) : @(kHIDUsage_GD_MultiAxisController) }
41 _mappings = [[NSMutableArray alloc] init];
42 _currentMapping = [[NJMapping alloc] initWithName:
43 NSLocalizedString(@"(default)", @"default name for first the mapping")];
44 _manualMapping = _currentMapping;
45 [_mappings addObject:_currentMapping];
47 // The HID manager uses 5-10ms per second doing basically
48 // nothing if a noisy device is plugged in (the % of that
49 // spent in input_callback is negligible, so it's not
50 // something we can make faster). I don't really think that's
51 // acceptable, CPU/power wise. So if simulation is disabled
52 // and the window is closed, just switch off the HID manager
53 // entirely. This probably also has some marginal benefits for
54 // compatibility with other applications that want exclusive
56 [NSNotificationCenter.defaultCenter
58 selector:@selector(stopHidIfDisabled:)
59 name:NSApplicationDidResignActiveNotification
61 [NSNotificationCenter.defaultCenter
63 selector:@selector(startHid)
64 name:NSApplicationDidBecomeActiveNotification
71 [NSNotificationCenter.defaultCenter removeObserver:self];
72 [_continuousOutputsTick invalidate];
75 - (void)addRunningOutput:(NJOutput *)output {
76 // Axis events will trigger every small movement, don't keep
77 // re-adding them or they trigger multiple times each time.
78 if (![_continousOutputs containsObject:output])
79 [_continousOutputs addObject:output];
80 if (!_continuousOutputsTick) {
81 _continuousOutputsTick = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0
83 selector:@selector(updateContinuousOutputs:)
89 - (void)runOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
90 NJDevice *dev = [self findDeviceByRef:device];
91 NJInput *mainInput = [dev inputForEvent:value];
92 [mainInput notifyEvent:value];
93 NSArray *children = mainInput.children ? mainInput.children : mainInput ? @[mainInput] : @[];
94 for (NJInput *subInput in children) {
95 NJOutput *output = self.currentMapping[subInput];
96 output.magnitude = subInput.magnitude;
97 output.running = subInput.active;
98 if ((output.running || output.magnitude) && output.isContinuous)
99 [self addRunningOutput:output];
103 - (void)showOutputForDevice:(IOHIDDeviceRef)device value:(IOHIDValueRef)value {
104 NJDevice *dev = [self findDeviceByRef:device];
105 NJInput *handler = [dev handlerForEvent:value];
109 [self.delegate inputController:self didInput:handler];
112 - (void)hidManager:(NJHIDManager *)manager
113 valueChanged:(IOHIDValueRef)value
114 fromDevice:(IOHIDDeviceRef)device {
115 if (self.simulatingEvents
116 && !NSApplication.sharedApplication.isActive) {
117 [self runOutputForDevice:device value:value];
119 [self showOutputForDevice:device value:value];
123 - (void)addDevice:(NJDevice *)device {
127 for (NJDevice *used in _devices) {
128 if ([used isEqual:device]) {
133 } while (!available);
135 [_devices addObject:device];
138 - (void)hidManager:(NJHIDManager *)manager deviceAdded:(IOHIDDeviceRef)device {
139 NJDevice *match = [[NJDevice alloc] initWithDevice:device];
140 [self addDevice:match];
141 [self.delegate inputController:self didAddDevice:match];
144 - (NJDevice *)findDeviceByRef:(IOHIDDeviceRef)device {
145 for (NJDevice *dev in _devices)
146 if (dev.device == device)
151 - (void)hidManager:(NJHIDManager *)manager deviceRemoved:(IOHIDDeviceRef)device {
152 NJDevice *match = [self findDeviceByRef:device];
154 NSInteger idx = [_devices indexOfObjectIdenticalTo:match];
155 [_devices removeObjectAtIndex:idx];
156 [self.delegate inputController:self didRemoveDeviceAtIndex:idx];
160 - (void)updateContinuousOutputs:(NSTimer *)timer {
161 self.mouseLoc = [NSEvent mouseLocation];
162 for (NJOutput *output in [_continousOutputs copy]) {
163 if (![output update:self]) {
164 [_continousOutputs removeObject:output];
167 if (!_continousOutputs.count) {
168 [_continuousOutputsTick invalidate];
169 _continuousOutputsTick = nil;
173 - (void)hidManager:(NJHIDManager *)manager didError:(NSError *)error {
174 [self.delegate inputController:self didError:error];
175 self.simulatingEvents = NO;
178 - (void)hidManagerDidStart:(NJHIDManager *)manager {
179 [self.delegate inputControllerDidStartHID:self];
182 - (void)hidManagerDidStop:(NJHIDManager *)manager {
183 [_devices removeAllObjects];
184 [self.delegate inputControllerDidStopHID:self];
195 - (void)setSimulatingEvents:(BOOL)simulatingEvents {
196 if (simulatingEvents != _simulatingEvents) {
197 _simulatingEvents = simulatingEvents;
198 NSString *name = simulatingEvents
199 ? NJEventSimulationStarted
200 : NJEventSimulationStopped;
201 [NSNotificationCenter.defaultCenter postNotificationName:name
204 if (!simulatingEvents && !NSApplication.sharedApplication.isActive)
211 - (void)stopHidIfDisabled:(NSNotification *)application {
212 if (!self.simulatingEvents && !NSProcessInfo.processInfo.isBeingDebugged)
216 - (NJInputPathElement *)elementForUID:(NSString *)uid {
217 for (NJDevice *dev in _devices) {
218 id item = [dev elementForUID:uid];
225 - (NJMapping *)mappingForKey:(NSString *)name {
226 for (NJMapping *mapping in _mappings)
227 if ([name isEqualToString:mapping.name])
232 - (void)mappingsSet {
233 [self postLoadProcess];
234 [NSNotificationCenter.defaultCenter
235 postNotificationName:NJEventMappingListChanged
237 userInfo:@{ NJMappingListKey: _mappings,
238 NJMappingKey: _currentMapping }];
241 - (void)mappingsChanged {
246 - (void)activateMappingForProcess:(NSRunningApplication *)app {
247 NJMapping *oldMapping = _manualMapping;
248 NSArray *names = app.possibleMappingNames;
250 for (NSString *name in names) {
251 NJMapping *mapping = [self mappingForKey:name];
253 [self activateMapping:mapping];
260 [self activateMapping:oldMapping];
261 if ([oldMapping.name.lowercaseString isEqualToString:@"@application"]
262 || [oldMapping.name.lowercaseString isEqualToString:
263 NSLocalizedString(@"@Application", nil).lowercaseString]) {
264 oldMapping.name = app.bestMappingName;
265 [self mappingsChanged];
268 _manualMapping = oldMapping;
271 - (void)activateMappingForcibly:(NJMapping *)mapping {
272 NSLog(@"Switching to mapping %@.", mapping.name);
273 _currentMapping = mapping;
274 NSUInteger idx = [self indexOfMapping:_currentMapping];
275 [NSNotificationCenter.defaultCenter
276 postNotificationName:NJEventMappingChanged
278 userInfo:@{ NJMappingKey : _currentMapping,
279 NJMappingIndexKey: @(idx) }];
282 - (void)activateMapping:(NJMapping *)mapping {
284 mapping = _manualMapping;
285 if (mapping == _currentMapping)
287 _manualMapping = mapping;
288 [self activateMappingForcibly:mapping];
292 NSLog(@"Saving mappings to defaults.");
293 NSMutableArray *ary = [[NSMutableArray alloc] initWithCapacity:_mappings.count];
294 for (NJMapping *mapping in _mappings)
295 [ary addObject:[mapping serialize]];
296 [NSUserDefaults.standardUserDefaults setObject:ary forKey:@"mappings"];
299 - (void)postLoadProcess {
300 for (NJMapping *mapping in self.mappings)
301 [mapping postLoadProcess:self.mappings];
305 NSUInteger selected = [NSUserDefaults.standardUserDefaults integerForKey:@"selected"];
306 NSArray *storedMappings = [NSUserDefaults.standardUserDefaults arrayForKey:@"mappings"];
307 NSMutableArray* newMappings = [[NSMutableArray alloc] initWithCapacity:storedMappings.count];
309 for (NSDictionary *serialization in storedMappings)
310 [newMappings addObject:
311 [[NJMapping alloc] initWithSerialization:serialization]];
313 if (newMappings.count) {
314 _mappings = newMappings;
315 if (selected >= newMappings.count)
317 [self activateMapping:_mappings[selected]];
322 - (NSInteger)indexOfMapping:(NJMapping *)mapping {
323 return [_mappings indexOfObjectIdenticalTo:mapping];
326 - (void)mergeMapping:(NJMapping *)mapping intoMapping:(NJMapping *)existing {
327 [existing mergeEntriesFrom:mapping];
328 [self mappingsChanged];
329 if (existing == _currentMapping)
330 [self activateMappingForcibly:mapping];
333 - (void)renameMapping:(NJMapping *)mapping to:(NSString *)name {
335 [self mappingsChanged];
336 if (mapping == _currentMapping)
337 [self activateMappingForcibly:mapping];
340 - (void)addMapping:(NJMapping *)mapping {
341 [self insertMapping:mapping atIndex:_mappings.count];
344 - (void)insertMapping:(NJMapping *)mapping atIndex:(NSInteger)idx {
345 [_mappings insertObject:mapping atIndex:idx];
346 [self mappingsChanged];
349 - (void)removeMappingAtIndex:(NSInteger)idx {
350 NSInteger currentIdx = [self indexOfMapping:_currentMapping];
351 [_mappings removeObjectAtIndex:idx];
352 [self activateMapping:self.mappings[MIN(currentIdx, _mappings.count - 1)]];
353 [self mappingsChanged];
356 - (void)moveMoveMappingFromIndex:(NSInteger)fromIdx toIndex:(NSInteger)toIdx {
357 [_mappings moveObjectAtIndex:fromIdx toIndex:toIdx];
358 [self mappingsChanged];