2 // EnjoyableApplicationDelegate.m
5 // Created by Sam McCall on 4/05/09.
8 #import "EnjoyableApplicationDelegate.h"
11 #import "NJMappingsController.h"
12 #import "NJDeviceController.h"
13 #import "NJOutputController.h"
16 @implementation EnjoyableApplicationDelegate {
17 NSInteger mappingsMenuIndex;
20 - (void)didSwitchApplication:(NSNotification *)notification {
21 NSRunningApplication *currentApp = notification.userInfo[NSWorkspaceApplicationKey];
22 [self.mappingsController activateMappingForProcess:currentApp.localizedName];
25 - (void)applicationDidFinishLaunching:(NSNotification *)notification {
26 [NSNotificationCenter.defaultCenter
28 selector:@selector(mappingDidChange:)
29 name:NJEventMappingChanged
31 [NSNotificationCenter.defaultCenter
33 selector:@selector(mappingListDidChange:)
34 name:NJEventMappingListChanged
36 [NSNotificationCenter.defaultCenter
38 selector:@selector(eventTranslationActivated:)
39 name:NJEventTranslationActivated
41 [NSNotificationCenter.defaultCenter
43 selector:@selector(eventTranslationDeactivated:)
44 name:NJEventTranslationDeactivated
47 while (![dockMenuBase itemAtIndex:mappingsMenuIndex++].tag);
49 self.outputController.enabled = NO;
50 [self.inputController setup];
51 [self.mappingsController load];
54 - (void)applicationWillTerminate:(NSNotification *)aNotification {
55 [NSUserDefaults.standardUserDefaults synchronize];
56 [NSNotificationCenter.defaultCenter removeObserver:self];
59 - (void)eventTranslationActivated:(NSNotification *)note {
60 [NSWorkspace.sharedWorkspace.notificationCenter
62 selector:@selector(didSwitchApplication:)
63 name:NSWorkspaceDidActivateApplicationNotification
65 NSLog(@"Listening for application changes.");
68 - (void)eventTranslationDeactivated:(NSNotification *)note {
69 [NSWorkspace.sharedWorkspace.notificationCenter
71 name:NSWorkspaceDidActivateApplicationNotification
73 NSLog(@"Ignoring application changes.");
76 - (void)mappingListDidChange:(NSNotification *)note {
77 NSArray *mappings = note.object;
78 NSInteger removeFrom = mappingsMenuIndex;
79 while (dockMenuBase.numberOfItems > removeFrom)
80 [dockMenuBase removeItemAtIndex:dockMenuBase.numberOfItems - 1];
82 for (NJMapping *mapping in mappings) {
83 NSString *keyEquiv = ++added < 10 ? @(added).stringValue : @"";
84 [dockMenuBase addItemWithTitle:mapping.name
85 action:@selector(chooseMapping:)
86 keyEquivalent:keyEquiv];
89 [_outputController refreshMappings];
92 - (void)mappingDidChange:(NSNotification *)note {
93 NJMapping *current = note.object;
94 NSArray *mappings = self.mappingsController.mappings;
95 for (NSUInteger i = 0; i < mappings.count; ++i)
96 [dockMenuBase itemAtIndex:i + mappingsMenuIndex].state = mappings[i] == current;
99 - (void)chooseMapping:(id)sender {
100 NSInteger idx = [dockMenuBase indexOfItem:sender] - mappingsMenuIndex;
101 NJMapping *chosen = self.mappingsController[idx];
102 [_mappingsController activateMapping:chosen];