-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tasks.m
741 lines (569 loc) · 21.3 KB
/
Tasks.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
//
// Tasks.m
//
#import "MySVN.h"
#import "Tasks.h"
#import "NSString+MyAdditions.h"
#import "CommonUtils.h"
// This file was patched by Yuichi Fujishige to provide better support for UTF-16 filenames. (0.9.6)
//----------------------------------------------------------------------------------------
// Task dictionary object accessors
BOOL
isCompleted (TaskObj* taskObj)
{
return [[taskObj objectForKey: @"status"] isEqualToString: @"completed"];
}
//----------------------------------------------------------------------------------------
NSString*
stdErr (TaskObj* taskObj)
{
NSString* str = [taskObj objectForKey: @"stderr"];
return (str && [str length] != 0) ? str : nil;
}
//----------------------------------------------------------------------------------------
NSString*
stdOut (TaskObj* taskObj)
{
return [taskObj objectForKey: @"stdout"];
}
//----------------------------------------------------------------------------------------
NSData*
stdOutData (TaskObj* taskObj)
{
return [taskObj objectForKey: @"stdoutData"];
}
//----------------------------------------------------------------------------------------
id
callbackInfo (TaskObj* taskObj)
{
return [taskObj objectForKey: @"callbackInfo"];
}
//----------------------------------------------------------------------------------------
#pragma mark -
//----------------------------------------------------------------------------------------
enum {
kLogLevelNone = 0,
kLogLevelError = 1,
kLogLevelGlobal = 2,
kLogLevelLocal = 3,
kLogLevelAll = 99
};
@implementation Tasks
static Tasks* gTasks = nil;
static NSDictionary* gTextStyleStd = nil, *gTextStyleErr = nil;
static int gLogLevel = kLogLevelAll;
//----------------------------------------------------------------------------------------
- (id) init
{
Assert(gTasks == nil);
gTasks = self;
if (gTextStyleStd == nil)
{
NSFont* txtFont = [NSFont fontWithName: @"Courier" size: 11];
gTextStyleStd = [[NSDictionary dictionaryWithObjectsAndKeys:
txtFont, NSFontAttributeName,
[NSColor blackColor], NSForegroundColorAttributeName,
nil] retain];
gTextStyleErr = [[NSDictionary dictionaryWithObjectsAndKeys:
txtFont, NSFontAttributeName,
[NSColor redColor], NSForegroundColorAttributeName,
nil] retain];
}
id loggingLevel = GetPreference(@"loggingLevel");
gLogLevel = loggingLevel ? [loggingLevel intValue] : kLogLevelAll;
return self;
}
//----------------------------------------------------------------------------------------
- (void) awakeFromNib
{
[tasksAC addObserver: self forKeyPath: @"selection.newStdout" options: NSKeyValueObservingOptionNew context: nil];
[tasksAC addObserver: self forKeyPath: @"selection.newStderr" options: NSKeyValueObservingOptionNew context: nil];
}
//----------------------------------------------------------------------------------------
// This is an optimized way to display the log output. The incoming data is directly appended to
// NSTextView's textstorage (see NSTextView+MyAdditions.m).
// With a classical binding, NSTextView would have to redisplay its content each time...
- (void) observeValueForKeyPath: (NSString*) keyPath
ofObject: (id) object
change: (NSDictionary*) change
context: (void*) context
{
#pragma unused(object, change, context)
NSArray* selectedTasks = [tasksAC selectedObjects];
if ([selectedTasks count] == 1)
{
NSDictionary* taskObj = [selectedTasks lastObject];
if (taskObj != currentTaskObj) // the selection must have changed
{
[[logTextView textStorage] setAttributedString: [taskObj objectForKey: @"combinedLog"]];
currentTaskObj = taskObj;
}
else if ([keyPath isEqualToString: @"selection.newStdout"])
{
if (gLogLevel >= kLogLevelGlobal)
[logTextView appendString: [taskObj objectForKey: @"newStdout"] isErrorStyle: NO];
}
else
{
if (gLogLevel >= kLogLevelError)
[logTextView appendString: [taskObj objectForKey: @"newStderr"] isErrorStyle: YES];
}
}
else
{
[logTextView setString: @""];
currentTaskObj = nil;
}
}
//----------------------------------------------------------------------------------------
#pragma mark IB Actions
//----------------------------------------------------------------------------------------
- (IBAction) stopTask: (id) sender
{
#pragma unused(sender)
const BOOL altPressed = AltOrShiftPressed();
for_each_obj(en, taskObj, [tasksAC arrangedObjects])
{
[MySvn killTask: taskObj force: altPressed];
}
}
//----------------------------------------------------------------------------------------
- (IBAction) clearCompleted: (id) sender
{
#pragma unused(sender)
for_each_obj(en, taskObj, [NSArray arrayWithArray: [tasksAC arrangedObjects]])
{
if (![[taskObj objectForKey: @"canBeKilled"] boolValue]) // tasks that can't be killed are already killed :-)
{
[tasksAC removeObject: taskObj];
}
}
}
//----------------------------------------------------------------------------------------
#pragma mark Helpers
//----------------------------------------------------------------------------------------
- (void) invokeCallBackForTask: (id) taskObj
{
NSInvocation* callback = [[[taskObj objectForKey: @"callback"] retain] autorelease];
[taskObj removeObjectForKey: @"callback"];
id status = @"completed";
if ( ![[taskObj objectForKey: @"status"] isEqualToString: @"error"] )
{
int exitCode = 0;
if ( ![[taskObj objectForKey: @"task"] isRunning] )
exitCode = [[taskObj objectForKey: @"task"] terminationStatus];
[taskObj setValue: [NSNumber numberWithInt: exitCode] forKey: @"exitCode"];
// in case taskCompleted is late, which is likely, we set status value here too
if (exitCode)
status = @"stopped";
}
if (stdErr(taskObj))
status = @"error";
[taskObj setValue: status forKey: @"status"];
[taskObj setValue: kNSFalse forKey: @"canBeKilled"];
[[taskObj objectForKey: @"handle"] closeFile];
[[taskObj objectForKey: @"errorHandle"] closeFile];
// see file://localhost/Developer/ADC%20Reference%20Library/documentation/Cocoa/Conceptual/DistrObjects/Tasks/invocations.html
[callback setArgument: &taskObj atIndex: 2]; // index 2 because of the two hidden default arguments (see NSInvocation doc).
if ( [callback target] )
{
[callback invoke]; // target may have been cancelled by cancelCallbacksOnTarget
[callback setTarget: nil];
}
}
//----------------------------------------------------------------------------------------
- (NSMutableAttributedString*) appendString: (NSString*) string
toAttributedString: (NSMutableAttributedString*) otherString
errorStyle: (BOOL) isError
{
NSDictionary* txtDict = isError ? gTextStyleErr : gTextStyleStd;
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString: string attributes: txtDict];
[otherString appendAttributedString: attrStr];
[attrStr release];
return otherString;
}
//----------------------------------------------------------------------------------------
- (void) taskIsDone: (TaskObj*) taskObj
{
// we want to make sure the callback will not be called twice (by the stdout finishing, and by the stderr)
// so we need a lock. Moreover, stderr can finish first. So we want both to be finished before we call the callback.
NSLock* taskLock = [taskObj objectForKey: @"lock"];
[taskLock lock];
if ([[taskObj valueForKey: @"otherStdDone"] boolValue])
[self invokeCallBackForTask: taskObj];
else
[taskObj setValue: kNSTrue forKey: @"otherStdDone"];
[taskLock unlock];
}
//----------------------------------------------------------------------------------------
- (void) stdoutDataAvailable: (NSNotification*) aNotification
{
[self taskDataAvailable: aNotification isError: NO];
}
//----------------------------------------------------------------------------------------
- (void) stderrDataAvailable: (NSNotification*) aNotification
{
[self taskDataAvailable: aNotification isError: YES];
}
//----------------------------------------------------------------------------------------
#pragma mark Control
//----------------------------------------------------------------------------------------
- (void) newTaskWithDictionary: (TaskObj*) taskObj
{
NSTask* task = [taskObj objectForKey: @"task"];
NSFileHandle* handle = [taskObj objectForKey: @"handle"];
NSFileHandle* errorHandle = [taskObj objectForKey: @"errorHandle"];
[taskObj setValue: [NSMutableString string] forKey: @"stdout"];
[taskObj setValue: [NSString string] forKey: @"newStdout"]; // will contain the incoming chunk to be appended to stdout
[taskObj setValue: [NSMutableString string] forKey: @"stderr"];
[taskObj setValue: [NSString string] forKey: @"newStderr"]; // see above
[taskObj setValue: [NSDate date] forKey: @"date"];
[taskObj setValue: [NSMutableData data] forKey: @"stdoutData"]; // row stdout data
const id combinedLog = [[NSMutableAttributedString alloc] initWithString: @"" attributes: gTextStyleStd];
[taskObj setValue: combinedLog forKey: @"combinedLog"];
[combinedLog release];
[taskObj setValue: kNSTrue forKey: @"canBeKilled"];
[taskObj setObject: [[[NSLock alloc] init] autorelease] forKey: @"lock"];
[tasksAC addObject: taskObj];
NSNotificationCenter* notifier = [NSNotificationCenter defaultCenter];
[notifier addObserver: self selector: @selector(stdoutDataAvailable:)
name: NSFileHandleReadCompletionNotification object: handle];
[notifier addObserver: self selector: @selector(stderrDataAvailable:)
name: NSFileHandleReadCompletionNotification object: errorHandle];
[notifier addObserver: self selector: @selector(taskCompleted:)
name: NSTaskDidTerminateNotification object: task];
// [activityWindow makeKeyAndOrderFront: self];
// [logDrawer open];
[handle readInBackgroundAndNotify];
[errorHandle readInBackgroundAndNotify];
@try
{
[task launch];
}
@catch (id exception)
{
dprintf("%@ %@\n CAUGHT %@", [task launchPath], [task arguments], exception);
if ([exception name] == NSInvalidArgumentException)
{
[taskObj setValue: [NSString stringWithFormat: @"Problem launching svn binary.\n"
"Make sure an svn binary is present at path:\n"
"'%@'.\nIs Subversion client installed?"
" If so, make sure the path is properly set in the preferences.",
[task launchPath]]
forKey: @"stderr"];
[taskObj setValue: @"error" forKey: @"status"];
[self invokeCallBackForTask: taskObj];
}
}
}
//----------------------------------------------------------------------------------------
// Unicode (Hex) Binary UTF-8 Format Legal UTF-8 Values (Hex)
// 0000-007F 0xxxxxxx 00-7F
// 0080-07FF 110yyyxx 10xxxxxx C2-DF 80-BF
// 0800-FFFF 1110yyyy 10yyyyxx 10xxxxxx E0 A0-BF 80-BF & E1-EF 80-BF 80-BF
// 10000-10FFFF 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx F0 90-BF 80-BF 80-BF & F1-F7 80-BF 80-BF 80-BF
- (void) taskDataAvailable: (NSNotification*) aNotification
isError: (BOOL) isError
{
NSData* const incomingData = [[aNotification userInfo] objectForKey: NSFileHandleNotificationDataItem];
NSFileHandle* const taskHandle = [aNotification object];
BOOL found = NO,
doLog = (gLogLevel > kLogLevelNone);
NSString* const key = isError ? @"errorHandle" : @"handle";
NSEnumerator *e = [[tasksAC arrangedObjects] objectEnumerator];
TaskObj* taskObj;
while ( taskObj = [e nextObject] )
{
if ( taskHandle == [taskObj objectForKey: key] )
{
found = YES;
break;
}
}
if (!found)
;
else if ( incomingData && [incomingData length] )
{
NSLock* const taskLock = [taskObj objectForKey: @"lock"];
NSString *string = nil;
if ( isError )
{
if (gLogLevel >= kLogLevelError)
{
// As LANG environment variable set to "en_US.UTF-8", error messages will be English only.
// We don't have to modify incomingData.
string = [[NSString alloc] initWithData: incomingData encoding: NSUTF8StringEncoding];
[taskLock lock]; // I'm not sure about the need for a lock here
NSMutableString *currentStderr = [taskObj objectForKey: @"stderr"];
[taskObj willChangeValueForKey: @"stderr"]; // there is currently no observer, but there could be in the future
[currentStderr appendString: string];
[taskObj didChangeValueForKey: @"stderr"];
[taskObj setValue: string forKey: @"newStderr"]; // this key is observed. This will trigger this new
// chunk to be appended directly in the NSTextView log
[taskLock unlock];
}
}
else
{
NSMutableData *restRowStdoutData = [taskObj objectForKey: @"stdoutData"];
NSMutableData *tmpIncomingData;
if (restRowStdoutData == nil)
{
tmpIncomingData = [NSMutableData dataWithData: incomingData];
}
else if ([taskObj objectForKey: @"outputToData"] == kNSTrue)
{
[restRowStdoutData appendData: incomingData];
doLog = NO;
}
else
{
tmpIncomingData = [NSMutableData dataWithData: restRowStdoutData];
[tmpIncomingData appendData: incomingData];
[taskLock lock];
[taskObj setValue: nil forKey: @"stdoutData"];
[taskLock unlock];
}
if (doLog)
{
const unsigned char* tmpIncomingDataBytes = (const unsigned char*)[tmpIncomingData bytes];
const unsigned int incominDataLength = [tmpIncomingData length];
unsigned int offset = incominDataLength - 1;
if (tmpIncomingDataBytes[offset] & 0x80)
{
int noFirstBytesLength = 0;
while (offset && (tmpIncomingDataBytes[offset] & 0xC0) == 0x80)
{
++noFirstBytesLength;
--offset;
}
int excessLength = noFirstBytesLength + 1;
NSData* excessData = [NSData dataWithBytes: (tmpIncomingDataBytes + incominDataLength - excessLength)
length: excessLength];
//NSLog(@"excessData:%@", excessData);
[tmpIncomingData setLength: incominDataLength - excessLength];
// incomingData = tmpIncomingData;
[taskLock lock];
[taskObj setValue: excessData forKey: @"stdoutData"];
[taskLock unlock];
}
string = [[NSString alloc] initWithData: tmpIncomingData encoding: NSUTF8StringEncoding];
Assert(string != nil); // stdin incomingData failed to convert
[taskLock lock];
NSMutableString* currentStdout = [taskObj objectForKey: @"stdout"];
[taskObj willChangeValueForKey: @"stdout"];
[currentStdout appendString: string];
[taskObj didChangeValueForKey: @"stdout"];
[taskObj setValue: string forKey: @"newStdout"];
[taskLock unlock];
}
}
if (doLog && gLogLevel >= kLogLevelGlobal)
{
NSMutableAttributedString* combinedLog = [taskObj objectForKey: @"combinedLog"]; // this is the combined log
[taskObj willChangeValueForKey: @"combinedLog"];
[self appendString: string toAttributedString: combinedLog errorStyle: isError]; // errors are appended in red
[taskObj didChangeValueForKey: @"combinedLog"];
}
if ([[taskObj valueForKey: @"status"] isEqualToString: @"stopped"]) // set in taskCompleted
{
[self taskIsDone: taskObj];
}
else
{
[taskHandle readInBackgroundAndNotify];
}
[string release];
}
else // We're finished with the task
{
[self taskIsDone: taskObj];
}
}
//----------------------------------------------------------------------------------------
// IMPORTANT : taskCompleted may be called before the task's output is totally read !
// This is the reason why the callback should be called from taskDataAvailable, when an empty NSData is finally returned;
- (void) taskCompleted: (NSNotification*) aNotification
{
NSTask* notifTask = [aNotification object];
NSEnumerator* e = [[tasksAC arrangedObjects] objectEnumerator];
TaskObj* taskObj;
BOOL found = NO;
while (taskObj = [e nextObject])
{
if (notifTask == [taskObj objectForKey: @"task"])
{
found = YES;
break;
}
}
if (found)
{
int exitCode = [[aNotification object] terminationStatus];
id status = stdErr(taskObj) ? @"error" : (exitCode ? @"stopped" : @"completed");
[taskObj setValue: status forKey: @"status"];
[taskObj setValue: kNSFalse forKey: @"canBeKilled"];
[taskObj setValue: [NSNumber numberWithInt: exitCode] forKey: @"exitCode"];
}
}
//----------------------------------------------------------------------------------------
+ (void) addTask: (TaskObj*) taskObj
{
Assert(gTasks != nil);
[gTasks newTaskWithDictionary: taskObj];
}
//----------------------------------------------------------------------------------------
// This is called from the target, before it's closed, because a callback on a closing target is likely to crash.
// The task is not stopped, though.
+ (void) cancelCallbacksOnTarget: (id) target
{
Assert(gTasks != nil);
NSNull* const nsNull = [NSNull null];
for_each_obj(en, callback, [[gTasks->tasksAC arrangedObjects] valueForKey: @"callback"])
{
if (callback != nsNull && target == [callback target])
{
[callback setTarget: nil];
}
}
}
@end // Tasks
//----------------------------------------------------------------------------------------
#pragma mark -
//----------------------------------------------------------------------------------------
@implementation Task
//----------------------------------------------------------------------------------------
// Create a default environment dictionary for each & every task
+ (NSMutableDictionary*) createEnvironment: (BOOL) isUnbuffered
{
// If there's a 'TaskEnvironment' dict in the plist then add its elements to the Task's environment.
static id kTaskEnvironment = nil;
static BOOL inited = FALSE;
if (!inited)
{
inited = TRUE;
kTaskEnvironment = [[NSBundle mainBundle] objectForInfoDictionaryKey: @"TaskEnvironment"];
if (![kTaskEnvironment isKindOfClass: [NSDictionary class]])
kTaskEnvironment = nil;
}
NSMutableDictionary* env = [NSMutableDictionary dictionaryWithDictionary:
[[NSProcessInfo processInfo] environment]];
if (isUnbuffered)
[env setObject: @"YES" forKey: @"NSUnbufferedIO"];
// [env setObject: @"en_US.UTF-8" forKey: @"LC_CTYPE"];
// [env setObject: @"en_US.UTF-8" forKey: @"LANG"];
[env setObject: @"en_US.UTF-8" forKey: @"LC_ALL"];
[env setObject: @"" forKey: @"DYLD_LIBRARY_PATH"];
if (kTaskEnvironment)
{
for_each_key(en, key, kTaskEnvironment)
[env setObject: [kTaskEnvironment objectForKey: key] forKey: key];
}
return env;
}
//----------------------------------------------------------------------------------------
+ (id) task
{
return [self taskWithDelegate: nil object: nil];
}
//----------------------------------------------------------------------------------------
+ (id) taskWithDelegate: (id<TaskDelegate>) target
object: (id) object
{
return [[Task alloc] initWithDelegate: target object: object];
}
//----------------------------------------------------------------------------------------
- (id) initWithDelegate: (id<TaskDelegate>) target
object: (id) object
{
if (self = [super init])
{
fTask = [[NSTask alloc] init];
fDelegate = [target retain];
fObject = [object retain];
[fTask setEnvironment: [Task createEnvironment: FALSE]];
}
return self;
}
//----------------------------------------------------------------------------------------
- (void) dealloc
{
[[NSNotificationCenter defaultCenter]
removeObserver: self name: NSTaskDidTerminateNotification object: fTask];
[fObject release];
[fDelegate release];
[fTask release];
[super dealloc];
}
//----------------------------------------------------------------------------------------
- (NSTask*) task
{
return fTask;
}
//----------------------------------------------------------------------------------------
- (void) launch: (NSString*) path
arguments: (NSArray*) arguments
{
[fTask setLaunchPath: path];
[fTask setArguments: arguments];
[[NSNotificationCenter defaultCenter]
addObserver: self selector: @selector(completed:)
name: NSTaskDidTerminateNotification object: fTask];
[fTask launch];
// NSLog(@"launch: %@", fTask);
}
//----------------------------------------------------------------------------------------
- (void) launch: (NSString*) path
arguments: (NSArray*) arguments
stdOutput: (NSString*) stdOutput
{
if (stdOutput != nil)
[fTask setStandardOutput: [NSFileHandle fileHandleForWritingAtPath: stdOutput]];
[self launch: path arguments: arguments];
}
//----------------------------------------------------------------------------------------
- (void) setStandardOutput: (id) file
{
[fTask setStandardOutput: file];
}
//----------------------------------------------------------------------------------------
// Calls [fDelegate taskCompleted: (Task*) self object: (id) fObject]
- (void) completed: (NSNotification*) aNotification
{
#pragma unused(aNotification)
id delegate = fDelegate;
if (delegate)
{
Assert([delegate respondsToSelector: @selector(taskCompleted:object:)]);
id object = fObject;
fDelegate = nil;
fObject = nil;
[delegate taskCompleted: self object: object];
[object release];
[delegate release];
}
[self release];
}
//----------------------------------------------------------------------------------------
- (void) kill
{
WarnIf(kill([fTask processIdentifier], SIGKILL));
}
//----------------------------------------------------------------------------------------
- (void) terminate: (BOOL) force
{
if (force)
{
[self kill];
}
else
{
[fTask terminate];
}
}
//----------------------------------------------------------------------------------------
- (void) terminate
{
[fTask terminate];
}
@end // Task