Change two-pass behavior for loading mappings. Allow lazy binding of mappings by...
[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 error:&error];
142 if (mapping) {
143 [self.mappingsController addOrMergeMapping:mapping];
144 return YES;
145 } else {
146 [window presentError:error
147 modalForWindow:window
148 delegate:nil
149 didPresentSelector:nil
150 contextInfo:nil];
151 return NO;
152 }
153 }
154
155 - (void)mappingWasChosen:(NJMapping *)mapping {
156 [self.mappingsController activateMapping:mapping];
157 }
158
159 - (void)mappingListShouldOpen {
160 [self restoreToForeground:self];
161 [self.mappingsController.mvc mappingTriggerClicked:self];
162 }
163
164 - (void)loginItemPromptDidEnd:(NSWindow *)sheet
165 returnCode:(int)returnCode
166 contextInfo:(void *)contextInfo {
167 if (returnCode == NSAlertDefaultReturn) {
168 [NSRunningApplication.currentApplication addToLoginItems];
169 // If we're going to automatically start, don't bug the user
170 // about automatic updates next boot - they probably want it,
171 // and if they don't they probably want a prompt for it less.
172 SUUpdater.sharedUpdater.automaticallyChecksForUpdates = YES;
173 }
174 }
175
176 - (void)loginItemPromptDidDismiss:(NSWindow *)sheet
177 returnCode:(int)returnCode
178 contextInfo:(void *)contextInfo {
179 [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"explained login items"];
180 [window performClose:sheet];
181 }
182
183 - (BOOL)windowShouldClose:(NSWindow *)sender {
184 if (sender != window
185 || NSRunningApplication.currentApplication.isLoginItem
186 || [NSUserDefaults.standardUserDefaults boolForKey:@"explained login items"])
187 return YES;
188 NSBeginAlertSheet(
189 NSLocalizedString(@"login items prompt", @"alert prompt for adding to login items"),
190 NSLocalizedString(@"login items add button", @"button to add to login items"),
191 NSLocalizedString(@"login items don't add button", @"button to not add to login items"),
192 nil, window, self,
193 @selector(loginItemPromptDidEnd:returnCode:contextInfo:),
194 @selector(loginItemPromptDidDismiss:returnCode:contextInfo:),
195 NULL,
196 NSLocalizedString(@"login items explanation", @"a brief explanation of login items")
197 );
198 for (int i = 0; i < 10; ++i)
199 [self performSelector:@selector(flashStatusItem)
200 withObject:self
201 afterDelay:0.5 * i];
202 return NO;
203 }
204
205 - (void)importMappingClicked:(id)sender {
206 NSOpenPanel *panel = [NSOpenPanel openPanel];
207 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
208 [panel beginSheetModalForWindow:window
209 completionHandler:^(NSInteger result) {
210 if (result != NSFileHandlingPanelOKButton)
211 return;
212 [panel close];
213 NSError *error;
214 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:panel.URL
215 error:&error];
216 if (mapping) {
217 [self.mappingsController addOrMergeMapping:mapping];
218 } else {
219 [window presentError:error
220 modalForWindow:window
221 delegate:nil
222 didPresentSelector:nil
223 contextInfo:nil];
224 }
225 }];
226
227 }
228
229 - (void)exportMappingClicked:(id)sender {
230 NSSavePanel *panel = [NSSavePanel savePanel];
231 panel.allowedFileTypes = @[ @"enjoyable" ];
232 NJMapping *mapping = self.mappingsController.currentMapping;
233 panel.nameFieldStringValue = [mapping.name stringByFixingPathComponent];
234 [panel beginSheetModalForWindow:window
235 completionHandler:^(NSInteger result) {
236 if (result != NSFileHandlingPanelOKButton)
237 return;
238 [panel close];
239 NSError *error;
240 if (![mapping writeToURL:panel.URL error:&error]) {
241 [window presentError:error
242 modalForWindow:window
243 delegate:nil
244 didPresentSelector:nil
245 contextInfo:nil];
246 }
247 }];
248 }
249
250
251
252 @end