forked from gnachman/iTerm2
/
PTYSession.m
3547 lines (3119 loc) · 113 KB
/
PTYSession.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
/*
** PTYSession.m
**
** Copyright (c) 2002, 2003
**
** Author: Fabian, Ujwal S. Setlur
**
** Project: iTerm
**
** Description: Implements the model class for a terminal session.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#import <iTerm/iTerm.h>
#import <iTerm/PTYSession.h>
#import <iTerm/PTYTask.h>
#import <iTerm/PTYTextView.h>
#import <iTerm/PTYScrollView.h>
#import <iTerm/VT100Screen.h>
#import <iTerm/VT100Terminal.h>
#import <iTerm/PreferencePanel.h>
#import <WindowControllerInterface.h>
#import <iTerm/iTermController.h>
#import <iTerm/PseudoTerminal.h>
#import <FakeWindow.h>
#import <iTerm/NSStringITerm.h>
#import <iTerm/iTermKeyBindingMgr.h>
#import <iTerm/ITAddressBookMgr.h>
#import <iTerm/iTermGrowlDelegate.h>
#import "iTermApplicationDelegate.h"
#import "SessionView.h"
#import "PTYTab.h"
#import "ProcessCache.h"
#import "MovePaneController.h"
#import "Trigger.h"
#import "Coprocess.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#define DEBUG_ALLOC 0
#define DEBUG_METHOD_TRACE 0
#define DEBUG_KEYDOWNDUMP 0
#define ASK_ABOUT_OUTDATED_FORMAT @"AskAboutOutdatedKeyMappingForGuid%@"
@implementation PTYSession
static NSString *TERM_ENVNAME = @"TERM";
static NSString *COLORFGBG_ENVNAME = @"COLORFGBG";
static NSString *PWD_ENVNAME = @"PWD";
static NSString *PWD_ENVVALUE = @"~";
// Constants for saved window arrangement keys.
static NSString* SESSION_ARRANGEMENT_COLUMNS = @"Columns";
static NSString* SESSION_ARRANGEMENT_ROWS = @"Rows";
static NSString* SESSION_ARRANGEMENT_BOOKMARK = @"Bookmark";
static NSString* SESSION_ARRANGEMENT_WORKING_DIRECTORY = @"Working Directory";
// init/dealloc
- (id)init
{
if ((self = [super init]) == nil) {
return (nil);
}
// The new session won't have the move-pane overlay, so just exit move pane
// mode.
[[MovePaneController sharedInstance] exitMovePaneMode];
triggerLine_ = [[NSMutableString alloc] init];
isDivorced = NO;
gettimeofday(&lastInput, NULL);
lastOutput = lastInput;
lastUpdate = lastInput;
EXIT=NO;
savedScrollPosition_ = -1;
updateTimer = nil;
antiIdleTimer = nil;
addressBookEntry=nil;
#if DEBUG_ALLOC
NSLog(@"%s: 0x%x", __PRETTY_FUNCTION__, self);
#endif
// Allocate screen, shell, and terminal objects
SHELL = [[PTYTask alloc] init];
TERMINAL = [[VT100Terminal alloc] init];
SCREEN = [[VT100Screen alloc] init];
NSParameterAssert(SHELL != nil && TERMINAL != nil && SCREEN != nil);
// Need Growl plist stuff
gd = [iTermGrowlDelegate sharedInstance];
growlIdle = growlNewOutput = NO;
slowPasteBuffer = [[NSMutableString alloc] init];
creationDate_ = [[NSDate date] retain];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(windowResized)
name:@"iTermWindowDidResize"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(coprocessChanged)
name:@"kCoprocessStatusChangeNotification"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(sessionContentsChanged:)
name:@"iTermTabContentsChanged"
object:nil];
return self;
}
- (void)dealloc
{
[self stopTailFind]; // This frees the substring in the tail find context, if needed.
[triggerLine_ release];
[triggers_ release];
[pasteboard_ release];
[pbtext_ release];
[slowPasteBuffer release];
if (slowPasteTimer) {
[slowPasteTimer invalidate];
}
[updateDisplayUntil_ release];
[creationDate_ release];
[lastActiveAt_ release];
[bookmarkName release];
[TERM_VALUE release];
[COLORFGBG_VALUE release];
[name release];
[windowTitle release];
[addressBookEntry release];
[backgroundImagePath release];
[antiIdleTimer invalidate];
[antiIdleTimer release];
[updateTimer invalidate];
[updateTimer release];
[originalAddressBookEntry release];
[liveSession_ release];
[SHELL release];
SHELL = nil;
[SCREEN release];
SCREEN = nil;
[TERMINAL release];
TERMINAL = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (dvrDecoder_) {
[dvr_ releaseDecoder:dvrDecoder_];
[dvr_ release];
}
[super dealloc];
#if DEBUG_ALLOC
NSLog(@"%s: 0x%x, done", __PRETTY_FUNCTION__, self);
#endif
}
- (void)cancelTimers
{
[view cancelTimers];
[updateTimer invalidate];
[antiIdleTimer invalidate];
}
- (void)setDvr:(DVR*)dvr liveSession:(PTYSession*)liveSession
{
assert(liveSession != self);
liveSession_ = liveSession;
[liveSession_ retain];
[SCREEN disableDvr];
dvr_ = dvr;
[dvr_ retain];
dvrDecoder_ = [dvr getDecoder];
long long t = [dvr_ lastTimeStamp];
if (t) {
[dvrDecoder_ seek:t];
[self setDvrFrame];
}
}
- (void)irAdvance:(int)dir
{
if (!dvr_) {
if (dir < 0) {
[[[self tab] realParentWindow] replaySession:self];
PTYSession* irSession = [[[self tab] realParentWindow] currentSession];
if (irSession != self) {
// Failed to enter replay mode (perhaps nothing to replay?)
[irSession irAdvance:dir];
}
return;
} else {
NSBeep();
return;
}
}
if (dir > 0) {
if (![dvrDecoder_ next] || [dvrDecoder_ timestamp] == [dvr_ lastTimeStamp]) {
// Switch to the live view
[[[self tab] realParentWindow] showLiveSession:liveSession_ inPlaceOf:self];
return;
}
} else {
if (![dvrDecoder_ prev]) {
NSBeep();
}
}
[self setDvrFrame];
}
- (long long)irSeekToAtLeast:(long long)timestamp
{
assert(dvr_);
if (![dvrDecoder_ seek:timestamp]) {
[dvrDecoder_ seek:[dvr_ firstTimeStamp]];
}
[self setDvrFrame];
return [dvrDecoder_ timestamp];
}
- (DVR*)dvr
{
return dvr_;
}
- (DVRDecoder*)dvrDecoder
{
return dvrDecoder_;
}
- (PTYSession*)liveSession
{
return liveSession_;
}
- (void)coprocessChanged
{
[TEXTVIEW setNeedsDisplay:YES];
}
- (void)windowResized
{
// When the window is resized the title is temporarily changed and it's our
// timer that resets it.
if (!EXIT) {
[self scheduleUpdateIn:kBackgroundSessionIntervalSec];
}
}
+ (void)drawArrangementPreview:(NSDictionary *)arrangement frame:(NSRect)frame
{
Bookmark* theBookmark = [[BookmarkModel sharedInstance] bookmarkWithGuid:[[arrangement objectForKey:SESSION_ARRANGEMENT_BOOKMARK] objectForKey:KEY_GUID]];
if (!theBookmark) {
theBookmark = [arrangement objectForKey:SESSION_ARRANGEMENT_BOOKMARK];
}
// [self setForegroundColor:[ITAddressBookMgr decodeColor:[aDict objectForKey:KEY_FOREGROUND_COLOR]]];
[[ITAddressBookMgr decodeColor:[theBookmark objectForKey:KEY_BACKGROUND_COLOR]] set];
NSRectFill(frame);
}
+ (PTYSession*)sessionFromArrangement:(NSDictionary*)arrangement
inView:(SessionView*)sessionView
inTab:(PTYTab*)theTab
forObjectType:(iTermObjectType)objectType
{
PTYSession* aSession = [[[PTYSession alloc] init] autorelease];
aSession->view = sessionView;
[[sessionView findViewController] setDelegate:aSession];
Bookmark* theBookmark = [[BookmarkModel sharedInstance] bookmarkWithGuid:[[arrangement objectForKey:SESSION_ARRANGEMENT_BOOKMARK] objectForKey:KEY_GUID]];
BOOL needDivorce = NO;
if (!theBookmark) {
theBookmark = [arrangement objectForKey:SESSION_ARRANGEMENT_BOOKMARK];
needDivorce = YES;
}
[[aSession SCREEN] setUnlimitedScrollback:[[theBookmark objectForKey:KEY_UNLIMITED_SCROLLBACK] boolValue]];
[[aSession SCREEN] setScrollback:[[theBookmark objectForKey:KEY_SCROLLBACK_LINES] intValue]];
// set our preferences
[aSession setAddressBookEntry:theBookmark];
[aSession setScreenSize:[sessionView frame] parent:[theTab realParentWindow]];
[aSession setPreferencesFromAddressBookEntry:theBookmark];
[[aSession SCREEN] setDisplay:[aSession TEXTVIEW]];
[aSession setName:[theBookmark objectForKey:KEY_NAME]];
if ([[[[theTab realParentWindow] window] title] compare:@"Window"] == NSOrderedSame) {
[[theTab realParentWindow] setWindowTitle];
}
[aSession setTab:theTab];
[aSession runCommandWithOldCwd:[arrangement objectForKey:SESSION_ARRANGEMENT_WORKING_DIRECTORY]
forObjectType:objectType];
if (needDivorce) {
[aSession divorceAddressBookEntryFromPreferences];
}
return aSession;
}
// Session specific methods
- (BOOL)setScreenSize:(NSRect)aRect parent:(id<WindowControllerInterface>)parent
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession setScreenSize:parent:]", __FILE__, __LINE__);
#endif
[SCREEN setSession:self];
// Allocate a container to hold the scrollview
if (!view) {
view = [[[SessionView alloc] initWithFrame:NSMakeRect(0, 0, aRect.size.width, aRect.size.height)
session:self] autorelease];
[[view findViewController] setDelegate:self];
}
// Allocate a scrollview
SCROLLVIEW = [[PTYScrollView alloc] initWithFrame:NSMakeRect(0, 0, aRect.size.width, aRect.size.height)
hasVerticalScroller:(![parent anyFullScreen] &&
![[PreferencePanel sharedInstance] hideScrollbar])];
NSParameterAssert(SCROLLVIEW != nil);
[SCROLLVIEW setAutoresizingMask: NSViewWidthSizable|NSViewHeightSizable];
// assign the main view
[view addSubview:SCROLLVIEW];
[view setAutoresizesSubviews:YES];
// TODO(georgen): I disabled setCopiesOnScroll because there is a vertical margin in the PTYTextView and
// we would not want that copied. This is obviously bad for performance when scrolling, but it's unclear
// whether the difference will ever be noticable. I believe it could be worked around (painfully) by
// subclassing NSClipView and overriding viewBoundsChanged: and viewFrameChanged: so that it coipes on
// scroll but it doesn't include the vertical marigns when doing so.
// The vertical margins are indespensable because different PTYTextViews may use different fonts/font
// sizes, but the window size does not change as you move from tab to tab. If the margin is outside the
// NSScrollView's contentView it looks funny.
[[SCROLLVIEW contentView] setCopiesOnScroll:NO];
// Allocate a text view
NSSize aSize = [SCROLLVIEW contentSize];
WRAPPER = [[TextViewWrapper alloc] initWithFrame:NSMakeRect(0, 0, aSize.width, aSize.height)];
[WRAPPER setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
TEXTVIEW = [[PTYTextView alloc] initWithFrame: NSMakeRect(0, VMARGIN, aSize.width, aSize.height)];
[TEXTVIEW setDimOnlyText:[[PreferencePanel sharedInstance] dimOnlyText]];
[TEXTVIEW setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
[TEXTVIEW setFont:[ITAddressBookMgr fontWithDesc:[addressBookEntry objectForKey:KEY_NORMAL_FONT]]
nafont:[ITAddressBookMgr fontWithDesc:[addressBookEntry objectForKey:KEY_NON_ASCII_FONT]]
horizontalSpacing:[[addressBookEntry objectForKey:KEY_HORIZONTAL_SPACING] floatValue]
verticalSpacing:[[addressBookEntry objectForKey:KEY_VERTICAL_SPACING] floatValue]];
[self setTransparency:[[addressBookEntry objectForKey:KEY_TRANSPARENCY] floatValue]];
[WRAPPER addSubview:TEXTVIEW];
[TEXTVIEW setFrame:NSMakeRect(0, VMARGIN, aSize.width, aSize.height - VMARGIN)];
[TEXTVIEW release];
// assign terminal and task objects
[SCREEN setShellTask:SHELL];
[SCREEN setTerminal:TERMINAL];
[TERMINAL setScreen: SCREEN];
[SHELL setDelegate:self];
// initialize the screen
int width = (aSize.width - MARGIN*2) / [TEXTVIEW charWidth];
int height = (aSize.height - VMARGIN*2) / [TEXTVIEW lineHeight];
if ([SCREEN initScreenWithWidth:width Height:height]) {
[self setName:@"Shell"];
[self setDefaultName:@"Shell"];
[TEXTVIEW setDataSource:SCREEN];
[TEXTVIEW setDelegate:self];
[SCROLLVIEW setDocumentView:WRAPPER];
[WRAPPER release];
[SCROLLVIEW setDocumentCursor:[PTYTextView textViewCursor]];
[SCROLLVIEW setLineScroll:[TEXTVIEW lineHeight]];
[SCROLLVIEW setPageScroll:2*[TEXTVIEW lineHeight]];
[SCROLLVIEW setHasVerticalScroller:(![parent anyFullScreen] &&
![[PreferencePanel sharedInstance] hideScrollbar])];
ai_code=0;
[antiIdleTimer release];
antiIdleTimer = nil;
newOutput = NO;
return YES;
} else {
[SCREEN release];
SCREEN = nil;
[TEXTVIEW release];
NSRunCriticalAlertPanel(NSLocalizedStringFromTableInBundle(@"Out of memory",@"iTerm", [NSBundle bundleForClass:[self class]], @"Error"),
NSLocalizedStringFromTableInBundle(@"New sesssion cannot be created. Try smaller buffer sizes.",@"iTerm", [NSBundle bundleForClass:[self class]], @"Error"),
NSLocalizedStringFromTableInBundle(@"OK",@"iTerm", [NSBundle bundleForClass:[self class]], @"OK"),
nil, nil);
return NO;
}
}
- (void)runCommandWithOldCwd:(NSString*)oldCWD
forObjectType:(iTermObjectType)objectType
{
NSMutableString *cmd;
NSArray *arg;
NSString *pwd;
BOOL isUTF8;
// Grab the addressbook command
Bookmark* addressbookEntry = [self addressBookEntry];
BOOL loginSession;
cmd = [[[NSMutableString alloc] initWithString:[ITAddressBookMgr bookmarkCommand:addressbookEntry isLoginSession:&loginSession]] autorelease];
NSMutableString* theName = [[[NSMutableString alloc] initWithString:[addressbookEntry objectForKey:KEY_NAME]] autorelease];
// Get session parameters
[[[self tab] realParentWindow] getSessionParameters:cmd withName:theName];
[cmd breakDownCommandToPath:&cmd cmdArgs:&arg];
pwd = [ITAddressBookMgr bookmarkWorkingDirectory:addressbookEntry
forObjectType:objectType];
if ([pwd length] == 0) {
if (oldCWD) {
pwd = oldCWD;
} else {
pwd = NSHomeDirectory();
}
}
NSDictionary *env = [NSDictionary dictionaryWithObject:pwd forKey:@"PWD"];
isUTF8 = ([[addressbookEntry objectForKey:KEY_CHARACTER_ENCODING] unsignedIntValue] == NSUTF8StringEncoding);
[[[self tab] realParentWindow] setName:theName forSession:self];
// Start the command
[self startProgram:cmd arguments:arg environment:env isUTF8:isUTF8 asLoginSession:loginSession];
}
- (void)setWidth:(int)width height:(int)height
{
[SCREEN resizeWidth:width height:height];
[SHELL setWidth:width height:height];
[TEXTVIEW clearHighlights];
[[tab_ realParentWindow] futureInvalidateRestorableState];
}
- (void)setSplitSelectionMode:(SplitSelectionMode)mode
{
[[self view] setSplitSelectionMode:mode];
}
- (int)overUnder:(int)proposedSize inVerticalDimension:(BOOL)vertically
{
int x = proposedSize;
if (vertically) {
if ([view showTitle]) {
// x = 50/53
x -= [SessionView titleHeight];
}
// x = 28/31
x -= VMARGIN * 2;
// x = 18/21
// iLineHeight = 10
int iLineHeight = [TEXTVIEW lineHeight];
x %= iLineHeight;
// x = 8/1
if (x > iLineHeight / 2) {
x -= iLineHeight;
}
// x = -2/1
return x;
} else {
x -= MARGIN * 2;
int iCharWidth = [TEXTVIEW charWidth];
x %= iCharWidth;
if (x > iCharWidth / 2) {
x -= iCharWidth;
}
}
return x;
}
- (NSArray *)childJobNames
{
int skip = 0;
pid_t thePid = [SHELL pid];
if ([[[ProcessCache sharedInstance] getNameOfPid:thePid isForeground:nil] isEqualToString:@"login"]) {
skip = 1;
}
NSMutableArray *names = [NSMutableArray array];
for (NSNumber *n in [[ProcessCache sharedInstance] childrenOfPid:thePid levelsToSkip:skip]) {
pid_t pid = [n intValue];
NSDictionary *info = [[ProcessCache sharedInstance] dictionaryOfTaskInfoForPid:pid];
[names addObject:[info objectForKey:PID_INFO_NAME]];
}
return names;
}
- (BOOL)promptOnClose
{
if (EXIT) {
return NO;
}
switch ([[addressBookEntry objectForKey:KEY_PROMPT_CLOSE] intValue]) {
case PROMPT_ALWAYS:
return YES;
case PROMPT_NEVER:
return NO;
case PROMPT_EX_JOBS: {
NSArray *jobsThatDontRequirePrompting = [addressBookEntry objectForKey:KEY_JOBS];
for (NSString *childName in [self childJobNames]) {
if ([jobsThatDontRequirePrompting indexOfObject:childName] == NSNotFound) {
// This job is not in the ignore list.
return YES;
}
}
// All jobs were in the ignore list.
return NO;
}
}
return YES;
}
- (void)setNewOutput:(BOOL)value
{
newOutput = value;
}
- (BOOL)newOutput
{
return newOutput;
}
// This command installs the xterm-256color terminfo in the user's terminfo directory:
// tic -e xterm-256color $FILENAME
- (void)_maybeAskAboutInstallXtermTerminfo
{
NSString* NEVER_WARN = @"NeverWarnAboutXterm256ColorTerminfo";
if ([[NSUserDefaults standardUserDefaults] objectForKey:NEVER_WARN]) {
return;
}
NSString* filename = [[NSBundle bundleForClass:[self class]] pathForResource:@"xterm-terminfo" ofType:@"txt"];
if (!filename) {
return;
}
NSString* cmd = [NSString stringWithFormat:@"tic -e xterm-256color %@", [filename stringWithEscapedShellCharacters]];
if (system("infocmp xterm-256color > /dev/null")) {
switch (NSRunAlertPanel(@"Warning",
@"The terminfo file for the terminal type you're using, \"xterm-256color\", is not installed on your system. Would you like to install it now?",
@"Install",
@"Never ask me again",
@"Not Now",
nil)) {
case NSAlertDefaultReturn:
if (system([cmd UTF8String])) {
NSRunAlertPanel(@"Error",
[NSString stringWithFormat:@"Sorry, an error occurred while running: %@", cmd],
@"Ok", nil, nil);
}
break;
case NSAlertAlternateReturn:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:NEVER_WARN];
break;
}
}
}
- (NSString *)_autoLogFilenameForTermId:(NSString *)termid
{
// $(LOGDIR)/YYYYMMDD_HHMMSS.$(NAME).wNtNpN.$(PID).$(RANDOM).log
return [NSString stringWithFormat:@"%@/%@.%@.%@.%d.%0x.log",
[addressBookEntry objectForKey:KEY_LOGDIR],
[[NSDate date] descriptionWithCalendarFormat:@"%Y%m%d_%H%M%S"
timeZone:nil
locale:nil],
[addressBookEntry objectForKey:KEY_NAME],
termid,
(int)getpid(),
(int)arc4random()];
}
- (void)startProgram:(NSString *)program
arguments:(NSArray *)prog_argv
environment:(NSDictionary *)prog_env
isUTF8:(BOOL)isUTF8
asLoginSession:(BOOL)asLoginSession
{
NSString *path = program;
NSMutableArray *argv = [NSMutableArray arrayWithArray:prog_argv];
NSMutableDictionary *env = [NSMutableDictionary dictionaryWithDictionary:prog_env];
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession startProgram:%@ arguments:%@ environment:%@]",
__FILE__, __LINE__, program, prog_argv, prog_env );
#endif
if ([env objectForKey:TERM_ENVNAME] == nil)
[env setObject:TERM_VALUE forKey:TERM_ENVNAME];
if ([[env objectForKey:TERM_ENVNAME] isEqualToString:@"xterm-256color"]) {
[self _maybeAskAboutInstallXtermTerminfo];
}
if ([env objectForKey:COLORFGBG_ENVNAME] == nil && COLORFGBG_VALUE != nil)
[env setObject:COLORFGBG_VALUE forKey:COLORFGBG_ENVNAME];
NSString* lang = [self _lang];
if (![addressBookEntry objectForKey:KEY_SET_LOCALE_VARS] ||
[[addressBookEntry objectForKey:KEY_SET_LOCALE_VARS] boolValue]) {
if (lang) {
[env setObject:lang forKey:@"LANG"];
} else {
[env setObject:[self encodingName] forKey:@"LC_CTYPE"];
}
}
if ([env objectForKey:PWD_ENVNAME] == nil) {
[env setObject:[PWD_ENVVALUE stringByExpandingTildeInPath] forKey:PWD_ENVNAME];
}
PseudoTerminal *pty = [tab_ realParentWindow];
NSString *itermId = [NSString stringWithFormat:@"w%dt%dp%d",
[pty number],
[tab_ realObjectCount] - 1,
[tab_ indexOfSessionView:[self view]]];
[env setObject:itermId forKey:@"ITERM_SESSION_ID"];
if ([addressBookEntry objectForKey:KEY_NAME]) {
[env setObject:[addressBookEntry objectForKey:KEY_NAME] forKey:@"ITERM_PROFILE"];
}
if ([[addressBookEntry objectForKey:KEY_AUTOLOG] boolValue]) {
[SHELL loggingStartWithPath:[self _autoLogFilenameForTermId:itermId]];
}
[SHELL launchWithPath:path
arguments:argv
environment:env
width:[SCREEN width]
height:[SCREEN height]
isUTF8:isUTF8
asLoginSession:asLoginSession];
NSString *initialText = [addressBookEntry objectForKey:KEY_INITIAL_TEXT];
if ([initialText length]) {
[SHELL writeTask:[initialText dataUsingEncoding:[self encoding]]];
[SHELL writeTask:[@"\n" dataUsingEncoding:[self encoding]]];
}
}
- (void)_maybeWarnAboutShortLivedSessions
{
if ([[NSDate date] timeIntervalSinceDate:creationDate_] < 3) {
NSString* theName = [addressBookEntry objectForKey:KEY_NAME];
NSString* theKey = [NSString stringWithFormat:@"NeverWarnAboutShortLivedSessions_%@", [addressBookEntry objectForKey:KEY_GUID]];
if (![[[NSUserDefaults standardUserDefaults] objectForKey:theKey] boolValue]) {
if (NSRunAlertPanel(@"Short-Lived Session Warning",
[NSString stringWithFormat:@"A session ended very soon after starting. Check that the command in profile \"%@\" is correct.", theName],
@"Ok",
@"Don't Warn Again for This Profile",
nil) != NSAlertDefaultReturn) {
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:theKey];
}
}
}
}
// Terminate a replay session but not the live session
- (void)softTerminate
{
liveSession_ = nil;
[self terminate];
}
- (void)terminate
{
if (EXIT) {
[self _maybeWarnAboutShortLivedSessions];
}
// The source pane may have just exited. Dogs and cats living together!
// Mass hysteria!
[[MovePaneController sharedInstance] exitMovePaneMode];
// deregister from the notification center
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (liveSession_) {
[liveSession_ terminate];
}
EXIT = YES;
[SHELL stop];
// final update of display
[self updateDisplay];
[TEXTVIEW setDataSource:nil];
[TEXTVIEW setDelegate:nil];
[TEXTVIEW removeFromSuperview];
TEXTVIEW = nil;
[SHELL setDelegate:nil];
[SCREEN setShellTask:nil];
[SCREEN setSession:nil];
[SCREEN setTerminal:nil];
[TERMINAL setScreen:nil];
if ([[view findViewController] delegate] == self) {
[[view findViewController] setDelegate:nil];
}
[updateTimer invalidate];
[updateTimer release];
updateTimer = nil;
if (slowPasteTimer) {
[slowPasteTimer invalidate];
slowPasteTimer = nil;
}
[tab_ removeSession:self];
tab_ = nil;
}
- (void)writeTask:(NSData*)data
{
static BOOL checkedDebug;
static BOOL debugKeyDown;
if (!checkedDebug) {
debugKeyDown = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DebugKeyDown"] boolValue];
checkedDebug = YES;
}
if (debugKeyDown) {
const char *bytes = [data bytes];
for (int i = 0; i < [data length]; i++) {
NSLog(@"writeTask keydown %d: %d (%c)", i, (int) bytes[i], bytes[i]);
}
}
// check if we want to send this input to all the sessions
if (![[[self tab] realParentWindow] broadcastInputToSession:self]) {
// Send to only this session
if (!EXIT) {
[self setBell:NO];
PTYScroller* ptys = (PTYScroller*)[SCROLLVIEW verticalScroller];
[SHELL writeTask:data];
[ptys setUserScroll:NO];
}
} else {
// send to all sessions
[[[self tab] realParentWindow] sendInputToAllSessions:data];
}
}
- (void)readTask:(NSData*)data
{
if ([data length] == 0 || EXIT) {
return;
}
if ([SHELL hasMuteCoprocess]) {
return;
}
if (gDebugLogging) {
const char* bytes = [data bytes];
int length = [data length];
DebugLog([NSString stringWithFormat:@"readTask called with %d bytes. The last byte is %d", (int)length, (int)bytes[length-1]]);
}
[TERMINAL putStreamData:data];
VT100TCC token;
// while loop to process all the tokens we can get
while (!EXIT &&
TERMINAL &&
((token = [TERMINAL getNextToken]),
token.type != VT100_WAIT &&
token.type != VT100CC_NULL)) {
// process token
if (token.type != VT100_SKIP) { // VT100_SKIP = there was no data to read
if (pasteboard_) {
// We are probably copying text to the clipboard until esc]50;EndCopy^G is received.
if (token.type != XTERMCC_SET_KVP || ![token.u.string hasPrefix:@"CopyToClipboard"]) {
// Append text to clipboard except for initial command that turns on copying to
// the clipboard.
[pbtext_ appendData:[NSData dataWithBytes:token.position
length:token.length]];
}
// Don't allow more than 100MB to be added to the pasteboard queue in case someone
// forgets to send the EndCopy command.
const int kMaxPasteboardBytes = 100 * 1024 * 1024;
if ([pbtext_ length] > kMaxPasteboardBytes) {
[self setPasteboard:nil];
}
}
if (token.type != VT100_NOTSUPPORT) {
[SCREEN putToken:token];
}
}
}
gettimeofday(&lastOutput, NULL);
newOutput = YES;
// Make sure the screen gets redrawn soonish
[updateDisplayUntil_ release];
updateDisplayUntil_ = [[NSDate dateWithTimeIntervalSinceNow:10] retain];
if ([[[self tab] parentWindow] currentTab] == [self tab]) {
if ([data length] < 1024) {
[self scheduleUpdateIn:kFastTimerIntervalSec];
} else {
[self scheduleUpdateIn:kSlowTimerIntervalSec];
}
} else {
[self scheduleUpdateIn:kBackgroundSessionIntervalSec];
}
[[ProcessCache sharedInstance] notifyNewOutput];
}
- (void)checkTriggers
{
for (Trigger *trigger in triggers_) {
[trigger tryString:triggerLine_ inSession:self];
}
}
- (void)appendStringToTriggerLine:(NSString *)s
{
const int kMaxTriggerLineLength = 1024;
if ([triggers_ count] && [triggerLine_ length] + [s length] < kMaxTriggerLineLength) {
[triggerLine_ appendString:s];
}
}
- (void)clearTriggerLine
{
if ([triggers_ count]) {
[self checkTriggers];
[triggerLine_ setString:@""];
}
}
- (BOOL)_growlOnForegroundTabs
{
return [[[NSUserDefaults standardUserDefaults] objectForKey:@"GrowlOnForegroundTabs"] boolValue];
}
- (void)brokenPipe
{
if ([SCREEN growl] && (![[self tab] isForegroundTab] || [self _growlOnForegroundTabs])) {
[gd growlNotify:@"Session Ended"
withDescription:[NSString stringWithFormat:@"Session \"%@\" in tab #%d just terminated.",
[self name],
[[self tab] realObjectCount]]
andNotification:@"Broken Pipes"
andSession:self];
}
EXIT = YES;
[[self tab] setLabelAttributes];
if ([self autoClose]) {
[[self tab] closeSession:self];
} else {
[self updateDisplay];
}
}
- (int)_keyBindingActionForEvent:(NSEvent*)event
{
unsigned int modflag;
NSString *unmodkeystr;
unichar unmodunicode;
int keyBindingAction;
NSString *keyBindingText;
modflag = [event modifierFlags];
unmodkeystr = [event charactersIgnoringModifiers];
unmodunicode = [unmodkeystr length]>0?[unmodkeystr characterAtIndex:0]:0;
/*
unsigned short keycode = [event keyCode];
NSString *keystr = [event characters];
unichar unicode = [keystr length] > 0 ? [keystr characterAtIndex:0] : 0;
NSLog(@"event:%@ (%x+%x)[%@][%@]:%x(%c) <%d>", event,modflag,keycode,keystr,unmodkeystr,unicode,unicode,(modflag & NSNumericPadKeyMask));
*/
// Check if we have a custom key mapping for this event
keyBindingAction = [iTermKeyBindingMgr actionForKeyCode:unmodunicode
modifiers:modflag
text:&keyBindingText
keyMappings:[[self addressBookEntry] objectForKey:KEY_KEYBOARD_MAP]];
return keyBindingAction;
}
- (BOOL)hasTextSendingKeyMappingForEvent:(NSEvent*)event
{
int keyBindingAction = [self _keyBindingActionForEvent:event];
switch (keyBindingAction) {
case KEY_ACTION_ESCAPE_SEQUENCE:
case KEY_ACTION_HEX_CODE:
case KEY_ACTION_TEXT:
case KEY_ACTION_IGNORE:
case KEY_ACTION_SEND_C_H_BACKSPACE:
case KEY_ACTION_SEND_C_QM_BACKSPACE:
return YES;
}
return NO;
}
- (BOOL)hasActionableKeyMappingForEvent:(NSEvent *)event
{
int keyBindingAction = [self _keyBindingActionForEvent:event];
return (keyBindingAction >= 0) && (keyBindingAction != KEY_ACTION_DO_NOT_REMAP_MODIFIERS) && (keyBindingAction != KEY_ACTION_REMAP_LOCALLY);
}
+ (void)reloadAllBookmarks
{
int n = [[iTermController sharedInstance] numberOfTerminals];
for (int i = 0; i < n; ++i) {
PseudoTerminal* pty = [[iTermController sharedInstance] terminalAtIndex:i];
[pty reloadBookmarks];
}
}
- (BOOL)_askAboutOutdatedKeyMappings
{
NSNumber* n = [addressBookEntry objectForKey:KEY_ASK_ABOUT_OUTDATED_KEYMAPS];
if (!n) {
n = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:ASK_ABOUT_OUTDATED_FORMAT, [addressBookEntry objectForKey:KEY_GUID]]];
if (!n && [addressBookEntry objectForKey:KEY_ORIGINAL_GUID]) {
n = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:ASK_ABOUT_OUTDATED_FORMAT, [addressBookEntry objectForKey:KEY_ORIGINAL_GUID]]];
}
}
return n ? [n boolValue] : YES;
}
- (void)_removeOutdatedKeyMapping
{
NSMutableDictionary* temp = [NSMutableDictionary dictionaryWithDictionary:addressBookEntry];
[iTermKeyBindingMgr removeMappingWithCode:NSLeftArrowFunctionKey
modifiers:NSCommandKeyMask | NSAlternateKeyMask | NSNumericPadKeyMask
inBookmark:temp];
[iTermKeyBindingMgr removeMappingWithCode:NSRightArrowFunctionKey
modifiers:NSCommandKeyMask | NSAlternateKeyMask | NSNumericPadKeyMask
inBookmark:temp];
BookmarkModel* model;
if (isDivorced) {
model = [BookmarkModel sessionsInstance];
} else {
model = [BookmarkModel sharedInstance];
}
[model setBookmark:temp withGuid:[temp objectForKey:KEY_GUID]];
[[NSNotificationCenter defaultCenter] postNotificationName:@"iTermKeyBindingsChanged"
object:nil
userInfo:nil];
[PTYSession reloadAllBookmarks];
}
- (void)_setKeepOutdatedKeyMapping
{
BookmarkModel* model;
if (isDivorced) {
model = [BookmarkModel sessionsInstance];
} else {
model = [BookmarkModel sharedInstance];
}
[model setObject:[NSNumber numberWithBool:NO]
forKey:KEY_ASK_ABOUT_OUTDATED_KEYMAPS
inBookmark:addressBookEntry];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO]
forKey:[NSString stringWithFormat:ASK_ABOUT_OUTDATED_FORMAT,
[addressBookEntry objectForKey:KEY_GUID]]];
if ([addressBookEntry objectForKey:KEY_ORIGINAL_GUID]) {
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO]
forKey:[NSString stringWithFormat:ASK_ABOUT_OUTDATED_FORMAT,
[addressBookEntry objectForKey:KEY_ORIGINAL_GUID]]];
}
[PTYSession reloadAllBookmarks];
}
+ (BOOL)_recursiveSelectMenuItem:(NSString*)theName inMenu:(NSMenu*)menu
{
for (NSMenuItem* item in [menu itemArray]) {
if (![item isEnabled] || [item isHidden] || [item isAlternate]) {
continue;