aboutsummaryrefslogtreecommitdiff
path: root/AppKit/GTMNSWorkspace+Running.m
blob: 0273e1084917995350f688f3b0815835f7ede2e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//
//  GTMNSWorkspace+Running.m
//
//  Copyright 2007-2008 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
// 
//  http://www.apache.org/licenses/LICENSE-2.0
// 
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#import "GTMNSWorkspace+Running.h"
#import <Carbon/Carbon.h>
#import <unistd.h>
#import "GTMGarbageCollection.h"
#import "GTMSystemVersion.h"
#import "GTMObjectSingleton.h"

NSString *const kGTMWorkspaceRunningPSN = @"PSN";
NSString *const kGTMWorkspaceRunningFlavor = @"Flavor";
NSString *const kGTMWorkspaceRunningAttributes = @"Attributes";
NSString *const kGTMWorkspaceRunningParentPSN = @"ParentPSN";
NSString *const kGTMWorkspaceRunningFileType = @"FileType";
NSString *const kGTMWorkspaceRunningFileCreator = @"FileCreator";
NSString *const kGTMWorkspaceRunningPID = @"pid";
NSString *const kGTMWorkspaceRunningLSBackgroundOnly = @"LSBackgroundOnly";
NSString *const kGTMWorkspaceRunningLSUIElement = @"LSUIElement";
NSString *const kGTMWorkspaceRunningIsHidden = @"IsHiddenAttr";
NSString *const kGTMWorkspaceRunningCheckedIn = @"IsCheckedInAttr";
NSString *const kGTMWorkspaceRunningLSUIPresentationMode 
  = @"LSUIPresentationMode";
NSString *const kGTMWorkspaceRunningBundlePath = @"BundlePath";
NSString *const kGTMWorkspaceRunningBundleVersion = @"CFBundleVersion";

@interface GTMWorkspaceRunningApplicationList : NSObject {
 @private 
  NSArray *launchedApps_;
}
+ (GTMWorkspaceRunningApplicationList *)sharedApplicationList;
- (NSArray *)launchedApplications;
- (void)didLaunchOrTerminateApp:(NSNotification *)notification;
@end

@implementation NSWorkspace (GTMWorkspaceRunningAdditions)

/// Returns a YES/NO if a process w/ the given identifier is running
- (BOOL)gtm_isAppWithIdentifierRunning:(NSString *)identifier {
  if ([identifier length] == 0) return NO;
  NSArray *launchedApps = [self gtm_launchedApplications];
  NSArray *buildIDs 
    = [launchedApps valueForKey:@"NSApplicationBundleIdentifier"];
  return [buildIDs containsObject:identifier];
}

- (NSDictionary *)gtm_processInfoDictionaryForPID:(pid_t)pid {
  NSDictionary *dict = nil;
  ProcessSerialNumber psn;
  if (GetProcessForPID(pid, &psn) == noErr) {
    dict = [self gtm_processInfoDictionaryForPSN:&psn];
  }
  return dict;
}

- (NSDictionary *)gtm_processInfoDictionaryForPSN:(ProcessSerialNumberPtr)psn {
  NSDictionary *dict = nil;
  if (psn) {
    CFDictionaryRef cfDict 
      = ProcessInformationCopyDictionary(psn, 
                                         kProcessDictionaryIncludeAllInformationMask);
    dict = GTMCFAutorelease(cfDict);
  }
  return dict;
}

- (NSDictionary *)gtm_processInfoDictionary {
  NSDictionary *dict = nil;
  ProcessSerialNumber selfNumber;
  if (MacGetCurrentProcess(&selfNumber) == noErr) {
    dict = [self gtm_processInfoDictionaryForPSN:&selfNumber];
  }
  return dict;
}

- (NSDictionary *)gtm_processInfoDictionaryForActiveApp {
  NSDictionary *processDict = nil;
  ProcessSerialNumber psn;
  OSStatus status = GetFrontProcess(&psn);
  if (status == noErr) {
    processDict = [self gtm_processInfoDictionaryForPSN:&psn];
  }
  return processDict;
}

- (BOOL)gtm_wasLaunchedAsLoginItem {
  // If the launching process was 'loginwindow', we were launched as a login 
  // item
  return [self gtm_wasLaunchedByProcess:@"com.apple.loginwindow"];
}

- (BOOL)gtm_wasLaunchedByProcess:(NSString*)bundleid {
  BOOL wasLaunchedByProcess = NO;
  NSDictionary *processInfo = [self gtm_processInfoDictionary];
  if (processInfo) {
    NSNumber *processNumber 
      = [processInfo objectForKey:kGTMWorkspaceRunningParentPSN];
    ProcessSerialNumber parentPSN 
      = [self gtm_numberToProcessSerialNumber:processNumber];
    NSDictionary *parentProcessInfo 
      = [self gtm_processInfoDictionaryForPSN:&parentPSN];
    NSString *parentBundle 
      = [parentProcessInfo objectForKey:kGTMWorkspaceRunningBundleIdentifier];
    wasLaunchedByProcess 
      = [parentBundle isEqualToString:bundleid];
  }
  return wasLaunchedByProcess;
}

- (BOOL)gtm_processSerialNumber:(ProcessSerialNumber*)outPSN 
                   withBundleID:(NSString*)bundleID {
  if (!outPSN || [bundleID length] == 0) {
    return NO;
  }
  
  NSArray *apps = [self gtm_launchedApplications];
  
  NSEnumerator *enumerator = [apps objectEnumerator];
  NSDictionary *dict;
  
  while ((dict = [enumerator nextObject])) {
    NSString *nextID = [dict objectForKey:@"NSApplicationBundleIdentifier"];
    
    if ([nextID isEqualToString:bundleID]) {
      NSNumber *psn 
        = [dict objectForKey:@"NSApplicationProcessSerialNumberLow"];
      outPSN->lowLongOfPSN = [psn unsignedIntValue];
      
      psn = [dict objectForKey:@"NSApplicationProcessSerialNumberHigh"];
      outPSN->highLongOfPSN = [psn unsignedIntValue];
      
      return YES;
    }
  }
  
  return NO;
}

- (ProcessSerialNumber)gtm_numberToProcessSerialNumber:(NSNumber*)number {
  // There is a bug in Tiger where they were packing ProcessSerialNumbers
  // incorrectly into the longlong that they stored in the dictionary.
  // This fixes it.
  ProcessSerialNumber outPSN = { kNoProcess, kNoProcess};
  if (number) {
    long long temp = [number longLongValue];
    UInt32 hi = (UInt32)((temp >> 32) & 0x00000000FFFFFFFFLL);
    UInt32 lo = (UInt32)((temp >> 0) & 0x00000000FFFFFFFFLL);
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
    outPSN.highLongOfPSN = hi;
    outPSN.lowLongOfPSN = lo;
#else  // MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
    if ([GTMSystemVersion isLeopardOrGreater]) {
      outPSN.highLongOfPSN = hi;
      outPSN.lowLongOfPSN = lo;
    } else {
#if TARGET_RT_BIG_ENDIAN
      outPSN.highLongOfPSN = hi;
      outPSN.lowLongOfPSN = lo;
#else
      outPSN.highLongOfPSN = lo;
      outPSN.lowLongOfPSN = hi;
#endif  // TARGET_RT_BIG_ENDIAN
    }
#endif  // MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
  }
  return outPSN;
}

- (NSArray *)gtm_launchedApplications {
  GTMWorkspaceRunningApplicationList *list 
    = [GTMWorkspaceRunningApplicationList sharedApplicationList];
  return [list launchedApplications];
}
@end

@implementation GTMWorkspaceRunningApplicationList
  
GTMOBJECT_SINGLETON_BOILERPLATE(GTMWorkspaceRunningApplicationList, 
                                sharedApplicationList)
- (id)init {
  if ((self = [super init])) {
    [self didLaunchOrTerminateApp:nil];
  }
  return self;
}

- (void)finalize {
  [self didLaunchOrTerminateApp:nil];
  [super finalize];
}

- (void)dealloc {
  [self didLaunchOrTerminateApp:nil];
  [super dealloc];
}

- (void)didLaunchOrTerminateApp:(NSNotification *)notification {
  @synchronized (self) {
    [launchedApps_ autorelease];
    NSNotificationCenter *workSpaceNC 
      = [[NSWorkspace sharedWorkspace] notificationCenter];
    [workSpaceNC removeObserver:self];
    launchedApps_ = nil;
  }
}

- (NSArray *)launchedApplications {
  @synchronized (self) {
    if (!launchedApps_) {
      NSWorkspace *ws = [NSWorkspace sharedWorkspace];
      NSNotificationCenter *workSpaceNC = [ws notificationCenter];
      [workSpaceNC addObserver:self
                      selector:@selector(didLaunchOrTerminateApp:)
                          name:NSWorkspaceDidLaunchApplicationNotification
                        object:nil];
      [workSpaceNC addObserver:self
                      selector:@selector(didLaunchOrTerminateApp:)
                          name:NSWorkspaceDidTerminateApplicationNotification
                        object:nil];
      launchedApps_ = [[ws launchedApplications] retain];
    }
    // We want to keep launchedApps_ in the autoreleasepool of this thread
    [[launchedApps_ retain] autorelease];
  }
  return launchedApps_;
}
  
@end