Support magic @Application token for automatic mapping names. Fall back to the bundle...
[enjoyable.git] / EnjoyableApplicationDelegate.m
index 388103b..2478b4e 100644 (file)
 
 @implementation EnjoyableApplicationDelegate
 
-- (void)didSwitchApplication:(NSNotification *)notification {
-    NSRunningApplication *currentApp = notification.userInfo[NSWorkspaceApplicationKey];
-    [self.mappingsController activateMappingForProcess:currentApp.localizedName];
+- (void)didSwitchApplication:(NSNotification *)note {
+    NSRunningApplication *activeApp = note.userInfo[NSWorkspaceApplicationKey];
+    NSString *name = activeApp.localizedName;
+    if (!name)
+        name = activeApp.bundleIdentifier;
+    if (name && ![name isEqualToString:NSRunningApplication.currentApplication.localizedName])
+        [self.mappingsController activateMappingForProcess:name];
 }
 
 - (void)applicationDidFinishLaunching:(NSNotification *)notification {
     [self.mappingsController load];
 }
 
-- (void)applicationWillTerminate:(NSNotification *)aNotification {
-       [NSUserDefaults.standardUserDefaults synchronize];
-    [NSNotificationCenter.defaultCenter removeObserver:self];
+- (void)applicationDidBecomeActive:(NSNotification *)notification {
+    [window makeKeyAndOrderFront:nil];
+}
+
+- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication
+                    hasVisibleWindows:(BOOL)flag {
+    [window makeKeyAndOrderFront:nil];
+    return NO;
 }
 
 - (void)eventTranslationActivated:(NSNotification *)note {
+    [NSProcessInfo.processInfo disableAutomaticTermination:@"Input translation is active."];
     [NSWorkspace.sharedWorkspace.notificationCenter
         addObserver:self
         selector:@selector(didSwitchApplication:)
@@ -61,6 +71,7 @@
 }
 
 - (void)eventTranslationDeactivated:(NSNotification *)note {
+    [NSProcessInfo.processInfo enableAutomaticTermination:@"Input translation is active."];
     [NSWorkspace.sharedWorkspace.notificationCenter
         removeObserver:self
         name:NSWorkspaceDidActivateApplicationNotification
     int added = 0;
     for (NJMapping *mapping in mappings) {
         NSString *keyEquiv = ++added < 10 ? @(added).stringValue : @"";
-        NSMenuItem *item = [dockMenuBase addItemWithTitle:mapping.name
-                                                   action:@selector(chooseMapping:)
-                                            keyEquivalent:keyEquiv];
+        NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:mapping.name
+                                                      action:@selector(chooseMapping:)
+                                               keyEquivalent:keyEquiv];
         item.representedObject = mapping;
+        item.state = mapping == self.mappingsController.currentMapping;
+        [dockMenuBase addItem:item];
     }
-    [_outputController refreshMappings];
 }
 
 - (void)mappingDidChange:(NSNotification *)note {