View-free NJMappingsController.
[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 [self.mvc.mappingList reloadData];
45 [self.mvc changedActiveMappingToIndex:
46 [self.mappingsController indexOfMapping:
47 self.mappingsController.currentMapping]];
48
49 statusItem = [NSStatusBar.systemStatusBar statusItemWithLength:36];
50 statusItem.image = [NSImage imageNamed:@"Status Menu Icon Disabled"];
51 statusItem.highlightMode = YES;
52 statusItem.menu = statusItemMenu;
53 statusItem.target = self;
54 }
55
56 - (void)applicationDidFinishLaunching:(NSNotification *)notification {
57 if ([NSUserDefaults.standardUserDefaults boolForKey:@"hidden in status item"]
58 && NSRunningApplication.currentApplication.wasLaunchedAsLoginItemOrResume)
59 [self transformIntoElement:nil];
60 else
61 [window makeKeyAndOrderFront:nil];
62 }
63
64 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication
65 hasVisibleWindows:(BOOL)flag {
66 [self restoreToForeground:theApplication];
67 return NO;
68 }
69
70 - (void)restoreToForeground:(id)sender {
71 ProcessSerialNumber psn = { 0, kCurrentProcess };
72 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
73 [NSApplication.sharedApplication activateIgnoringOtherApps:YES];
74 [window makeKeyAndOrderFront:sender];
75 [NSObject cancelPreviousPerformRequestsWithTarget:self
76 selector:@selector(transformIntoElement:)
77 object:self];
78 [NSUserDefaults.standardUserDefaults setBool:NO forKey:@"hidden in status item"];
79 }
80
81 - (void)applicationWillBecomeActive:(NSNotification *)notification {
82 if (window.isVisible)
83 [self restoreToForeground:notification];
84 }
85
86 - (void)transformIntoElement:(id)sender {
87 ProcessSerialNumber psn = { 0, kCurrentProcess };
88 TransformProcessType(&psn, kProcessTransformToUIElementApplication);
89 [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"hidden in status item"];
90 }
91
92 - (void)flashStatusItem {
93 if ([statusItem.image.name isEqualToString:@"Status Menu Icon"]) {
94 statusItem.image = [NSImage imageNamed:@"Status Menu Icon Disabled"];
95 } else {
96 statusItem.image = [NSImage imageNamed:@"Status Menu Icon"];
97 }
98
99 }
100
101 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication {
102 [theApplication hide:theApplication];
103 // If we turn into a UIElement right away, the application cancels
104 // the deactivation events. The dock icon disappears, but an
105 // unresponsive menu bar remains until the user clicks somewhere.
106 // So delay just long enough to be past the end handling that.
107 [self performSelector:@selector(transformIntoElement:) withObject:self afterDelay:0.001];
108 return NO;
109 }
110
111 - (void)eventSimulationStarted:(NSNotification *)note {
112 statusItem.image = [NSImage imageNamed:@"Status Menu Icon"];
113 [NSWorkspace.sharedWorkspace.notificationCenter
114 addObserver:self
115 selector:@selector(didSwitchApplication:)
116 name:NSWorkspaceDidActivateApplicationNotification
117 object:nil];
118 }
119
120 - (void)eventSimulationStopped:(NSNotification *)note {
121 statusItem.image = [NSImage imageNamed:@"Status Menu Icon Disabled"];
122 [NSWorkspace.sharedWorkspace.notificationCenter
123 removeObserver:self
124 name:NSWorkspaceDidActivateApplicationNotification
125 object:nil];
126 }
127
128 - (void)mappingDidChange:(NSNotification *)note {
129 NSUInteger idx = [note.userInfo[NJMappingIndexKey] intValue];
130 [self.mvc changedActiveMappingToIndex:idx];
131
132 if (!window.isVisible)
133 for (int i = 0; i < 4; ++i)
134 [self performSelector:@selector(flashStatusItem)
135 withObject:self
136 afterDelay:0.2 * i];
137 }
138
139 - (NSMenu *)applicationDockMenu:(NSApplication *)sender {
140 return dockMenu;
141 }
142
143 - (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
144 [self restoreToForeground:sender];
145 NSError *error;
146 NSURL *URL = [NSURL fileURLWithPath:filename];
147 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:URL
148 error:&error];
149 if ([self.mappingsController[mapping.name] hasConflictWith:mapping]) {
150 [self promptForMapping:mapping atIndex:self.mappingsController.count];
151 } else if (self.mappingsController[mapping.name]) {
152 [self.mappingsController[mapping.name] mergeEntriesFrom:mapping];
153 } else if (mapping) {
154 [self.mappingsController addMapping:mapping];
155 } else {
156 [window presentError:error
157 modalForWindow:window
158 delegate:nil
159 didPresentSelector:nil
160 contextInfo:nil];
161 }
162 return !!mapping;
163 }
164
165 - (void)mappingWasChosen:(NJMapping *)mapping {
166 [self.mappingsController activateMapping:mapping];
167 }
168
169 - (void)mappingListShouldOpen {
170 [self restoreToForeground:self];
171 [self.mvc mappingTriggerClicked:self];
172 }
173
174 - (void)loginItemPromptDidEnd:(NSWindow *)sheet
175 returnCode:(int)returnCode
176 contextInfo:(void *)contextInfo {
177 if (returnCode == NSAlertDefaultReturn) {
178 [NSRunningApplication.currentApplication addToLoginItems];
179 // If we're going to automatically start, don't bug the user
180 // about automatic updates next boot - they probably want it,
181 // and if they don't they probably want a prompt for it less.
182 SUUpdater.sharedUpdater.automaticallyChecksForUpdates = YES;
183 }
184 }
185
186 - (void)loginItemPromptDidDismiss:(NSWindow *)sheet
187 returnCode:(int)returnCode
188 contextInfo:(void *)contextInfo {
189 [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"explained login items"];
190 [window performClose:sheet];
191 }
192
193 - (BOOL)windowShouldClose:(NSWindow *)sender {
194 if (sender != window
195 || NSRunningApplication.currentApplication.isLoginItem
196 || [NSUserDefaults.standardUserDefaults boolForKey:@"explained login items"])
197 return YES;
198 NSBeginAlertSheet(
199 NSLocalizedString(@"login items prompt", @"alert prompt for adding to login items"),
200 NSLocalizedString(@"login items add button", @"button to add to login items"),
201 NSLocalizedString(@"login items don't add button", @"button to not add to login items"),
202 nil, window, self,
203 @selector(loginItemPromptDidEnd:returnCode:contextInfo:),
204 @selector(loginItemPromptDidDismiss:returnCode:contextInfo:),
205 NULL,
206 NSLocalizedString(@"login items explanation", @"a brief explanation of login items")
207 );
208 for (int i = 0; i < 10; ++i)
209 [self performSelector:@selector(flashStatusItem)
210 withObject:self
211 afterDelay:0.5 * i];
212 return NO;
213 }
214
215 - (void)importMappingClicked:(id)sender {
216 NSOpenPanel *panel = [NSOpenPanel openPanel];
217 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
218 [panel beginSheetModalForWindow:window
219 completionHandler:^(NSInteger result) {
220 if (result != NSFileHandlingPanelOKButton)
221 return;
222 [panel close];
223 NSError *error;
224 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:panel.URL
225 error:&error];
226 if ([self.mappingsController[mapping.name] hasConflictWith:mapping]) {
227 [self promptForMapping:mapping atIndex:self.mappingsController.count];
228 } else if (self.mappingsController[mapping.name]) {
229 [self.mappingsController[mapping.name] mergeEntriesFrom:mapping];
230 } else if (mapping) {
231 [self.mappingsController addMapping:mapping];
232 } else {
233 [window presentError:error
234 modalForWindow:window
235 delegate:nil
236 didPresentSelector:nil
237 contextInfo:nil];
238 }
239 }];
240
241 }
242
243 - (void)exportMappingClicked:(id)sender {
244 NSSavePanel *panel = [NSSavePanel savePanel];
245 panel.allowedFileTypes = @[ @"enjoyable" ];
246 NJMapping *mapping = self.mappingsController.currentMapping;
247 panel.nameFieldStringValue = [mapping.name stringByFixingPathComponent];
248 [panel beginSheetModalForWindow:window
249 completionHandler:^(NSInteger result) {
250 if (result != NSFileHandlingPanelOKButton)
251 return;
252 [panel close];
253 NSError *error;
254 if (![mapping writeToURL:panel.URL error:&error]) {
255 [window presentError:error
256 modalForWindow:window
257 delegate:nil
258 didPresentSelector:nil
259 contextInfo:nil];
260 }
261 }];
262 }
263
264 - (void)mappingConflictDidResolve:(NSAlert *)alert
265 returnCode:(NSInteger)returnCode
266 contextInfo:(void *)contextInfo {
267 NSDictionary *userInfo = CFBridgingRelease(contextInfo);
268 NJMapping *oldMapping = userInfo[@"old mapping"];
269 NJMapping *newMapping = userInfo[@"new mapping"];
270 NSInteger idx = [userInfo[@"index"] intValue];
271 [alert.window orderOut:nil];
272 switch (returnCode) {
273 case NSAlertFirstButtonReturn: // Merge
274 [self.mappingsController mergeMapping:newMapping intoMapping:oldMapping];
275 [self.mappingsController activateMapping:oldMapping];
276 break;
277 case NSAlertThirdButtonReturn: // New Mapping
278 [self.mvc beginUpdates];
279 [self.mappingsController addMapping:newMapping];
280 [self.mvc addedMappingAtIndex:idx startEditing:YES];
281 [self.mvc endUpdates];
282 [self.mappingsController activateMapping:newMapping];
283 break;
284 default: // Cancel, other.
285 break;
286 }
287 }
288
289 - (void)promptForMapping:(NJMapping *)mapping atIndex:(NSInteger)idx {
290 NJMapping *mergeInto = self.mappingsController[mapping.name];
291 NSAlert *conflictAlert = [[NSAlert alloc] init];
292 conflictAlert.messageText = NSLocalizedString(@"import conflict prompt", @"Title of import conflict alert");
293 conflictAlert.informativeText =
294 [NSString stringWithFormat:NSLocalizedString(@"import conflict in %@", @"Explanation of import conflict"),
295 mapping.name];
296 [conflictAlert addButtonWithTitle:NSLocalizedString(@"import and merge", @"button to merge imported mappings")];
297 [conflictAlert addButtonWithTitle:NSLocalizedString(@"cancel import", @"button to cancel import")];
298 [conflictAlert addButtonWithTitle:NSLocalizedString(@"import new mapping", @"button to import as new mapping")];
299 [conflictAlert beginSheetModalForWindow:window
300 modalDelegate:self
301 didEndSelector:@selector(mappingConflictDidResolve:returnCode:contextInfo:)
302 contextInfo:(void *)CFBridgingRetain(@{ @"index": @(idx),
303 @"old mapping": mergeInto,
304 @"new mapping": mapping })];
305 }
306
307 - (NSInteger)numberOfMappings:(NJMappingsViewController *)mvc {
308 return self.mappingsController.count;
309 }
310
311 - (NJMapping *)mappingsViewController:(NJMappingsViewController *)mvc
312 mappingForIndex:(NSUInteger)idx {
313 return self.mappingsController[idx];
314 }
315
316 - (void)mappingsViewController:(NJMappingsViewController *)mvc
317 renameMappingAtIndex:(NSInteger)index
318 toName:(NSString *)name {
319 [self.mappingsController renameMapping:self.mappingsController[index]
320 to:name];
321 }
322
323 - (BOOL)mappingsViewController:(NJMappingsViewController *)mvc
324 canMoveMappingFromIndex:(NSInteger)fromIdx
325 toIndex:(NSInteger)toIdx {
326 return fromIdx != toIdx && fromIdx != 0 && toIdx != 0
327 && toIdx < (NSInteger)self.mappingsController.count;
328 }
329
330 - (void)mappingsViewController:(NJMappingsViewController *)mvc
331 moveMappingFromIndex:(NSInteger)fromIdx
332 toIndex:(NSInteger)toIdx {
333 [mvc beginUpdates];
334 [mvc.mappingList moveRowAtIndex:fromIdx toIndex:toIdx];
335 [self.mappingsController moveMoveMappingFromIndex:fromIdx toIndex:toIdx];
336 [mvc endUpdates];
337 }
338
339 - (BOOL)mappingsViewController:(NJMappingsViewController *)mvc
340 canRemoveMappingAtIndex:(NSInteger)idx {
341 return idx != 0;
342 }
343
344 - (void)mappingsViewController:(NJMappingsViewController *)mvc
345 removeMappingAtIndex:(NSInteger)idx {
346 [mvc beginUpdates];
347 [mvc removedMappingAtIndex:idx];
348 [self.mappingsController removeMappingAtIndex:idx];
349 [mvc endUpdates];
350 }
351
352 - (BOOL)mappingsViewController:(NJMappingsViewController *)mvc
353 importMappingFromURL:(NSURL *)url
354 atIndex:(NSInteger)index
355 error:(NSError **)error {
356 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
357 error:error];
358 if ([self.mappingsController[mapping.name] hasConflictWith:mapping]) {
359 [self promptForMapping:mapping atIndex:index];
360 } else if (self.mappingsController[mapping.name]) {
361 [self.mappingsController[mapping.name] mergeEntriesFrom:mapping];
362 } else if (mapping) {
363 [self.mappingsController insertMapping:mapping atIndex:index];
364 }
365 return !!mapping;
366 }
367
368 - (void)mappingsViewController:(NJMappingsViewController *)mvc
369 addMapping:(NJMapping *)mapping {
370 [mvc beginUpdates];
371 [mvc addedMappingAtIndex:self.mappingsController.count startEditing:YES];
372 [self.mappingsController addMapping:mapping];
373 [mvc endUpdates];
374 [self.mappingsController activateMapping:mapping];
375 }
376
377 - (void)mappingsViewController:(NJMappingsViewController *)mvc
378 choseMappingAtIndex:(NSInteger)idx {
379 [self.mappingsController activateMapping:self.mappingsController[idx]];
380 }
381
382 @end