Split NJMappingController view handling off into NJMappingViewController. This is...
[enjoyable.git] / Classes / EnjoyableApplicationDelegate.m
1 //
2 // EnjoyableApplicationDelegate.m
3 // Enjoy
4 //
5 // Created by Sam McCall on 4/05/09.
6 //
7
8 #import <Sparkle/Sparkle.h>
9
10 #import "EnjoyableApplicationDelegate.h"
11
12 #import "NJMapping.h"
13 #import "NJMappingsController.h"
14 #import "NJEvents.h"
15
16 @implementation EnjoyableApplicationDelegate {
17 NSStatusItem *statusItem;
18 }
19
20 - (void)didSwitchApplication:(NSNotification *)note {
21 NSRunningApplication *activeApp = note.userInfo[NSWorkspaceApplicationKey];
22 if (activeApp)
23 [self.mappingsController activateMappingForProcess:activeApp];
24 }
25
26 - (void)applicationWillFinishLaunching:(NSNotification *)notification {
27 [NSNotificationCenter.defaultCenter
28 addObserver:self
29 selector:@selector(mappingDidChange:)
30 name:NJEventMappingChanged
31 object:nil];
32 [NSNotificationCenter.defaultCenter
33 addObserver:self
34 selector:@selector(eventSimulationStarted:)
35 name:NJEventSimulationStarted
36 object:nil];
37 [NSNotificationCenter.defaultCenter
38 addObserver:self
39 selector:@selector(eventSimulationStopped:)
40 name:NJEventSimulationStopped
41 object:nil];
42
43 [self.mappingsController load];
44
45 statusItem = [NSStatusBar.systemStatusBar statusItemWithLength:36];
46 statusItem.image = [NSImage imageNamed:@"Status Menu Icon Disabled"];
47 statusItem.highlightMode = YES;
48 statusItem.menu = statusItemMenu;
49 statusItem.target = self;
50 }
51
52 - (void)applicationDidFinishLaunching:(NSNotification *)notification {
53 if ([NSUserDefaults.standardUserDefaults boolForKey:@"hidden in status item"]
54 && NSRunningApplication.currentApplication.wasLaunchedAsLoginItemOrResume)
55 [self transformIntoElement:nil];
56 else
57 [window makeKeyAndOrderFront:nil];
58 }
59
60 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication
61 hasVisibleWindows:(BOOL)flag {
62 [self restoreToForeground:theApplication];
63 return NO;
64 }
65
66 - (void)restoreToForeground:(id)sender {
67 ProcessSerialNumber psn = { 0, kCurrentProcess };
68 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
69 [NSApplication.sharedApplication activateIgnoringOtherApps:YES];
70 [window makeKeyAndOrderFront:sender];
71 [NSObject cancelPreviousPerformRequestsWithTarget:self
72 selector:@selector(transformIntoElement:)
73 object:self];
74 [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"hidden in status item"];
75 }
76
77 - (void)applicationWillBecomeActive:(NSNotification *)notification {
78 if (window.isVisible)
79 [self restoreToForeground:notification];
80 }
81
82 - (void)transformIntoElement:(id)sender {
83 ProcessSerialNumber psn = { 0, kCurrentProcess };
84 TransformProcessType(&psn, kProcessTransformToUIElementApplication);
85 [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"hidden in status item"];
86 }
87
88 - (void)flashStatusItem {
89 if ([statusItem.image.name isEqualToString:@"Status Menu Icon"]) {
90 statusItem.image = [NSImage imageNamed:@"Status Menu Icon Disabled"];
91 } else {
92 statusItem.image = [NSImage imageNamed:@"Status Menu Icon"];
93 }
94
95 }
96
97 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication {
98 [theApplication hide:theApplication];
99 // If we turn into a UIElement right away, the application cancels
100 // the deactivation events. The dock icon disappears, but an
101 // unresponsive menu bar remains until the user clicks somewhere.
102 // So delay just long enough to be past the end handling that.
103 [self performSelector:@selector(transformIntoElement:) withObject:self afterDelay:0.001];
104 return NO;
105 }
106
107 - (void)eventSimulationStarted:(NSNotification *)note {
108 statusItem.image = [NSImage imageNamed:@"Status Menu Icon"];
109 [NSWorkspace.sharedWorkspace.notificationCenter
110 addObserver:self
111 selector:@selector(didSwitchApplication:)
112 name:NSWorkspaceDidActivateApplicationNotification
113 object:nil];
114 }
115
116 - (void)eventSimulationStopped:(NSNotification *)note {
117 statusItem.image = [NSImage imageNamed:@"Status Menu Icon Disabled"];
118 [NSWorkspace.sharedWorkspace.notificationCenter
119 removeObserver:self
120 name:NSWorkspaceDidActivateApplicationNotification
121 object:nil];
122 }
123
124 - (void)mappingDidChange:(NSNotification *)note {
125 if (!window.isVisible)
126 for (int i = 0; i < 4; ++i)
127 [self performSelector:@selector(flashStatusItem)
128 withObject:self
129 afterDelay:0.2 * i];
130 }
131
132 - (NSMenu *)applicationDockMenu:(NSApplication *)sender {
133 return dockMenu;
134 }
135
136 - (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
137 [self restoreToForeground:sender];
138 NSError *error;
139 NSURL *URL = [NSURL fileURLWithPath:filename];
140 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:URL
141 mappings:self.mappingsController
142 error:&error];
143 if (mapping) {
144 [self.mappingsController addOrMergeMapping:mapping];
145 return YES;
146 } else {
147 [window presentError:error
148 modalForWindow:window
149 delegate:nil
150 didPresentSelector:nil
151 contextInfo:nil];
152 return NO;
153 }
154 }
155
156 - (void)mappingWasChosen:(NJMapping *)mapping {
157 [self.mappingsController activateMapping:mapping];
158 }
159
160 - (void)mappingListShouldOpen {
161 [self restoreToForeground:self];
162 [self.mappingsController.mvc mappingTriggerClicked:self];
163 }
164
165 - (void)loginItemPromptDidEnd:(NSWindow *)sheet
166 returnCode:(int)returnCode
167 contextInfo:(void *)contextInfo {
168 if (returnCode == NSAlertDefaultReturn) {
169 [NSRunningApplication.currentApplication addToLoginItems];
170 // If we're going to automatically start, don't bug the user
171 // about automatic updates next boot - they probably want it,
172 // and if they don't they probably want a prompt for it less.
173 SUUpdater.sharedUpdater.automaticallyChecksForUpdates = YES;
174 }
175 }
176
177 - (void)loginItemPromptDidDismiss:(NSWindow *)sheet
178 returnCode:(int)returnCode
179 contextInfo:(void *)contextInfo {
180 [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"explained login items"];
181 [window performClose:sheet];
182 }
183
184 - (BOOL)windowShouldClose:(NSWindow *)sender {
185 if (sender != window
186 || NSRunningApplication.currentApplication.isLoginItem
187 || [NSUserDefaults.standardUserDefaults boolForKey:@"explained login items"])
188 return YES;
189 NSBeginAlertSheet(
190 NSLocalizedString(@"login items prompt", @"alert prompt for adding to login items"),
191 NSLocalizedString(@"login items add button", @"button to add to login items"),
192 NSLocalizedString(@"login items don't add button", @"button to not add to login items"),
193 nil, window, self,
194 @selector(loginItemPromptDidEnd:returnCode:contextInfo:),
195 @selector(loginItemPromptDidDismiss:returnCode:contextInfo:),
196 NULL,
197 NSLocalizedString(@"login items explanation", @"a brief explanation of login items")
198 );
199 for (int i = 0; i < 10; ++i)
200 [self performSelector:@selector(flashStatusItem)
201 withObject:self
202 afterDelay:0.5 * i];
203 return NO;
204 }
205
206 - (void)importMappingClicked:(id)sender {
207 NSOpenPanel *panel = [NSOpenPanel openPanel];
208 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
209 [panel beginSheetModalForWindow:window
210 completionHandler:^(NSInteger result) {
211 if (result != NSFileHandlingPanelOKButton)
212 return;
213 [panel close];
214 NSError *error;
215 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:panel.URL
216 mappings:self.mappingsController
217 error:&error];
218 if (mapping) {
219 [self.mappingsController addOrMergeMapping:mapping];
220 } else {
221 [window presentError:error
222 modalForWindow:window
223 delegate:nil
224 didPresentSelector:nil
225 contextInfo:nil];
226 }
227 }];
228
229 }
230
231 - (void)exportMappingClicked:(id)sender {
232 NSSavePanel *panel = [NSSavePanel savePanel];
233 panel.allowedFileTypes = @[ @"enjoyable" ];
234 NJMapping *mapping = self.mappingsController.currentMapping;
235 panel.nameFieldStringValue = [mapping.name stringByFixingPathComponent];
236 [panel beginSheetModalForWindow:window
237 completionHandler:^(NSInteger result) {
238 if (result != NSFileHandlingPanelOKButton)
239 return;
240 [panel close];
241 NSError *error;
242 if (![mapping writeToURL:panel.URL error:&error]) {
243 [window presentError:error
244 modalForWindow:window
245 delegate:nil
246 didPresentSelector:nil
247 contextInfo:nil];
248 }
249 }];
250 }
251
252
253
254 @end