Fix a variety of issues with incorrect / unexpected / unfriendly first responder...
[enjoyable.git] / ApplicationController.m
1 //
2 // ApplicationController.m
3 // Enjoy
4 //
5 // Created by Sam McCall on 4/05/09.
6 //
7
8 #import "ApplicationController.h"
9
10 #import "Config.h"
11 #import "ConfigsController.h"
12 #import "JoystickController.h"
13 #import "TargetController.h"
14
15 @implementation ApplicationController {
16 BOOL active;
17 }
18
19 - (void)didSwitchApplication:(NSNotification *)notification {
20 NSRunningApplication *currentApp = notification.userInfo[NSWorkspaceApplicationKey];
21 [self.configsController activateConfigForProcess:currentApp.localizedName];
22 }
23
24 - (void)applicationDidFinishLaunching:(NSNotification *)notification {
25 [drawer open];
26 self.targetController.enabled = NO;
27 [self.jsController setup];
28 [self.configsController load];
29 [[NSWorkspace sharedWorkspace].notificationCenter
30 addObserver:self
31 selector:@selector(didSwitchApplication:)
32 name:NSWorkspaceDidActivateApplicationNotification
33 object:nil];
34 }
35
36 - (void)applicationWillTerminate:(NSNotification *)aNotification {
37 [[NSUserDefaults standardUserDefaults] synchronize];
38 [[NSWorkspace sharedWorkspace].notificationCenter
39 removeObserver:self
40 name:NSWorkspaceDidActivateApplicationNotification
41 object:nil];
42 }
43
44 - (IBAction)toggleActivity:(id)sender {
45 BOOL sendRealEvents = !self.jsController.sendingRealEvents;
46 self.jsController.sendingRealEvents = sendRealEvents;
47 activeButton.label = sendRealEvents ? @"Stop" : @"Start";
48 activeButton.image = [NSImage imageNamed:sendRealEvents ? @"NSStopProgressFreestandingTemplate" : @"NSGoRightTemplate"];
49 activeMenuItem.state = sendRealEvents;
50 }
51
52 - (NSUInteger)firstConfigMenuIndex {
53 NSUInteger count = dockMenuBase.numberOfItems;
54 for (int i = 0; i < count; ++i)
55 if ([dockMenuBase itemAtIndex:i].isSeparatorItem)
56 return i + 1;
57 return count;
58 }
59
60 - (void)configsChanged {
61 NSUInteger removeFrom = [self firstConfigMenuIndex];
62 while (dockMenuBase.numberOfItems > removeFrom)
63 [dockMenuBase removeItemAtIndex:dockMenuBase.numberOfItems - 1];
64 for (Config *config in self.configsController.configs)
65 [dockMenuBase addItemWithTitle:config.name action:@selector(chooseConfig:) keyEquivalent:@""];
66 [_targetController refreshConfigs];
67 [self configChanged];
68 }
69
70 - (void)configChanged {
71 NSUInteger firstConfig = [self firstConfigMenuIndex];
72 Config *current = self.configsController.currentConfig;
73 NSArray *configs = self.configsController.configs;
74 for (int i = 0; i < configs.count; ++i)
75 [dockMenuBase itemAtIndex:i + firstConfig].state = configs[i] == current;
76 }
77
78 - (void)chooseConfig:(id)sender {
79 int idx = [dockMenuBase indexOfItem:sender] - [self firstConfigMenuIndex];
80 Config *chosen = self.configsController.configs[idx];
81 [_configsController activateConfig:chosen];
82 }
83 @end