Update project for OS X 10.10.
[enjoyable.git] / Categories / NSRunningApplication+LoginItem.m
1 //
2 // NSApplication+LoginItem.m
3 // Enjoyable
4 //
5 // Created by Joe Wreschnig on 3/13/13.
6 //
7 //
8
9 #import "NSRunningApplication+LoginItem.h"
10
11 #import <CoreServices/CoreServices.h>
12
13 static const UInt32 RESOLVE_FLAGS = kLSSharedFileListNoUserInteraction
14 | kLSSharedFileListDoNotMountVolumes;
15
16 @implementation NSRunningApplication (LoginItem)
17
18 - (BOOL)isLoginItem {
19 LSSharedFileListRef loginItems = LSSharedFileListCreate(
20 NULL, kLSSharedFileListSessionLoginItems, NULL);
21 NSURL *myURL = self.bundleURL;
22 BOOL found = NO;
23 UInt32 seed = 0;
24 NSArray *currentLoginItems = CFBridgingRelease(
25 LSSharedFileListCopySnapshot(loginItems, &seed));
26 for (id obj in currentLoginItems) {
27 LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)obj;
28 CFURLRef itemURL = NULL;
29 if (!LSSharedFileListItemResolve(item, RESOLVE_FLAGS, &itemURL, NULL)) {
30 found = CFEqual(itemURL, (__bridge CFURLRef)myURL);
31 CFRelease(itemURL);
32 }
33 if (found)
34 break;
35 }
36 CFRelease(loginItems);
37 return found;
38 }
39
40 - (void)addToLoginItems {
41 if (!self.isLoginItem) {
42 NSURL *myURL = self.bundleURL;
43 LSSharedFileListRef loginItems = LSSharedFileListCreate(
44 NULL, kLSSharedFileListSessionLoginItems, NULL);
45 LSSharedFileListInsertItemURL(
46 loginItems, kLSSharedFileListItemBeforeFirst,
47 NULL, NULL, (__bridge CFURLRef)myURL, NULL, NULL);
48 CFRelease(loginItems);
49 }
50 }
51
52 - (void)removeFromLoginItems {
53 LSSharedFileListRef loginItems = LSSharedFileListCreate(
54 NULL, kLSSharedFileListSessionLoginItems, NULL);
55 NSURL *myURL = self.bundleURL;
56 UInt32 seed = 0;
57 NSArray *currentLoginItems = CFBridgingRelease(
58 LSSharedFileListCopySnapshot(loginItems, &seed));
59 for (id obj in currentLoginItems) {
60 LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)obj;
61 CFURLRef itemURL = NULL;
62 if (!LSSharedFileListItemResolve(item, RESOLVE_FLAGS, &itemURL, NULL)) {
63 if (CFEqual(itemURL, (__bridge CFURLRef)myURL))
64 LSSharedFileListItemRemove(loginItems, item);
65 CFRelease(itemURL);
66 }
67 }
68 CFRelease(loginItems);
69 }
70
71 - (BOOL)wasLaunchedAsLoginItemOrResume {
72 ProcessSerialNumber psn = { 0, kCurrentProcess };
73 NSDictionary *processInfo = CFBridgingRelease(
74 ProcessInformationCopyDictionary(
75 &psn, kProcessDictionaryIncludeAllInformationMask));
76 long long parent = [processInfo[@"ParentPSN"] longLongValue];
77 ProcessSerialNumber parentPsn = {
78 (parent >> 32) & 0x00000000FFFFFFFFLL,
79 parent & 0x00000000FFFFFFFFLL
80 };
81
82 NSDictionary *parentInfo = CFBridgingRelease(
83 ProcessInformationCopyDictionary(
84 &parentPsn, kProcessDictionaryIncludeAllInformationMask));
85 return [parentInfo[@"FileCreator"] isEqualToString:@"lgnw"];
86 }
87
88
89 @end