-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSSYOtherApper.m
1213 lines (1063 loc) · 40.3 KB
/
SSYOtherApper.m
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "SSYOtherApper.h"
#import "SSYShellTasker.h"
#import "NSError+LowLevel.h"
#import "NSString+SSYExtraUtils.h"
#import "NSFileManager+SomeMore.h"
#import "NSRunningApplication+SSYHideReliably.h"
#import "NSError+InfoAccess.h"
#import "SSYAppleScripter.h"
NSString* const SSYOtherApperErrorDomain = @"SSYOtherApperErrorDomain" ;
NSString* const SSYOtherApperKeyPid = @"pid" ;
NSString* const SSYOtherApperKeyUser = @"user" ;
NSString* const SSYOtherApperKeyEtime = @"etime" ;
NSString* const SSYOtherApperKeyExecutable = @"executable" ;
@implementation SSYOtherApper
+ (pid_t)pidOfThisUsersAppWithBundleIdentifier:(NSString*)bundleIdentifier {
pid_t pid = 0 ; // not found
if (bundleIdentifier) {
// Running the main run loop is necessary for -runningApplications to
// update. The next line is actually necessary in tools which may be lacking
// a running run loop, and it actually works.
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]] ;
NSArray* runningApps = [[NSWorkspace sharedWorkspace] runningApplications] ;
for (NSRunningApplication* runningApp in runningApps) {
if ([[runningApp bundleIdentifier] isEqualToString:bundleIdentifier]) {
pid = [runningApp processIdentifier] ;
break ;
}
}
}
return pid ;
}
+ (pid_t)pidOfThisUsersAppWithBundlePath:(NSString*)bundlePath {
pid_t pid = 0 ; // not found
if (bundlePath) {
// Running the main run loop is necessary for -runningApplications to
// update. The next line is actually necessary in tools which may be lacking
// a running run loop, and it actually works.
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]] ;
NSArray* runningApplications = [[NSWorkspace sharedWorkspace] runningApplications] ;
for (NSRunningApplication* runningApp in runningApplications) {
NSURL* url = [runningApp bundleURL] ;
NSString* path = [url path] ;
if ([path isEqualToString:bundlePath]) {
pid = [runningApp processIdentifier] ;
break ;
}
}
}
return pid ;
}
+ (NSString*)pathOfThisUsersRunningAppWithBundleIdentifier:(NSString*)bundleIdentifier {
NSString* path = nil ;
if (bundleIdentifier) {
// Running the main run loop is necessary for -runningApplications to
// update. To my amazement, the next line is actually necessary, and
// it actually works.
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]] ;
NSArray* runningApps = [[NSWorkspace sharedWorkspace] runningApplications] ;
for (NSRunningApplication* runningApp in runningApps) {
if ([[runningApp bundleIdentifier] isEqualToString:bundleIdentifier]) {
path = [[runningApp bundleURL] path] ;
break ;
}
}
}
return path ;
}
+ (BOOL)launchApplicationPath:(NSString*)path
activate:(BOOL)activate
hideGuardTime:(NSTimeInterval)hideGuardTime
error_p:(NSError**)error_p {
NSMutableArray* arguments = [[NSMutableArray alloc] initWithObjects:
@"-a",
path,
nil];
if (!activate) {
[arguments addObject:@"-gj"];
/* I don't understand from the `man open` the reason for both -g and
-j. In macOS 10.14.2, -g is sufficient. I added -j for extra oomph,
since I've had so much trouble with this in the past (see
Apple Bug 19070101). */
}
NSTask* task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/open";
task.arguments = arguments;
#if !__has_feature(objc_arc)
[arguments release];
#endif
[task launch];
[task waitUntilExit];
NSInteger status = task.terminationStatus;
BOOL ok = (status == 0);
/* The following section is for apps such as Google Chrome which do not
seem to obey the -g or -j options of /usr/bin/open. */
if (!activate && ok && (hideGuardTime > 0.0)) {
dispatch_queue_t aSerialQueue = dispatch_queue_create(
"SSYOtherApper.HideLaunchedApp",
DISPATCH_QUEUE_SERIAL
);
dispatch_async(aSerialQueue, ^{
NSArray* runningApps = [[NSWorkspace sharedWorkspace] runningApplications];
NSMutableSet* appsToHide = [[NSMutableSet alloc] init];
for (NSRunningApplication* app in runningApps) {
NSString* executablePath = app.executableURL.path;
if ([executablePath hasPrefix:path]) {
[appsToHide addObject:app];
/* Don't break here because app could have helper executables
running, so we may have just hidden a helper. Instead, we
want to hide apps whose executablePath has prefix `path`. */
}
}
for (NSRunningApplication* app in appsToHide) {
[app hideReliablyWithGuardInterval:hideGuardTime];
}
#if !__has_feature(objc_arc)
[appsToHide release];
#endif
});
}
if (!ok && error_p) {
NSString* errorDesc;
id rawErrorDesc = task.standardError;
if ([rawErrorDesc isKindOfClass:[NSString class]]) {
errorDesc = rawErrorDesc;
} else {
errorDesc = [rawErrorDesc description];
if (![errorDesc isKindOfClass:[NSString class]]) {
errorDesc = @"Unknown Error";
}
}
*error_p = [NSError errorWithDomain:SSYOtherApperErrorDomain
code:398626
userInfo:@{
NSLocalizedDescriptionKey : errorDesc,
@"Path" : path
}];
}
#if !__has_feature(objc_arc)
[task release];
#endif
return ok ;
}
+ (NSImage*)iconForAppWithBundleIdentifier:(NSString*)bundleIdentifier {
NSString* path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:bundleIdentifier] ;
NSImage* answer ;
if (path) {
answer = [[NSWorkspace sharedWorkspace] iconForFile:path] ;
}
else {
answer = nil ;
}
return answer ;
}
+ (NSString*)fullPathForAppWithBundleIdentifier:(NSString*)bundleIdentifier {
NSString* fullPath = nil ;
if (bundleIdentifier) {
NSWorkspace* sharedWorkspace = [NSWorkspace sharedWorkspace] ;
fullPath = [sharedWorkspace absolutePathForAppBundleWithIdentifier:bundleIdentifier] ;
}
return fullPath ;
}
+ (NSArray*)pidsExecutablesFull:(BOOL)fullExecutablePath {
// Run unix task "ps" and get results as an array, with each element containing process command and user
// The invocation to be constructed is: ps -xa[c]awww -o pid -o user -o command
// -ww is required for long command path strings!!
NSData* stdoutData ;
NSString* options = fullExecutablePath ? @"-xaww" : @"-xacww" ;
NSArray* args = [[NSArray alloc] initWithObjects:options, @"-o", @"pid=", @"-o", @"etime=", @"-o", @"user=", @"-o", @"comm=", nil] ;
// In args, the "=" say to omit the column headers
[SSYShellTasker doShellTaskCommand:@"/bin/ps"
arguments:args
inDirectory:nil
stdinData:nil
stdoutData_p:&stdoutData
stderrData_p:NULL
timeout:5.0
error_p:NULL] ;
[args release] ;
NSMutableArray* processInfoDics = nil ;
if (stdoutData) {
NSString* processInfosString = [[NSString alloc] initWithData:stdoutData encoding:[NSString defaultCStringEncoding]] ;
NSArray* processInfoStrings = [processInfosString componentsSeparatedByString:@"\n"] ;
[processInfosString release] ;
/* We must now parse processInfoStrings which looks like this (with fullExecutablePath = NO):
* 1 root launchd
* 10 root kextd
* …
* 82 jk loginwindow
* 84 root KernelEventAgent
* …
* 30903 jk CrashReporter
* 32814 b Google Chrome
* …
* 48329 jk Google Chrome Helper
* 48330 jk Google Chrome Helper EH
* …
* 50253 root activitymonitord
* 53399 jk CocoaMySQL
* 53410 jk mdworker
* 53642 jk gdb-i386-apple-darwin
* 53651 jk BookMacster
* …
*/
processInfoDics = [[NSMutableArray alloc] init] ;
NSScanner* scanner = nil ;
for (NSString* processInfoString in processInfoStrings) {
NSInteger pid ;
NSString* user = nil ;
NSString* etimeString = nil ;
NSString* command ;
BOOL ok ;
scanner = [[NSScanner alloc] initWithString:processInfoString] ;
[scanner setCharactersToBeSkipped:nil] ;
// Scan leading whitespace, if any
[scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet]
intoString:NULL] ;
// Scan pid
ok = [scanner scanInteger:&pid] ;
if (!ok) {
[scanner release] ;
continue ;
}
// Scan whitespace between pid and etime
ok = [scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet]
intoString:NULL] ;
if (!ok) {
[scanner release] ;
continue ;
}
/*
Scan process elapsed time. I would have preferred to get the
start time using lstart or start rather than etime, but after a
half hour of research, decided that their formats were too
unpredictable to be parseable.
*/
[scanner scanCharactersFromSet:[[NSCharacterSet whitespaceCharacterSet] invertedSet]
intoString:&etimeString] ;
// Scan whitespace between etime and user
ok = [scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet]
intoString:NULL] ;
if (!ok) {
[scanner release] ;
continue ;
}
// Scan user. Fortunately, short user names in macOS cannot contain whitespace
[scanner scanCharactersFromSet:[[NSCharacterSet whitespaceCharacterSet] invertedSet]
intoString:&user] ;
// Scan whitespace between user and command
ok = [scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet]
intoString:NULL] ;
if (!ok) {
[scanner release] ;
continue ;
}
// Get command which is the remainder of the string
NSInteger commandBeginsAt = [scanner scanLocation] ;
[scanner release] ;
scanner = nil ;
command = [processInfoString substringFromIndex:commandBeginsAt] ;
NSDictionary* processInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInteger:pid], SSYOtherApperKeyPid,
user, SSYOtherApperKeyUser,
etimeString, SSYOtherApperKeyEtime,
command, SSYOtherApperKeyExecutable,
nil ] ;
[processInfoDics addObject:processInfoDic] ;
}
}
NSArray* result = [processInfoDics copy] ;
[processInfoDics release] ;
return [result autorelease] ;
}
+ (pid_t)pidOfMyRunningExecutableName:(NSString*)executableName {
pid_t pid = 0 ; // not found
NSString* targetUser = NSUserName() ;
for (NSDictionary* processInfoDic in [self pidsExecutablesFull:NO]) {
NSString* user = [processInfoDic objectForKey:SSYOtherApperKeyUser] ;
NSString* command = [processInfoDic objectForKey:SSYOtherApperKeyExecutable] ;
if ([targetUser isEqualToString:user] && [executableName isEqualToString:command]) {
pid = (pid_t)[[processInfoDic objectForKey:SSYOtherApperKeyPid] integerValue] ;
break ;
}
}
return pid ;
}
+ (NSArray*)pidsOfMyRunningExecutablesName:(NSString*)executableName
zombies:(BOOL)zombies
exactMatch:(BOOL)exactMatch {
// The following reverse-engineering emulates the way that ps presents
// an executable name when it is a zombie process:
NSString* zombifiedExecutableName ;
if (zombies) {
NSInteger length = executableName.length;
if (length > 16) {
length = 16;
}
zombifiedExecutableName = [NSString stringWithFormat:
@"(%@)",
[executableName substringToIndex:length]] ;
}
else {
zombifiedExecutableName = nil ;
}
NSMutableArray* pids = [[NSMutableArray alloc] init] ;
NSString* targetUser = NSUserName() ;
for (NSDictionary* processInfoDic in [self pidsExecutablesFull:NO]) {
NSString* user = [processInfoDic objectForKey:SSYOtherApperKeyUser] ;
NSString* command = [processInfoDic objectForKey:SSYOtherApperKeyExecutable] ;
if (command) {
if ([targetUser isEqualToString:user]) {
if (exactMatch) {
if (
(
[executableName isEqualToString:command]
||
[zombifiedExecutableName isEqualToString:command]
)
) {
NSNumber* pid = [processInfoDic objectForKey:SSYOtherApperKeyPid] ;
if (pid) { // Defensive programming
[pids addObject:pid] ;
}
}
} else {
if (
(
([command rangeOfString:executableName].location != NSNotFound)
||
([command rangeOfString:zombifiedExecutableName].location != NSNotFound)
)
) {
NSNumber* pid = [processInfoDic objectForKey:SSYOtherApperKeyPid] ;
if (pid) { // Defensive programming
[pids addObject:pid] ;
}
}
}
}
}
}
NSArray* answer = [pids copy] ;
[pids release] ;
return [answer autorelease] ;
}
+ (SSYOtherApperProcessState)stateOfPid:(pid_t)pid {
NSData* stdoutData ;
NSString* options = @"-xww" ;
NSString* pidString = [NSString stringWithFormat:@"%ld", (long)pid] ;
NSArray* args = [[NSArray alloc] initWithObjects:options, @"-o", @"state=", pidString, nil] ;
// In args, the "=" say to omit the column headers
[SSYShellTasker doShellTaskCommand:@"/bin/ps"
arguments:args
inDirectory:nil
stdinData:nil
stdoutData_p:&stdoutData
stderrData_p:NULL
timeout:5.0
error_p:NULL] ;
[args release] ;
SSYOtherApperProcessState processState ;
if ([stdoutData length] == 0) {
processState = SSYOtherApperProcessDoesNotExist ;
}
else {
NSString* stateString = [[NSString alloc] initWithData:stdoutData
encoding:[NSString defaultCStringEncoding]] ;
unichar firstChar = [stateString characterAtIndex:0] ;
switch (firstChar) {
case 'S' :
processState = SSYOtherApperProcessStateRunning ;
break ;
case 'U' :
processState = SSYOtherApperProcessStateWaiting ;
break ;
case 'I' :
processState = SSYOtherApperProcessStateIdle ;
break ;
case 'R' :
processState = SSYOtherApperProcessStateRunnable ;
break ;
case 'T' :
processState = SSYOtherApperProcessStateStopped ;
break ;
case 'Z' :
processState = SSYOtherApperProcessStateZombie ;
break ;
default :
processState = SSYOtherApperProcessUnknown ;
break ;
}
[stateString release] ;
}
return processState ;
}
+ (pid_t)pidOfProcessNamed:(NSString*)processName
user:(NSString*)user {
NSArray* infos = [self pidsExecutablesFull:NO] ;
pid_t pid = 0 ;
BOOL foundIt = NO ;
for (NSDictionary* info in infos) {
NSString* aPath = [info objectForKey:SSYOtherApperKeyExecutable] ;
if ([aPath isEqualToString:processName]) {
if (user) {
NSString* aUser = [info objectForKey:SSYOtherApperKeyUser] ;
if ([aUser isEqualToString:user] ) {
foundIt = YES ;
}
}
else {
foundIt = YES ;
}
if (foundIt) {
pid = (pid_t)[[info objectForKey:SSYOtherApperKeyPid] integerValue] ;
break ;
}
}
}
return pid ;
}
+ (NSSet*)infosOfProcessesNamed:(NSSet*)processNames
user:(NSString*)user {
NSArray* infos = [self pidsExecutablesFull:YES] ;
NSMutableSet* results = [[NSMutableSet alloc] init] ;
for (NSString* processName in processNames) {
for (NSDictionary* info in infos) {
NSString* aPath = [info objectForKey:SSYOtherApperKeyExecutable] ;
if ([aPath rangeOfString:processName].location != NSNotFound) {
if (user) {
NSString* aUser = [info objectForKey:SSYOtherApperKeyUser] ;
if ([aUser isEqualToString:user] ) {
[results addObject:info] ;
}
}
else {
[results addObject:info] ;
}
}
}
}
NSSet* answer = [results copy] ;
[results release] ;
[answer autorelease] ;
return answer ;
}
+ (BOOL)quitThisUsersAppWithBundlePath:(NSString*)bundlePath
closeWindows:(BOOL)closeWindows
wasRunning_p:(BOOL*)wasRunning_p
error_p:(NSError**)error_p {
NSError* error = nil ;
// Because AppleScript 'tell application' will *launch* an app if it is not
// running, we do one last test first. Of course, this still leaves a little
// window, a race condition, in which the app might quit and we relaunch it
// a millisecond later, but at least this will reduce the probability of
// that happening, and a quick launch/quit is not the end of the world.
// I don't know how to do any better.
BOOL isRunning = [self pidOfThisUsersAppWithBundlePath:bundlePath] != 0 ;
if (wasRunning_p) {
*wasRunning_p = isRunning ;
}
BOOL ok = YES ;
if (isRunning) {
NSString* source = [NSString stringWithFormat:
@"tell application \"%@\"\n",
bundlePath] ;
if (closeWindows) {
/* We enclose 'close windows' in a 'try' block because some apps,
such as iCab 6 running in macOS 10.11.2, throw an AppleScript
error when told to 'close windows'. */
source = [source stringByAppendingString:@"try\nclose windows\nend try\n"] ;
}
source = [source stringByAppendingString:@"quit\nend tell"] ;
BOOL __block ok;
[SSYAppleScripter executeScriptSource:source
ignoreKeyPrefix:nil
userInfo:nil
blockUntilCompletion:YES
failSafeTimeout:16.666
completionHandler:^(id _Nullable payload, id _Nullable userInfo, NSError * _Nullable scriptError) {
ok = (error == nil);
}];
}
if (error_p && error) {
*error_p = error ;
}
return ok ;
}
+ (NSString*)descriptionOfPid:(pid_t)pid {
NSArray* args = [NSArray arrayWithObjects:
@"-www", // Allow 4x the normal column width. Should be enough!!
@"-o", // Print the following column (= means to suppress header line)
@"command=", // command and arguments
@"-o", // Print the following column (= means to suppress header line)
@"stime=", // time started
@"-o", // Print the following column (= means to suppress header line)
@"etime=", // elapsed running time
@"-o", // Print the following column (= means to suppress header line)
@"uid=", // effective user id
@"-o", // Print the following column (= means to suppress header line)
@"user=", // user name (from UID)
@"-o", // Print the following column (= means to suppress header line)
@"ruid=", // real user id
@"-o", // Print the following column (= means to suppress header line)
@"%cpu=", // percentage of CPU usage
@"-p", // subject pid follows
[NSString stringWithFormat:@"%ld", (long)pid],
nil] ;
NSString* answer = nil ;
NSData* stdoutData ;
[SSYShellTasker doShellTaskCommand:@"/bin/ps"
arguments:args
inDirectory:nil
stdinData:nil
stdoutData_p:&stdoutData
stderrData_p:NULL
timeout:5.0
error_p:NULL] ;
if (stdoutData) {
answer = [[NSString alloc] initWithData:stdoutData
encoding:NSUTF8StringEncoding] ;
[answer autorelease] ;
}
if ([answer length] == 0) {
answer = nil ;
}
answer = [answer stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] ;
return answer ;
}
+ (NSString*)humanReadableElapsedRunningTimeOfPid:(pid_t)pid {
NSArray* args = [NSArray arrayWithObjects:
@"-www", // Allow 4x the normal column width. Should be enough!!
@"-o", // Print the following column (= means to suppress header line)
@"etime=", // elapsed running time
@"-p", // subject pid follows
[NSString stringWithFormat:@"%ld", (long)pid],
nil] ;
NSString* answer = nil ;
NSData* stdoutData ;
[SSYShellTasker doShellTaskCommand:@"/bin/ps"
arguments:args
inDirectory:nil
stdinData:nil
stdoutData_p:&stdoutData
stderrData_p:NULL
timeout:5.0
error_p:NULL] ;
if (stdoutData) {
NSString* raw = [[NSString alloc] initWithData:stdoutData
encoding:NSUTF8StringEncoding];
/* raw can be one of several forms. Here is what I got in
macOS 10.14.2, 2018-12-29:
02-02:57:50 means 2 days, 2 hours, 57 minutes and 50 seconds
19:29 means 19 minutes and 29 seconds
00:22 means 0 minutes and 22 seconds */
NSString* trimmed = [raw stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[raw release];
NSArray* comps = [trimmed componentsSeparatedByString:@"-"];
NSString* days;
NSString* hms;
if (comps.count > 1) {
days = [comps objectAtIndex:0];
hms = [comps objectAtIndex:1];
} else {
days = nil;
hms = [comps objectAtIndex:0];
}
comps = [hms componentsSeparatedByString:@":"];
NSString* hours;
NSString* minutes;
NSString* seconds;
if (comps.count > 2) {
hours = [comps objectAtIndex:0];
minutes = [comps objectAtIndex:1];
seconds = [comps objectAtIndex:0];
} else if (comps.count > 1) {
hours = nil;
minutes = [comps objectAtIndex:0];
seconds = [comps objectAtIndex:1];
} else {
hours = nil;
minutes = nil;
seconds = [comps objectAtIndex:0];
}
if (hours.integerValue == 0) {
/* This branch will never occur with the year 2018 implementation
of `ps` because 0 hours are omitted. But just in case. */
hours = nil;
}
if (minutes.integerValue == 0) {
/* This branch *will* occur with the year 2018 implementation
of `ps` because 0 minutes are returned by `ps` as "00". */
minutes = nil;
}
NSMutableString* string = [[NSMutableString alloc] init];
if (days) {
[string appendString:days];
[string appendString:@" dayss"];
}
if (hours) {
if (string.length > 0) {
[string appendString:@" "];
}
[string appendString:hours];
[string appendString:@" hours"];
}
if (minutes) {
if (string.length > 0) {
[string appendString:@" "];
}
[string appendString:minutes];
[string appendString:@" minutes"];
}
if (seconds) {
if (string.length > 0) {
[string appendString:@" "];
}
[string appendString:seconds];
[string appendString:@" seconds"];
}
answer = [string copy];
[string release];
}
[answer autorelease];
return answer ;
}
+ (BOOL)isProcessRunningPid:(pid_t)pid
thisUserOnly:(BOOL)thisUserOnly {
BOOL answer = NO ;
NSArray* args ;
if (thisUserOnly) {
args = [NSArray arrayWithObjects:
@"-x",
@"-o", // Print the following column(s)
@"pid=", // = means to suppress header line
nil] ;
}
else {
args = [NSArray arrayWithObjects:
@"-x",
@"-a", // All users
@"-o", // Print the following column(s)
@"pid=", // = means to suppress header line
nil] ;
}
NSData* stdoutData ;
[SSYShellTasker doShellTaskCommand:@"/bin/ps"
arguments:args
inDirectory:nil
stdinData:nil
stdoutData_p:&stdoutData
stderrData_p:NULL
timeout:5.0
error_p:NULL] ;
if (stdoutData) {
NSString* pidsString = [[NSString alloc] initWithData:stdoutData
encoding:NSUTF8StringEncoding] ;
NSArray* pidStrings = [pidsString componentsSeparatedByString:@"\n"] ;
[pidsString release] ;
for (NSString* pidString in pidStrings) {
// The members of pidStrings which are less than 5 digits long
// have leading whitespaces so that the columns are right-justified.
// Of course, that might change.
// I hope that using the -[NSString intValue] will give a fairly
// robust and future-proof reading…
if ((pid_t)[pidString integerValue] == pid) {
answer = YES ;
break ;
}
}
}
return answer ;
}
+ (BOOL)isProcessRunningPid:(pid_t)pid
logAs:(NSString*)logAs {
BOOL answer = NO ;
// There is a bug in -launchedApplications. Sometimes, after an app such
// as "com.google.Chrome" quits, it still keeps showing up on repeated invocations
// of -launchedApplications. So we need to check and see if it is *really*
// still running before setting answer to YES.
if (pid > 0) {
answer = [self isProcessRunningPid:pid
thisUserOnly:YES] ;
if (!answer && logAs) {
NSLog(@"NSWorkspace says %@ running. But I can't find its pid %ld. Ignoring stupid NSWorkspace.", logAs, (long)pid) ;
}
}
return answer ;
}
+ (BOOL)isThisUsersAppRunningWithBundleIdentifier:(NSString*)bundleIdentifier {
pid_t pid = [self pidOfThisUsersAppWithBundleIdentifier:bundleIdentifier] ;
return [self isProcessRunningPid:pid
logAs:[bundleIdentifier pathExtension]] ;
}
+ (BOOL)isThisUsersAppRunningWithBundlePath:(NSString*)bundlePath {
if (!bundlePath) {
return NO ;
}
pid_t pid = [self pidOfThisUsersAppWithBundlePath:bundlePath] ;
return [self isProcessRunningPid:pid
logAs:[bundlePath lastPathComponent]] ;
}
+ (BOOL)quitThisUsersAppWithBundlePath:(NSString*)bundlePath
closeWindows:(BOOL)closeWindows
timeout:(NSTimeInterval)timeout
killAfterTimeout:(BOOL)killAfterTimeout
wasRunning_p:(BOOL*)wasRunning_p
error_p:(NSError**)error_p {
NSError* error = nil ;
BOOL ok = YES ;
BOOL wasRunning = NO ;
if (!bundlePath) {
goto end ;
}
NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:timeout] ;
#if 0
#warning Feigning Quitting 1
#else
ok = [self quitThisUsersAppWithBundlePath:bundlePath
closeWindows:closeWindows
wasRunning_p:&wasRunning
error_p:&error] ;
#endif
if (!ok) {
// Supposedly no chance that it will quit, so give up immediately.
goto end ;
}
// The following test was added in BookMacster 1.13.6. No need to wait
// for quitting if the app was not running to begin with.
if (wasRunning) {
NSInteger nTries = 1 ;
while (YES) {
// No app is likely to quit in less than 1 second, so we sleep *first*
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]] ;
// and *then* check if it's running
if (![self isThisUsersAppRunningWithBundlePath:bundlePath]) {
goto end ;
}
if ([(NSDate*)[NSDate date] compare:endDate] == NSOrderedDescending) {
// Timed out
if (killAfterTimeout) {
pid_t pid = [self pidOfThisUsersAppWithBundlePath:bundlePath] ;
if (pid != 0) {
kill(pid, SIGKILL) ;
}
goto end ;
}
ok = NO ;
NSString* desc = [NSString stringWithFormat:
@"Asked %@ nicely (via AppleScript) to quit %ld times in %g seconds, but it's still running.",
bundlePath,
(long)nTries,
timeout] ;
NSString* sugg = @"Try to activate and quit it yourself." ;
error = [NSError errorWithDomain:SSYOtherApperErrorDomain
code:494987
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
desc, NSLocalizedDescriptionKey,
sugg, NSLocalizedRecoverySuggestionErrorKey,
nil]] ;
goto end ;
}
}
}
end:
if (wasRunning_p) {
*wasRunning_p = wasRunning ;
}
if (error && error_p) {
*error_p = error ;
}
return ok ;
}
/*
+ (void)killProcessPID:(pid_t)pid
waitUntilExit:(BOOL)wait {
if (pid) {
NSArray* args = [[NSArray alloc] initWithObjects: @"-9", [NSString stringWithFormat:@"%i", pid], nil] ;
[SSYShellTasker doShellTaskCommand:@"/bin/kill"
arguments:args
inDirectory:nil
stdinData:nil
stdoutData_p:NULL
stderrData_p:NULL
waitUntilExit:YES
error_p:NULL] ;
}
}
*/
/* The following two methods, written during different years, could be
refactored to use some common code, if one would want to do the testing. */
+ (BOOL)killThisUsersProcessWithPid:(pid_t)pid
sig:(int)sig
timeout:(NSTimeInterval)timeout {
NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:timeout] ;
if (pid != 0) {
kill(pid, sig) ;
while (YES) {
if (![self isProcessRunningPid:pid
logAs:nil]) {
return YES ;
}
if ([(NSDate*)[NSDate date] compare:endDate] == NSOrderedDescending) {
return NO ;
}
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]] ;
}
}
/* We return YES because, due to the infinite `while(YES)` above, the only
way we could get here is if the passed-in pid == 0 */
return YES;
}
+ (BOOL)killThisUsersAppWithBundleIdentifier:(NSString*)bundleIdentifier
timeout:(NSTimeInterval)timeout {
if (!bundleIdentifier) {
return YES ;
}
NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:timeout] ;
pid_t pid = [self pidOfThisUsersAppWithBundleIdentifier:bundleIdentifier] ;
if (pid != 0) {
kill(pid, SIGKILL) ;
while (YES) {
if (![self isThisUsersAppRunningWithBundleIdentifier:bundleIdentifier]) {
return YES ;
}
if ([(NSDate*)[NSDate date] compare:endDate] == NSOrderedDescending) {
return NO ;
}
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]] ;
}
}
/* We return YES because, due to the infinite `while(YES)` above, the only
way we could get here is if pid == 0, which means the relevant app is
not running. */
return YES ;
}
+ (NSString*)applicationPathForUrl:(NSURL*)url {
CFErrorRef error = nil ;
CFURLRef appUrl = LSCopyDefaultApplicationURLForURL((CFURLRef)url,
kLSRolesViewer,
&error
) ;
NSString* path = [(NSURL*)appUrl path] ;
if (appUrl) {
CFRelease(appUrl) ;
}
return path ;
}
+ (NSString*)nameOfDefaultWebBrowser {
NSURL* url = [NSURL URLWithString:@"http://apple.com"] ;
NSString *path = [self applicationPathForUrl: url];
NSString* name = [path stringByDeletingPathExtension] ;
name = [[name pathComponents] lastObject] ;
return name ;
}
+ (NSString*)nameOfDefaultEmailClient {
NSURL* url = [NSURL URLWithString:@"mailto://[email protected]"] ;
NSString *path = [self applicationPathForUrl: url] ;
NSString* name = [path stringByDeletingPathExtension] ;
name = [[name pathComponents] lastObject] ;
return name ;
}
+ (NSString*)bundleIdentifierOfDefaultEmailClient {
NSURL* url = [NSURL URLWithString:@"mailto://[email protected]"] ;
NSString *path = [self applicationPathForUrl: url] ;
NSBundle* bundle = [NSBundle bundleWithPath:path] ;
NSString* bundleIdentifier = [bundle bundleIdentifier] ;
return bundleIdentifier ;
}
+ (BOOL)processPid:(pid_t)pid
timeout:(NSTimeInterval)timeout
cpuPercent_p:(CGFloat*)cpuPercent_p
error_p:(NSError**)error_p {
NSInteger errorCode = 0 ;
NSInteger psReturnValue = 0 ;
NSString* psErrorString = nil ;
NSString* errorDescription = nil ;
NSString* pidString = [NSString stringWithFormat:@"%i", pid] ;
NSArray* args = [NSArray arrayWithObjects:
@"-x", // include processes which do not have a controlling terminal
@"-p", // include only the process with the following pid
pidString,