-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathQSProcessMonitor.m
More file actions
490 lines (412 loc) · 15.7 KB
/
QSProcessMonitor.m
File metadata and controls
490 lines (412 loc) · 15.7 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
#import "QSObject.h"
#import "QSObject_FileHandling.h"
#import "QSProcessMonitor.h"
#import "QSTypes.h"
#import "NSEvent+BLTRExtensions.h"
@implementation NSValue (ProcessSerialNumberExtension)
+ (id)valueWithProcessSerialNumber:(ProcessSerialNumber)psn {
return [[self alloc] initWithProcessSerialNumber:psn];
}
- (id)initWithProcessSerialNumber:(ProcessSerialNumber)psn {
self = [self initWithBytes:(const void *)&psn objCType:@encode(ProcessSerialNumber)];
return self;
}
- (ProcessSerialNumber)processSerialNumberValue {
ProcessSerialNumber psn;
[self getValue:&psn];
return psn;
}
@end
@interface QSProcessMonitor (QSInternal)
- (NSDictionary *)infoForPSN:(ProcessSerialNumber)processSerialNumber;
- (void)setPreviousApplication:(NSDictionary *)newPreviousApplication;
- (void)setCurrentApplication:(NSDictionary *)newCurrentApplication;
- (NSDictionary *)processesDict;
- (void)appChanged:(ProcessSerialNumber)psn;
- (void)appLaunched:(ProcessSerialNumber)psn;
- (void)appTerminated:(ProcessSerialNumber)psn;
@end
NSString *QSProcessMonitorFrontApplicationSwitched = @"QSProcessMonitorFrontApplicationSwitched";
NSString *QSProcessMonitorApplicationLaunched = @"QSProcessMonitorApplicationLaunched";
NSString *QSProcessMonitorApplicationTerminated = @"QSProcessMonitorApplicationTerminated";
dispatch_queue_t proc_thread;
OSStatus GetPSNForAppInfo(ProcessSerialNumber *psn, NSDictionary *theApp) {
if (!theApp) return 1;
psn->highLongOfPSN = [[theApp objectForKey:@"NSApplicationProcessSerialNumberHigh"] intValue];
psn->lowLongOfPSN = [[theApp objectForKey:@"NSApplicationProcessSerialNumberLow"] intValue];
return noErr;
}
#pragma mark -
#pragma mark Carbon Process event handlers
OSStatus appChanged(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
ProcessSerialNumber psn;
OSStatus result;
result = GetEventParameter(theEvent,
kEventParamProcessID,
typeProcessSerialNumber, NULL,
sizeof(psn), NULL,
&psn);
if( result == noErr ) {
QSGCDQueueAsync(proc_thread, ^{
[(__bridge QSProcessMonitor*)userData appChanged:psn];
});
} else {
NSLog(@"Unable to get event parameter kEventParamProcessID");
}
return CallNextEventHandler(nextHandler, theEvent);
}
OSStatus appLaunched(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
ProcessSerialNumber psn;
OSStatus result;
result = GetEventParameter(theEvent,
kEventParamProcessID,
typeProcessSerialNumber, NULL,
sizeof(psn), NULL,
&psn);
if( result == noErr ) {
QSGCDQueueAsync(proc_thread, ^{
[(__bridge QSProcessMonitor*)userData appLaunched:psn];
});
} else {
NSLog(@"Unable to get event parameter kEventParamProcessID");
}
return CallNextEventHandler(nextHandler, theEvent);
}
OSStatus appTerminated(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
ProcessSerialNumber psn;
OSStatus result;
result = GetEventParameter(theEvent,
kEventParamProcessID,
typeProcessSerialNumber, NULL,
sizeof(psn), NULL,
&psn);
if( result == noErr ) {
QSGCDQueueAsync(proc_thread, ^{
[(__bridge QSProcessMonitor*)userData appTerminated:psn];
});
} else {
NSLog(@"Unable to get event parameter kEventParamProcessID");
}
return CallNextEventHandler(nextHandler, theEvent);
}
@implementation QSProcessMonitor
+ (id)sharedInstance {
static id _sharedInstance;
if (!_sharedInstance) _sharedInstance = [[self allocWithZone:nil] init];
return _sharedInstance;
}
- (id)init {
if (self = [super init]) {
isReloading = NO;
proc_thread = dispatch_queue_create("quicksilver.qsprocessmonitor.update", DISPATCH_QUEUE_SERIAL);
EventTypeSpec eventType;
EventHandlerUPP handlerFunction;
OSStatus err;
eventType.eventClass = kEventClassApplication;
eventType.eventKind = kEventAppFrontSwitched;
handlerFunction = NewEventHandlerUPP(appChanged);
err = InstallApplicationEventHandler(handlerFunction, 1, &eventType, (__bridge void *) self, &changeHandler);
if (err)
NSLog(@"QSProcessMonitor Change registration err %ld", (long)err);
eventType.eventClass = kEventClassApplication;
eventType.eventKind = kEventAppLaunched;
handlerFunction = NewEventHandlerUPP(appLaunched);
err = InstallApplicationEventHandler(handlerFunction, 1, &eventType, (__bridge void *) self, &launchHandler);
if (err)
NSLog(@"QSProcessMonitor Launch registration err %ld", (long)err);
eventType.eventClass = kEventClassApplication;
eventType.eventKind = kEventAppTerminated;
handlerFunction = NewEventHandlerUPP(appTerminated);
err = InstallApplicationEventHandler(handlerFunction, 1, &eventType, (__bridge void *) self, &terminateHandler);
if (err)
NSLog(@"QSProcessMonitor Terminate registration err %ld", (long)err);
}
return self;
}
- (void)dealloc {
OSStatus err;
err = RemoveEventHandler(changeHandler);
if(err)
NSLog(@"error %ld removing change handler", (long)err);
err = RemoveEventHandler(launchHandler);
if(err)
NSLog(@"error %ld removing launch handler", (long)err);
err = RemoveEventHandler(terminateHandler);
if(err)
NSLog(@"error %ld removing terminate handler", (long)err);
currentApplication = nil;
previousApplication = nil;
processes = nil;
processesSnapshot = nil;
}
- (QSObject *)imbuedFileProcessForDict:(NSDictionary *)dict {
NSString *ident = [dict objectForKey:@"NSApplicationBundleIdentifier"];
NSString *appPath = [dict objectForKey:@"NSApplicationPath"];
NSBundle *bundle = [NSBundle bundleWithIdentifier:ident];
QSObject *newObject = nil;
if (bundle && [appPath isEqualToString:[bundle executablePath]]) {
newObject = [QSObject fileObjectWithPath:[bundle bundlePath]];
// NSLog(@"%@ %@", bundlePath, newObject);
}
if (!newObject) {
if (appPath) {
newObject = [QSObject fileObjectWithPath:[dict objectForKey:@"NSApplicationPath"]];
} else {
// the process isn't an app
newObject = [QSObject fileObjectWithPath:[dict objectForKey:@"CFBundleExecutable"]];
}
}
[newObject setObject:dict forType:QSProcessType];
return newObject;
}
- (QSObject *)processObjectWithPSN:(ProcessSerialNumber)psn {
return [self processObjectWithPSN:psn fromSnapshot:NO];
}
- (QSObject *)processObjectWithPSN:(ProcessSerialNumber)psn fromSnapshot:(BOOL)snapshot {
NSDictionary *dict = (snapshot ? processesSnapshot : [self processesDict]);
pid_t pid;
GetProcessPID(&psn, &pid);
__block QSObject *matchedProcess = [dict objectForKey:[NSNumber numberWithInt:pid]];
if (matchedProcess) {
return matchedProcess;
}
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, QSObject *thisProcess, BOOL * _Nonnull stop) {
NSDictionary *info = [thisProcess objectForType:QSProcessType];
Boolean match;
ProcessSerialNumber thisPSN;
GetPSNForAppInfo(&thisPSN, info);
SameProcess(&psn, &thisPSN, &match);
if (match) {
*stop = YES;
matchedProcess = thisProcess;
}
}];
return matchedProcess;
}
- (QSObject *)processObjectWithDict:(NSDictionary *)dict {
ProcessSerialNumber psn;
if (noErr == GetPSNForAppInfo(&psn, dict) )
return [self processObjectWithPSN:psn];
return nil;
}
- (NSDictionary *)infoForApp:(NSRunningApplication *)app {
ProcessSerialNumber psn;
GetProcessForPID(app.processIdentifier, &psn);
NSDictionary *dict = [[NSDictionary dictionaryWithObjectsAndKeys:
[app localizedName], @"NSApplicationName",
[[app bundleURL] path], @"NSApplicationPath",
app.bundleIdentifier, @"NSApplicationBundleIdentifier",
[NSNumber numberWithInt:[app processIdentifier]], @"NSApplicationProcessIdentifier",
[NSNumber numberWithBool:(app.activationPolicy == NSApplicationActivationPolicyProhibited)], @"LSBackgroundOnly",
[NSNumber numberWithBool:(app.activationPolicy == NSApplicationActivationPolicyAccessory)], @"LSUIElement",
[NSNumber numberWithLong:psn.highLongOfPSN], @"NSApplicationProcessSerialNumberHigh",
[NSNumber numberWithLong:psn.lowLongOfPSN], @"NSApplicationProcessSerialNumberLow",
nil] mutableCopy];
return dict;
}
- (NSDictionary *)infoForPSN:(ProcessSerialNumber)processSerialNumber {
NSMutableDictionary *dict = [(NSDictionary *)CFBridgingRelease(ProcessInformationCopyDictionary(&processSerialNumber, kProcessDictionaryIncludeAllInformationMask)) mutableCopy];
[dict setValue:[dict objectForKey:@"CFBundleName"]
forKey:@"NSApplicationName"];
[dict setValue:[dict objectForKey:@"BundlePath"]
forKey:@"NSApplicationPath"];
[dict setValue:[dict objectForKey:@"CFBundleIdentifier"]
forKey:@"NSApplicationBundleIdentifier"];
[dict setValue:[dict objectForKey:@"pid"]
forKey:@"NSApplicationProcessIdentifier"];
[dict setValue:[NSNumber numberWithLong:processSerialNumber.highLongOfPSN]
forKey:@"NSApplicationProcessSerialNumberHigh"];
[dict setValue:[NSNumber numberWithLong:processSerialNumber.lowLongOfPSN]
forKey:@"NSApplicationProcessSerialNumberLow"];
dict = [dict copy];
return dict;
}
#pragma mark -
#pragma mark Process Notifications
- (BOOL)handleProcessEvent:(NSEvent *)theEvent {
ProcessSerialNumber psn;
psn.highLongOfPSN = (UInt32)[theEvent data1];
psn.lowLongOfPSN = (UInt32)[theEvent data2];
QSGCDQueueAsync(proc_thread, ^{
switch ([theEvent subtype]) {
case NSProcessDidLaunchSubType: {
[self appLaunched:psn];
break;
} case NSProcessDidTerminateSubType: {
[self appTerminated:psn];
break;
} case NSFrontProcessSwitched: {
[self appChanged:psn];
break;
}
default:
break;
}
});
return YES;
}
- (void)appLaunched:(ProcessSerialNumber)psn {
NSDictionary *dict = [self infoForPSN:psn];
// if we're including background processes (i.e. all processes) OR if it's a foreground process, reload
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QSShowBackgroundProcesses"] || ![[dict objectForKey:@"LSBackgroundOnly"] boolValue]) {
[self reloadProcesses];
}
if (dict) {
QSObject *procObject = [self imbuedFileProcessForDict:dict];
QSGCDMainAsync(^{
// This notif is used for the Events plugin 'Application Launched' event trigger
NSDictionary *userInfo = procObject ? [NSDictionary dictionaryWithObject:procObject forKey:@"object"] : nil;
[[NSNotificationCenter defaultCenter] postNotificationName:@"QSEventNotification" object:@"QSApplicationLaunchEvent" userInfo:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:QSProcessMonitorApplicationLaunched object:self userInfo:dict];
});
}
}
- (void)appTerminated:(ProcessSerialNumber)psn {
QSObject *processObject = [self processObjectWithPSN:psn];
if (processObject) {
NSDictionary *dict = [processObject objectForType:QSProcessType];
[self reloadProcesses];
QSGCDMainAsync(^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"QSEventNotification" object:@"QSApplicationQuitEvent" userInfo:[NSDictionary dictionaryWithObject:processObject forKey:@"object"]];
[[NSNotificationCenter defaultCenter] postNotificationName:QSProcessMonitorApplicationTerminated object:self userInfo:dict];
});
} else {
#ifdef DEBUG
if (psn.highLongOfPSN != 0) {
NSLog(@"No object found for process %u", (unsigned int)psn.highLongOfPSN);
}
#endif
}
}
- (void)appChanged:(ProcessSerialNumber)psn {
NSDictionary *dict = [[self processObjectWithPSN:psn] objectForType:QSProcessType];
QSGCDMainAsync(^{
[[NSNotificationCenter defaultCenter] postNotificationName:QSProcessMonitorFrontApplicationSwitched object:self userInfo:dict];
/* TODO: tiennou This doesn't belong here */
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSDictionary *newApp = [workspace activeApplication];
if ([[newApp objectForKey:@"NSApplicationBundleIdentifier"] isEqualToString:@"com.blacktree.Quicksilver"] && [[NSUserDefaults standardUserDefaults] boolForKey:kHideDockIcon]) {
return;
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"Hide Other Apps When Switching"]) {
if (!(GetCurrentKeyModifiers() & shiftKey) ) {
//if (VERBOSE) NSLog(@"Hide Other Apps");
[workspace hideOtherApplications:[NSArray arrayWithObject:newApp]];
}
}
[self setPreviousApplication:currentApplication];
[self setCurrentApplication:newApp];
});
}
#pragma mark -
#pragma mark Utilities
- (NSArray *)processesWithHiddenState:(BOOL)hidden {
NSArray *objs = [[self processesDict] allValues];
NSIndexSet *i = [objs indexesOfObjectsWithOptions:NSEnumerationConcurrent passingTest:^BOOL(QSObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSDictionary *infoDict = [obj objectForType:QSProcessType];
NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:[[infoDict objectForKey:@"NSApplicationProcessIdentifier"] intValue]];
if (!app) {
return NO;
}
BOOL isBackground = app.activationPolicy == NSApplicationActivationPolicyProhibited;
if (!hidden && isBackground) {
return NO;
}
if (hidden && !isBackground) {
return NO;
}
return YES;
}];
return [objs objectsAtIndexes:i];
}
- (void)reloadProcesses {
QSGCDQueueAsync(proc_thread, ^{
[self _reloadProcesses];
});
}
- (void)_reloadProcesses {
/* Mark us as reloading to prevent -addProcessWithPSN from sending one notification per found process, and handle KVO ourselves. */
[self willChangeValueForKey:@"visibleProcesses"];
[self willChangeValueForKey:@"backgroundProcesses"];
[self willChangeValueForKey:@"allProcesses"];
if (processes != nil) {
processesSnapshot = [processes copy];
}
#ifdef DEBUG
NSDate *date = [NSDate date];
#endif
NSArray *tempProcesses = [[NSWorkspace sharedWorkspace] runningApplications];
NSMutableDictionary *procs = [[NSMutableDictionary alloc] initWithCapacity:tempProcesses.count];
for (NSRunningApplication *app in tempProcesses) {
NSDictionary *info = [self infoForApp:app];
QSObject *procObject = [self imbuedFileProcessForDict:info];
NSNumber *pidValue = [NSNumber numberWithInt:app.processIdentifier];
if (procObject) {
[procs setObject:procObject forKey:pidValue];
}
}
processes = [procs copy];
#ifdef DEBUG
NSLog(@"Reload time: %f ms", [date timeIntervalSinceNow]*-1000);
#endif
[self didChangeValueForKey:@"allProcesses"];
[self didChangeValueForKey:@"backgroundProcesses"];
[self didChangeValueForKey:@"visibleProcesses"];
}
#pragma mark -
#pragma mark Proxies
- (id)resolveProxyObject:(id)proxy {
if ([[proxy identifier] isEqualToString:@"QSCurrentApplicationProxy"]) {
// NSLog(@"return");
return [self imbuedFileProcessForDict:[[NSWorkspace sharedWorkspace] activeApplication]];
} else if ([[proxy identifier] isEqualToString:@"QSPreviousApplicationProxy"]) {
return [self imbuedFileProcessForDict:previousApplication];
}
return nil;
}
- (NSTimeInterval) cacheTimeForProxy:(id)proxy {
return 0.0f;
}
#pragma mark -
#pragma mark Accessors
- (NSDictionary *)processesDict {
if (!processes) {
processes = [NSMutableDictionary dictionaryWithCapacity:1];
isReloading = YES;
[self reloadProcesses];
isReloading = NO;
}
return processes;
}
- (NSArray *)allProcesses {
return [[self processesDict] allValues];
}
- (NSArray *)getAllProcesses {
return [self allProcesses];
}
- (NSArray *)getVisibleProcesses {
return [self visibleProcesses];
}
- (NSArray *)visibleProcesses {
return [self processesWithHiddenState:NO];
}
- (NSArray *)backgroundProcesses {
return [self processesWithHiddenState:YES];
}
- (NSDictionary *)currentApplication {
return currentApplication;
}
- (void)setCurrentApplication:(NSDictionary *)newCurrentApplication {
if (currentApplication != newCurrentApplication) {
currentApplication = newCurrentApplication;
}
}
- (NSDictionary *)previousApplication {
return previousApplication;
}
- (void)setPreviousApplication:(NSDictionary *)newPreviousApplication {
if (previousApplication != newPreviousApplication) {
previousApplication = newPreviousApplication;
}
}
@end