-
Notifications
You must be signed in to change notification settings - Fork 38
/
DTRunManager.m
575 lines (499 loc) · 18.9 KB
/
DTRunManager.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
// Copyright (c) 2007-2010 Decimus Software, Inc. All rights reserved.
#import "DTRunManager.h"
#import "DSUniqueTextStorage.h"
#import "DTAppController.h"
#import "DTPrefsWindowController.h"
#import "DTTermWindowController.h"
#import "GrowlApplicationBridge.h"
#define DTUserDefault_ShellPath @"ShellPath"
@interface DTRunManager ()
@property (readwrite, assign) NSTask* task;
- (void)launch;
- (void)processResultsData;
- (void)handleEscapeSequenceWithType:(UInt8)type params:(NSArray*)params;
@end
@implementation DTRunManager
@synthesize workingDirectory, selectedURLStrings, command, task, resultsStorage;
+ (NSString*)shellPath {
static NSString* sharedPath = nil;
if(!sharedPath) {
sharedPath = [[NSUserDefaults standardUserDefaults] stringForKey:DTUserDefault_ShellPath];
if(!sharedPath || ![sharedPath hasPrefix:@"/"]) {
NSDictionary* env = [[NSProcessInfo processInfo] environment];
sharedPath = [env objectForKey:@"SHELL"];
}
if(!sharedPath)
sharedPath = @"/bin/bash";
}
return sharedPath;
}
+ (NSArray*)argumentsToRunCommand:(NSString*)command {
NSString* shell = [[DTRunManager shellPath] lastPathComponent];
if([shell isEqualToString:@"bash"] || [shell isEqualToString:@"sh"])
return [NSArray arrayWithObjects:@"-l", @"-i", @"-c", command, nil];
else
return [NSArray arrayWithObjects:@"-i", @"-c", command, nil];
}
- (id)initWithWD:(NSString*)_wd selection:(NSArray*)_selection command:(NSString*)_command demoExpired:(BOOL)demoExpired {
if((self = [super init])) {
resultsStorage = [[NSTextStorage alloc] init];
currentAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSFont fontWithName:[[NSUserDefaults standardUserDefaults] objectForKey:DTFontNameKey]
size:[[NSUserDefaults standardUserDefaults] doubleForKey:DTFontSizeKey]], NSFontAttributeName,
[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:DTTextColorKey]], NSForegroundColorAttributeName,
nil];
self.workingDirectory = _wd;
self.selectedURLStrings = _selection;
command = _command;
NSMutableString* selectedFilesEnvString = [NSMutableString string];
for(NSString* urlString in _selection) {
NSURL* url = [NSURL URLWithString:urlString];
if([url isFileURL]) {
NSString* newPath = [url path];
if([selectedFilesEnvString length])
[selectedFilesEnvString appendString:@" "];
[selectedFilesEnvString appendString:newPath];
}
}
if([selectedFilesEnvString length])
setenv("DTERM_SELECTED_FILES", [selectedFilesEnvString fileSystemRepresentation], 1);
else
unsetenv("DTERM_SELECTED_FILES");
// if(demoExpired) {
// [resultsStorage beginEditing];
// [resultsStorage setAttributedString:[[NSAttributedString alloc] initWithString:NSLocalizedString(@"Sorry, your demo period has expired! Please visit the Licensing preferences to purchase a license.", nil)
// attributes:[currentAttributes copy]]];
// [resultsStorage endEditing];
// [NSApp activateIgnoringOtherApps:YES];
// [((DTAppController*)[NSApp delegate]).prefsWindowController showRegistration:self];
// } else {
[self launch];
// }
}
return self;
}
- (void)launch {
// Set up basic task parameters
self.task = [[NSTask alloc] init];
[task setCurrentDirectoryPath:self.workingDirectory];
[task setLaunchPath:[DTRunManager shellPath]];
[task setArguments:[DTRunManager argumentsToRunCommand:self.command]];
// Attach pipe to task's standard output
NSPipe* newPipe = [NSPipe pipe];
stdOut = [newPipe fileHandleForReading];
[task setStandardOutput:newPipe];
// Attach pipe to task's standard err
newPipe = [NSPipe pipe];
stdErr = [newPipe fileHandleForReading];
[task setStandardError:newPipe];
// NSLog(@"Executing command %@ with args %@ in WD %@", [task launchPath], [[task arguments] componentsJoinedByString:@" "], [task currentDirectoryPath]);
// Setting the accessibility flag gives us a sticky egid of 'accessibility', which seems to interfere with shells using .bashrc and whatnot.
// We temporarily set our gid back before launching to work around this problem.
// Case 8042: http://fogbugz.decimus.net/default.php?8042
gid_t savedEGID = getegid();
setegid(getgid());
[task launch];
setegid(savedEGID);
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(readData:)
name:NSFileHandleReadCompletionNotification
object:stdOut];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(readData:)
name:NSFileHandleReadCompletionNotification
object:stdErr];
[stdOut readInBackgroundAndNotify];
[stdErr readInBackgroundAndNotify];
}
- (void)readData:(NSNotification*)notification {
id fileHandle = [notification object];
if((fileHandle == stdOut) || (fileHandle == stdErr)) {
NSData* data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
if([data length]) {
// Data was returned; append it
if(!unprocessedResultsData)
unprocessedResultsData = [NSMutableData dataWithCapacity:[data length]];
[unprocessedResultsData appendData:data];
[self processResultsData];
// Reschedule for the next round of reading
[fileHandle readInBackgroundAndNotify];
} else {
// No data, so this handle is done
if(fileHandle == stdOut)
stdOut = nil;
if(fileHandle == stdErr)
stdErr = nil;
// If both handles have closed, we're done with the task too
if(!stdOut && !stdErr) {
self.task = nil;
DTTermWindowController* termWindowController = [[NSApp delegate] termWindowController];
if(![[termWindowController window] isVisible] || ![[[termWindowController runsController] selectedObjects] containsObject:self]) {
NSArray* lines = [[self.resultsStorage string] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSString* lastLine = [lines lastObject];
if(![lastLine length])
lastLine = NSLocalizedString(@"<no results>", @"Growl notification description");
[GrowlApplicationBridge notifyWithTitle:[NSString stringWithFormat:NSLocalizedString(@"Command finished: %@", @"Growl notification title"), self.command]
description:lastLine
notificationName:@"DTCommandCompleted"
iconData:nil
priority:0
isSticky:NO
clickContext:nil];
}
}
}
}
}
#define ASCII_BS 0x08
#define ASCII_CR 0x0D
#define ASCII_ESC 0x1B
- (void)processResultsData {
if(![unprocessedResultsData length])
return;
const UInt8* data = [unprocessedResultsData bytes];
NSUInteger remainingLength = [unprocessedResultsData length];
[resultsStorage beginEditing];
// Add our trailing whitespace back on
if([trailingWhitespace length])
[resultsStorage appendAttributedString:trailingWhitespace];
trailingWhitespace = nil;
// Process the data
while(remainingLength) {
// Handle escape sequences
if(data[0] == ASCII_ESC) {
// If we don't have enough chars for ESC[x (a minimal escape sequence), wait for more data
if(remainingLength < 3)
break;
if(data[1] == '[') {
// Pull off the ESC[
data += 2;
remainingLength -= 2;
// Grab ##;###;### sequence
NSUInteger lengthOfEscapeString = 0;
while((lengthOfEscapeString < remainingLength) &&
((data[lengthOfEscapeString] >= '0') && (data[lengthOfEscapeString] <= '9')) ||
(data[lengthOfEscapeString] == ';'))
lengthOfEscapeString++;
// If we ate up all of the rest of the string without a terminating char, wait for more data
if(lengthOfEscapeString == remainingLength) {
// Only after putting back the ESC[, of course
// https://decimus.fogbugz.com/default.asp?10711
data -= 2;
remainingLength += 2;
break;
}
NSString* escapeString = [[NSString alloc] initWithBytes:data
length:lengthOfEscapeString
encoding:NSUTF8StringEncoding];
[self handleEscapeSequenceWithType:data[lengthOfEscapeString]
params:[escapeString componentsSeparatedByString:@";"]];
data += (lengthOfEscapeString + 1);
remainingLength -= (lengthOfEscapeString + 1);
} else {
// Hmmm...malformed ESC sequence without the [...
// Just pass it through as normal characters, I guess...
data++;
remainingLength--;
}
}
// Handle backspace characters
else if(data[0] == ASCII_BS) {
cursorLoc--;
data++;
remainingLength--;
}
// Handle CR
else if(data[0] == ASCII_CR) {
data++;
remainingLength--;
// Go back until we find a newline
while(cursorLoc && ([[resultsStorage string] characterAtIndex:(cursorLoc-1)] != '\n'))
cursorLoc--;
}
// Handle cursor not at end of string
else if(cursorLoc != [resultsStorage length]) {
unichar oldChar = [[resultsStorage string] characterAtIndex:cursorLoc];
unichar newChar = data[0];
if(oldChar == newChar) {
// bold it if they're identical
[resultsStorage applyFontTraits:NSBoldFontMask range:NSMakeRange(cursorLoc, 1)];
} else if((oldChar == '_') || (newChar == '_')) {
// If one is an underscore, underline the other char
if(oldChar == '_') {
// Need to replace the old underscore with the new real char
[resultsStorage replaceCharactersInRange:NSMakeRange(cursorLoc, 1)
withString:[NSString stringWithCharacters:&newChar length:1]];
}
[resultsStorage addAttributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInt:(NSUnderlineStyleSingle|NSUnderlinePatternSolid)]
forKey:NSUnderlineStyleAttributeName]
range:NSMakeRange(cursorLoc, 1)];
} else if(newChar == '\n') {
// For newlines, seek forward to the next newline
while((cursorLoc < [resultsStorage length]) && ([[resultsStorage string] characterAtIndex:cursorLoc] != '\n'))
cursorLoc++;
// If we're at the end, we didn't find one, so append one
if(cursorLoc == [resultsStorage length])
[resultsStorage appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"
attributes:[currentAttributes copy]]];
// The code outside this if-else if-... will skip over the \n the cursor is now at
} else {
// Just overwrite the old character
[resultsStorage replaceCharactersInRange:NSMakeRange(cursorLoc, 1)
withString:[NSString stringWithCharacters:&newChar length:1]];
}
cursorLoc++;
data++;
remainingLength--;
}
// Normal case; just appending bytes
else {
NSUInteger lengthOfNormalString = 0;
while((lengthOfNormalString < remainingLength) &&
(data[lengthOfNormalString] != ASCII_BS) &&
(data[lengthOfNormalString] != ASCII_CR) &&
(data[lengthOfNormalString] != ASCII_ESC))
lengthOfNormalString++;
if(lengthOfNormalString > 0) {
NSString* plainString = nil;
while(!plainString && (lengthOfNormalString > 0)) {
plainString = [[NSString alloc] initWithBytes:data
length:lengthOfNormalString
encoding:NSUTF8StringEncoding];
if(!plainString) {
// Failed! Cut off half of it and try again, rounding down so we'll eventually hit zero
lengthOfNormalString = trunc(lengthOfNormalString / 2.0);
}
}
if(!plainString) {
// If we couldn't get a good string, fill in a '?' and skip a byte to try and get back on track
plainString = @"?";
lengthOfNormalString = 1;
}
[resultsStorage appendAttributedString:[[NSAttributedString alloc] initWithString:plainString
attributes:[currentAttributes copy]]];
data += lengthOfNormalString;
remainingLength -= lengthOfNormalString;
cursorLoc += [plainString length];
}
}
}
// Pull any trailing whitespace off
NSCharacterSet* wsChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSUInteger wsStart = [resultsStorage length];
while((wsStart > 0) && [wsChars characterIsMember:[[resultsStorage string] characterAtIndex:(wsStart-1)]])
wsStart--;
if(wsStart < [resultsStorage length]) {
NSRange wsRange = NSMakeRange(wsStart, [resultsStorage length]-wsStart);
trailingWhitespace = [resultsStorage attributedSubstringFromRange:wsRange];
[resultsStorage deleteCharactersInRange:wsRange];
}
[resultsStorage endEditing];
if(remainingLength) {
if(remainingLength != [unprocessedResultsData length])
unprocessedResultsData = [NSMutableData dataWithBytes:data length:remainingLength];
} else {
[unprocessedResultsData setLength:0];
}
}
- (void)handleEscapeSequenceWithType:(UInt8)type params:(NSArray*)params {
switch(type) {
case 'm':
{
NSColor* fgColor = [currentAttributes objectForKey:NSForegroundColorAttributeName];
NSColor* bgColor = [currentAttributes objectForKey:NSBackgroundColorAttributeName];
for(NSString* paramString in params) {
switch([paramString integerValue]) {
case 0: // turn off all attributes
fgColor = nil;
bgColor = nil;
[currentAttributes removeObjectForKey:NSUnderlineStyleAttributeName];
[currentAttributes setObject:[[NSFontManager sharedFontManager] convertFont:[currentAttributes objectForKey:NSFontAttributeName]
toNotHaveTrait:NSFontBoldTrait]
forKey:NSFontAttributeName];
break;
case 1: // bold
[currentAttributes setObject:[[NSFontManager sharedFontManager] convertFont:[currentAttributes objectForKey:NSFontAttributeName]
toHaveTrait:NSFontBoldTrait]
forKey:NSFontAttributeName];
break;
case 4: // underline single
[currentAttributes setObject:[NSNumber numberWithInteger:NSUnderlineStyleSingle]
forKey:NSUnderlineStyleAttributeName];
break;
case 5: // blink
// not supported
break;
case 7: // FG black on BG white
fgColor = [NSColor blackColor];
bgColor = [NSColor whiteColor];
break;
case 8: // "hidden"
fgColor = bgColor;
break;
case 21: // underline double
[currentAttributes setObject:[NSNumber numberWithInteger:NSUnderlineStyleDouble]
forKey:NSUnderlineStyleAttributeName];
break;
case 22: // stop bold
[currentAttributes setObject:[[NSFontManager sharedFontManager] convertFont:[currentAttributes objectForKey:NSFontAttributeName]
toNotHaveTrait:NSFontBoldTrait]
forKey:NSFontAttributeName];
break;
case 24: // underline none
[currentAttributes setObject:[NSNumber numberWithInteger:NSUnderlineStyleNone]
forKey:NSUnderlineStyleAttributeName];
break;
case 30: // FG black
fgColor = [NSColor blackColor];
break;
case 31: // FG red
fgColor = [NSColor redColor];
break;
case 32: // FG green
fgColor = [NSColor greenColor];
break;
case 33: // FG yellow
fgColor = [NSColor yellowColor];
break;
case 34: // FG blue
fgColor = [NSColor blueColor];
break;
case 35: // FG magenta
fgColor = [NSColor magentaColor];
break;
case 36: // FG cyan
fgColor = [NSColor cyanColor];
break;
case 37: // FG white
fgColor = [NSColor whiteColor];
break;
case 39: // FG reset
fgColor = nil;
break;
case 40: // BG black
bgColor = [NSColor blackColor];
break;
case 41: // BG red
bgColor = [NSColor redColor];
break;
case 42: // BG green
bgColor = [NSColor greenColor];
break;
case 43: // BG yellow
bgColor = [NSColor yellowColor];
break;
case 44: // BG blue
bgColor = [NSColor blueColor];
break;
case 45: // BG magenta
bgColor = [NSColor magentaColor];
break;
case 46: // BG cyan
bgColor = [NSColor cyanColor];
break;
case 47: // BG white
bgColor = [NSColor whiteColor];
break;
case 49: // BG reset
bgColor = nil;
break;
case 90: // FG bright black
fgColor = [NSColor blackColor];
break;
case 91: // FG bright red
fgColor = [NSColor redColor];
break;
case 92: // FG bright green
fgColor = [NSColor greenColor];
break;
case 93: // FG bright yellow
fgColor = [NSColor yellowColor];
break;
case 94: // FG bright blue
fgColor = [NSColor blueColor];
break;
case 95: // FG bright magenta
fgColor = [NSColor magentaColor];
break;
case 96: // FG bright cyan
fgColor = [NSColor cyanColor];
break;
case 97: // FG bright white
fgColor = [NSColor whiteColor];
break;
case 100: // BG bright black
bgColor = [NSColor blackColor];
break;
case 101: // BG bright red
bgColor = [NSColor redColor];
break;
case 102: // BG bright green
bgColor = [NSColor greenColor];
break;
case 103: // BG bright yellow
bgColor = [NSColor yellowColor];
break;
case 104: // BG bright blue
bgColor = [NSColor blueColor];
break;
case 105: // BG bright magenta
bgColor = [NSColor magentaColor];
break;
case 106: // BG bright cyan
bgColor = [NSColor cyanColor];
break;
case 107: // BG bright white
bgColor = [NSColor whiteColor];
break;
}
}
NSColor* standardFGColor = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:DTTextColorKey]];
fgColor = ( fgColor ? [fgColor colorWithAlphaComponent:[standardFGColor alphaComponent]] : standardFGColor );
bgColor = [bgColor colorWithAlphaComponent:[standardFGColor alphaComponent]];
[currentAttributes setObject:fgColor forKey:NSForegroundColorAttributeName];
if(bgColor)
[currentAttributes setObject:bgColor forKey:NSBackgroundColorAttributeName];
else
[currentAttributes removeObjectForKey:NSBackgroundColorAttributeName];
}
break;
default:
// If we don't handle it, just ignore it
#ifdef DEVBUILD
NSLog(@"Got '%c' escape sequence with: %@", type, params);
#endif
break;
}
}
- (IBAction)cancel:(id)sender {
@try {
if([task isRunning]) {
// Bash catches basically all signals, but terminates on SIGHUP, terminating subprocesses as well
kill([task processIdentifier], SIGHUP);
}
self.task = nil;
stdOut = nil;
stdErr = nil;
}
@catch (NSException* e) {
NSLog(@"Caught exception terminating process: %@", e);
}
}
#pragma mark display support
- (void)setDisplayFont:(NSFont*)font {
[resultsStorage beginEditing];
[resultsStorage addAttribute:NSFontAttributeName
value:font
range:NSMakeRange(0, [resultsStorage length])];
[resultsStorage endEditing];
[currentAttributes setObject:font forKey:NSFontAttributeName];
}
- (void)setDisplayColor:(NSColor*)color {
[resultsStorage beginEditing];
[resultsStorage addAttribute:NSForegroundColorAttributeName
value:color
range:NSMakeRange(0, [resultsStorage length])];
[resultsStorage endEditing];
[currentAttributes setObject:color forKey:NSForegroundColorAttributeName];
}
@end