-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPTYSession.m
1955 lines (1635 loc) · 50.8 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 <iTerm/PseudoTerminal.h>
#import <iTerm/iTermController.h>
#import <iTerm/NSStringITerm.h>
#import <iTerm/iTermKeyBindingMgr.h>
#import <iTerm/ITAddressBookMgr.h>
#import <iTerm/iTermTerminalProfileMgr.h>
#import <iTerm/iTermDisplayProfileMgr.h>
//#import <iTerm/iTermGrowlDelegate.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
@implementation PTYSession
static NSString *TERM_ENVNAME = @"TERM";
static NSString *COLORFGBG_ENVNAME = @"COLORFGBG";
static NSString *PWD_ENVNAME = @"PWD";
static NSString *PWD_ENVVALUE = @"~";
// tab label attributes
static NSColor *normalStateColor;
static NSColor *chosenStateColor;
static NSColor *idleStateColor;
static NSColor *newOutputStateColor;
static NSColor *deadStateColor;
static NSImage *warningImage;
+ (void)initialize
{
NSBundle *thisBundle;
NSString *imagePath;
thisBundle = [NSBundle bundleForClass: [self class]];
imagePath = [thisBundle pathForResource:@"important" ofType:@"png"];
if (imagePath) {
warningImage = [[NSImage alloc] initByReferencingFile: imagePath];
//NSLog(@"%@\n%@",imagePath,warningImage);
}
normalStateColor = [NSColor blackColor];
chosenStateColor = [NSColor blackColor];
idleStateColor = [NSColor redColor];
newOutputStateColor = [NSColor purpleColor];
deadStateColor = [NSColor grayColor];
}
// init/dealloc
- (id)init
{
if((self = [super init]) == nil)
return (nil);
gettimeofday(&lastInput, NULL);
lastOutput = lastBlink = lastInput;
EXIT=NO;
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;
return (self);
}
- (void)dealloc
{
#if DEBUG_ALLOC
NSLog(@"%s: 0x%x", __PRETTY_FUNCTION__, self);
#endif
[icon release];
[TERM_VALUE release];
[COLORFGBG_VALUE release];
[view release];
[name release];
[windowTitle release];
[addressBookEntry release];
[backgroundImagePath release];
[antiIdleTimer invalidate];
[antiIdleTimer release];
[updateTimer invalidate];
[updateTimer release];
[SHELL release];
SHELL = nil;
[SCREEN release];
SCREEN = nil;
[TERMINAL release];
TERMINAL = nil;
[[NSNotificationCenter defaultCenter] removeObserver: self];
[super dealloc];
#if DEBUG_ALLOC
NSLog(@"%s: 0x%x, done", __PRETTY_FUNCTION__, self);
#endif
}
// Session specific methods
- (BOOL)initScreen: (NSRect) aRect width:(int)width height:(int) height
{
NSSize aSize;
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession initScreen]", __FILE__, __LINE__);
#endif
[SCREEN setSession:self];
// Allocate a scrollview
SCROLLVIEW = [[PTYScrollView alloc] initWithFrame: NSMakeRect(0, 0, aRect.size.width, aRect.size.height)];
[SCROLLVIEW setHasVerticalScroller:![parent fullScreen] && ![[PreferencePanel sharedInstance] hideScrollbar]];
NSParameterAssert(SCROLLVIEW != nil);
[SCROLLVIEW setAutoresizingMask: NSViewWidthSizable|NSViewHeightSizable];
// assign the main view
view = SCROLLVIEW;
// Allocate a text view
aSize = [SCROLLVIEW contentSize];
TEXTVIEW = [[PTYTextView alloc] initWithFrame: NSMakeRect(0, 0, aSize.width, aSize.height)];
[TEXTVIEW setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
[TEXTVIEW setUseTransparency: [parent useTransparency]];
// assign terminal and task objects
[SCREEN setShellTask:SHELL];
[SCREEN setTerminal:TERMINAL];
[TERMINAL setScreen: SCREEN];
[SHELL setDelegate:self];
// initialize the screen
if ([SCREEN initScreenWithWidth:width Height:height]) {
[self setName:@"Shell"];
[self setDefaultName:@"Shell"];
[TEXTVIEW setDataSource: SCREEN];
[TEXTVIEW setDelegate: self];
[SCROLLVIEW setDocumentView:TEXTVIEW];
[TEXTVIEW release];
[SCROLLVIEW setDocumentCursor: [PTYTextView textViewCursor]];
ai_code=0;
[antiIdleTimer release];
antiIdleTimer = nil;
newOutput = NO;
// register for some notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(tabViewWillRedraw:)
name:@"iTermTabViewWillRedraw" object:nil];
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;
}
}
- (BOOL) isActiveSession
{
return ([[[self tabViewItem] tabView] selectedTabViewItem] == [self tabViewItem]);
}
- (void)startProgram:(NSString *)program
arguments:(NSArray *)prog_argv
environment:(NSDictionary *)prog_env
{
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:COLORFGBG_ENVNAME] == nil && COLORFGBG_VALUE != nil)
[env setObject:COLORFGBG_VALUE forKey:COLORFGBG_ENVNAME];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
NSString* locale = [self _getLocale];
if(locale != nil) {
[env setObject:locale forKey:@"LANG"];
[env setObject:locale forKey:@"LC_COLLATE"];
[env setObject:locale forKey:@"LC_CTYPE"];
[env setObject:locale forKey:@"LC_MESSAGES"];
[env setObject:locale forKey:@"LC_MONETARY"];
[env setObject:locale forKey:@"LC_NUMERIC"];
[env setObject:locale forKey:@"LC_TIME"];
}
#endif
if ([env objectForKey:PWD_ENVNAME] == nil)
[env setObject:[PWD_ENVVALUE stringByExpandingTildeInPath] forKey:PWD_ENVNAME];
[SHELL launchWithPath:path
arguments:argv
environment:env
width:[SCREEN width]
height:[SCREEN height]];
}
- (void) terminate
{
// deregister from the notification center
[[NSNotificationCenter defaultCenter] removeObserver:self];
EXIT = YES;
[SHELL stop];
// final update of display
[self updateDisplay];
[addressBookEntry release];
addressBookEntry = nil;
[TEXTVIEW setDataSource: nil];
[TEXTVIEW setDelegate: nil];
[TEXTVIEW removeFromSuperview];
[SHELL setDelegate:nil];
[SCREEN setShellTask:nil];
[SCREEN setSession: nil];
[SCREEN setTerminal: nil];
[TERMINAL setScreen: nil];
[updateTimer invalidate];
[updateTimer release];
updateTimer = nil;
parent = nil;
}
- (void)writeTask:(NSData*)data
{
// check if we want to send this input to all the sessions
if([parent sendInputToAllSessions] == NO) {
if (!EXIT) {
[self setBell: NO];
PTYScroller* ptys=(PTYScroller*)[SCROLLVIEW verticalScroller];
[SHELL writeTask: data];
[ptys setUserScroll:NO];
}
}
else {
// send to all sessions
[parent sendInputToAllSessions: data];
}
}
- (void)readTask:(NSData*)data
{
if([data length] == 0 || EXIT)
return;
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession readTask:%@]", __FILE__, __LINE__,
[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:nil]);
#endif
[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)
{
if (token.type == VT100_NOTSUPPORT) {
//NSLog(@"%s(%d):not support token", __FILE__ , __LINE__);
}
else {
[SCREEN putToken:token];
}
}
} // end token processing loop
gettimeofday(&lastOutput, NULL);
newOutput=YES;
// Make sure the screen gets redrawn soonish
[self scheduleUpdateSoon:YES];
}
- (void)brokenPipe
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession brokenPipe]", __FILE__, __LINE__);
#endif
#if 0
[gd growlNotify:NSLocalizedStringFromTableInBundle(@"Broken Pipe",@"iTerm", [NSBundle bundleForClass: [self class]], @"Growl Alerts")
withDescription:[NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"Session %@ #%d just terminated.",@"iTerm", [NSBundle bundleForClass: [self class]], @"Growl Alerts"),[self name],[self realObjectCount]]
andNotification:@"Broken Pipes"];
#endif
EXIT=YES;
[self setLabelAttribute];
if ([self autoClose]) {
[parent closeSession: self];
}
else
{
[self updateDisplay];
}
}
- (BOOL) hasKeyMappingForEvent: (NSEvent *) event highPriority: (BOOL) priority
{
unsigned int modflag;
unsigned short keycode;
NSString *keystr;
NSString *unmodkeystr;
unichar unicode, unmodunicode;
int keyBindingAction;
NSString *keyBindingText;
BOOL keyBindingPriority;
modflag = [event modifierFlags];
keycode = [event keyCode];
keystr = [event characters];
unmodkeystr = [event charactersIgnoringModifiers];
unicode = [keystr length]>0?[keystr characterAtIndex:0]:0;
unmodunicode = [unmodkeystr length]>0?[unmodkeystr 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 singleInstance] actionForKeyCode: unmodunicode
modifiers: modflag
highPriority: &keyBindingPriority
text: &keyBindingText
profile: [[self addressBookEntry] objectForKey: KEY_KEYBOARD_PROFILE]];
return (keyBindingAction >= 0 && keyBindingPriority >= priority);
}
// Screen for special keys
- (void)keyDown:(NSEvent *)event
{
unsigned char *send_str = NULL;
unsigned char *dataPtr = NULL;
int dataLength = 0;
size_t send_strlen = 0;
int send_pchr = -1;
int keyBindingAction;
NSString *keyBindingText;
BOOL priority;
unsigned int modflag;
unsigned short keycode;
NSString *keystr;
NSString *unmodkeystr;
unichar unicode, unmodunicode;
#if DEBUG_METHOD_TRACE || DEBUG_KEYDOWNDUMP
NSLog(@"%s(%d):-[PseudoTerminal keyDown:%@]",
__FILE__, __LINE__, event);
#endif
if (EXIT) return;
modflag = [event modifierFlags];
keycode = [event keyCode];
keystr = [event characters];
unmodkeystr = [event charactersIgnoringModifiers];
unicode = [keystr length]>0?[keystr characterAtIndex:0]:0;
unmodunicode = [unmodkeystr length]>0?[unmodkeystr characterAtIndex:0]:0;
gettimeofday(&lastInput, NULL);
//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 singleInstance] actionForKeyCode: unmodunicode
modifiers: modflag
highPriority: &priority
text: &keyBindingText
profile: [[self addressBookEntry] objectForKey: KEY_KEYBOARD_PROFILE]];
if(keyBindingAction >= 0)
{
NSString *aString;
unsigned char hexCode;
int hexCodeTmp;
switch (keyBindingAction)
{
case KEY_ACTION_NEXT_SESSION:
[parent nextSession: nil];
break;
case KEY_ACTION_NEXT_WINDOW:
[[iTermController sharedInstance] nextTerminal: nil];
break;
case KEY_ACTION_PREVIOUS_SESSION:
[parent previousSession: nil];
break;
case KEY_ACTION_PREVIOUS_WINDOW:
[[iTermController sharedInstance] previousTerminal: nil];
break;
case KEY_ACTION_SCROLL_END:
[TEXTVIEW scrollEnd];
[(PTYScrollView *)[TEXTVIEW enclosingScrollView] detectUserScroll];
break;
case KEY_ACTION_SCROLL_HOME:
[TEXTVIEW scrollHome];
[(PTYScrollView *)[TEXTVIEW enclosingScrollView] detectUserScroll];
break;
case KEY_ACTION_SCROLL_LINE_DOWN:
[TEXTVIEW scrollLineDown: self];
[(PTYScrollView *)[TEXTVIEW enclosingScrollView] detectUserScroll];
break;
case KEY_ACTION_SCROLL_LINE_UP:
[TEXTVIEW scrollLineUp: self];
[(PTYScrollView *)[TEXTVIEW enclosingScrollView] detectUserScroll];
break;
case KEY_ACTION_SCROLL_PAGE_DOWN:
[TEXTVIEW scrollPageDown: self];
[(PTYScrollView *)[TEXTVIEW enclosingScrollView] detectUserScroll];
break;
case KEY_ACTION_SCROLL_PAGE_UP:
[TEXTVIEW scrollPageUp: self];
[(PTYScrollView *)[TEXTVIEW enclosingScrollView] detectUserScroll];
break;
case KEY_ACTION_ESCAPE_SEQUENCE:
if([keyBindingText length] > 0)
{
aString = [NSString stringWithFormat:@"\e%@", keyBindingText];
[self writeTask: [aString dataUsingEncoding: NSUTF8StringEncoding]];
}
break;
case KEY_ACTION_HEX_CODE:
if([keyBindingText length] > 0 && sscanf([keyBindingText UTF8String], "%x", &hexCodeTmp) == 1)
{
hexCode = (unsigned char) hexCodeTmp;
[self writeTask:[NSData dataWithBytes:&hexCode length: sizeof(hexCode)]];
}
break;
case KEY_ACTION_TEXT:
if([keyBindingText length] > 0)
{
NSMutableString *aString = [NSMutableString stringWithString: keyBindingText];
[aString replaceOccurrencesOfString:@"\\n" withString:@"\n" options:NSLiteralSearch range:NSMakeRange(0,[aString length])];
[aString replaceOccurrencesOfString:@"\\e" withString:@"\e" options:NSLiteralSearch range:NSMakeRange(0,[aString length])];
[aString replaceOccurrencesOfString:@"\\a" withString:@"\a" options:NSLiteralSearch range:NSMakeRange(0,[aString length])];
[aString replaceOccurrencesOfString:@"\\t" withString:@"\t" options:NSLiteralSearch range:NSMakeRange(0,[aString length])];
[self writeTask: [aString dataUsingEncoding: NSUTF8StringEncoding]];
}
break;
case KEY_ACTION_IGNORE:
break;
default:
NSLog(@"Unknown key action %d", keyBindingAction);
break;
}
}
// else do standard handling of event
else
{
if (modflag & NSFunctionKeyMask)
{
NSData *data = nil;
switch(unicode)
{
case NSUpArrowFunctionKey: data = [TERMINAL keyArrowUp:modflag]; break;
case NSDownArrowFunctionKey: data = [TERMINAL keyArrowDown:modflag]; break;
case NSLeftArrowFunctionKey: data = [TERMINAL keyArrowLeft:modflag]; break;
case NSRightArrowFunctionKey: data = [TERMINAL keyArrowRight:modflag]; break;
case NSInsertFunctionKey:
// case NSHelpFunctionKey:
data = [TERMINAL keyInsert]; break;
case NSDeleteFunctionKey:
data = [TERMINAL keyDelete]; break;
case NSHomeFunctionKey: data = [TERMINAL keyHome:modflag]; break;
case NSEndFunctionKey: data = [TERMINAL keyEnd:modflag]; break;
case NSPageUpFunctionKey: data = [TERMINAL keyPageUp]; break;
case NSPageDownFunctionKey: data = [TERMINAL keyPageDown]; break;
case NSPrintScreenFunctionKey:
break;
case NSScrollLockFunctionKey:
case NSPauseFunctionKey:
break;
case NSClearLineFunctionKey:
data = [@"\e" dataUsingEncoding: NSUTF8StringEncoding];
break;
}
if (NSF1FunctionKey<=unicode&&unicode<=NSF35FunctionKey)
data = [TERMINAL keyFunction:unicode-NSF1FunctionKey+1];
if (data != nil) {
send_str = (unsigned char *)[data bytes];
send_strlen = [data length];
}
else if (keystr != nil) {
NSData *keydat = ((modflag & NSControlKeyMask) && unicode>0)?
[keystr dataUsingEncoding:NSUTF8StringEncoding]:
[unmodkeystr dataUsingEncoding:NSUTF8StringEncoding];
send_str = (unsigned char *)[keydat bytes];
send_strlen = [keydat length];
}
}
else if ((modflag & NSAlternateKeyMask) &&
([self optionKey] != OPT_NORMAL))
{
NSData *keydat = ((modflag & NSControlKeyMask) && unicode>0)?
[keystr dataUsingEncoding:NSUTF8StringEncoding]:
[unmodkeystr dataUsingEncoding:NSUTF8StringEncoding];
// META combination
if (keydat != nil) {
send_str = (unsigned char *)[keydat bytes];
send_strlen = [keydat length];
}
if ([self optionKey] == OPT_ESC) {
send_pchr = '\e';
}
else if ([self optionKey] == OPT_META && send_str != NULL)
{
int i;
for (i = 0; i < send_strlen; ++i)
send_str[i] |= 0x80;
}
}
else
{
int max = [keystr length];
NSData *data=nil;
if (max!=1||[keystr characterAtIndex:0] > 0x7f)
data = [keystr dataUsingEncoding:[TERMINAL encoding]];
else
data = [keystr dataUsingEncoding:NSUTF8StringEncoding];
// Enter key is on numeric keypad, but not marked as such
if (unicode == NSEnterCharacter && unmodunicode == NSEnterCharacter) {
modflag |= NSNumericPadKeyMask;
keystr = @"\015"; // Enter key -> 0x0d
}
// Check if we are in keypad mode
if (modflag & NSNumericPadKeyMask) {
data = [TERMINAL keypadData: unicode keystr: keystr];
}
if (data != nil ) {
send_str = (unsigned char *)[data bytes];
send_strlen = [data length];
}
// NSLog(@"modflag = 0x%x; send_strlen = %d; send_str[0] = '%c (0x%x)'", modflag, send_strlen, send_str[0]);
if (modflag & NSControlKeyMask &&
send_strlen == 1 &&
send_str[0] == '|')
{
send_str = (unsigned char*)"\034"; // control-backslash
send_strlen = 1;
}
else if ((modflag & NSControlKeyMask) &&
(modflag & NSShiftKeyMask) &&
send_strlen == 1 &&
send_str[0] == '/')
{
send_str = (unsigned char*)"\177"; // control-?
send_strlen = 1;
}
else if (modflag & NSControlKeyMask &&
send_strlen == 1 &&
send_str[0] == '/')
{
send_str = (unsigned char*)"\037"; // control-/
send_strlen = 1;
}
else if (modflag & NSShiftKeyMask &&
send_strlen == 1 &&
send_str[0] == '\031')
{
send_str = (unsigned char*)"\033[Z"; // backtab
send_strlen = 3;
}
}
if (EXIT == NO )
{
if (send_pchr >= 0) {
char c = send_pchr;
dataPtr = (unsigned char*)&c;
dataLength = 1;
[self writeTask:[NSData dataWithBytes:dataPtr length:dataLength]];
}
if (send_str != NULL) {
dataPtr = send_str;
dataLength = send_strlen;
[self writeTask:[NSData dataWithBytes:dataPtr length:dataLength]];
}
}
}
}
- (BOOL)willHandleEvent: (NSEvent *) theEvent
{
// Handle the option-click event
return 0;
/* return (([theEvent type] == NSLeftMouseDown) &&
([theEvent modifierFlags] & NSAlternateKeyMask)); */
}
- (void)handleEvent: (NSEvent *) theEvent
{
// We handle option-click to position the cursor...
/*if(([theEvent type] == NSLeftMouseDown) &&
([theEvent modifierFlags] & NSAlternateKeyMask))
[self handleOptionClick: theEvent]; */
}
- (void) handleOptionClick: (NSEvent *) theEvent
{
if (EXIT) return;
// Here we will attempt to position the cursor to the mouse-click
NSPoint locationInWindow, locationInTextView, locationInScrollView;
int x, y;
float w=[parent charWidth], h=[parent charHeight];
locationInWindow = [theEvent locationInWindow];
locationInTextView = [TEXTVIEW convertPoint: locationInWindow fromView: nil];
locationInScrollView = [SCROLLVIEW convertPoint: locationInWindow fromView: nil];
x = locationInTextView.x/w;
y = locationInScrollView.y/h + 1;
// NSLog(@"loc_x = %f; loc_y = %f", locationInTextView.x, locationInScrollView.y);
// NSLog(@"font width = %f, font height = %f", fontSize.width, fontSize.height);
// NSLog(@"x = %d; y = %d", x, y);
if(x == [SCREEN cursorX] && y == [SCREEN cursorY])
return;
NSData *data;
int i;
// now move the cursor up or down
for(i = 0; i < abs(y - [SCREEN cursorY]); i++)
{
if(y < [SCREEN cursorY])
data = [TERMINAL keyArrowUp:0];
else
data = [TERMINAL keyArrowDown:0];
[self writeTask:[NSData dataWithBytes:[data bytes] length:[data length]]];
}
// now move the cursor left or right
for(i = 0; i < abs(x - [SCREEN cursorX]); i++)
{
if(x < [SCREEN cursorX])
data = [TERMINAL keyArrowLeft:0];
else
data = [TERMINAL keyArrowRight:0];
[self writeTask:[NSData dataWithBytes:[data bytes] length:[data length]]];
}
// trigger an update of the display.
[TEXTVIEW setNeedsDisplay:YES];
}
- (void)insertText:(NSString *)string
{
NSData *data;
NSMutableString *mstring;
int i, max;
if (EXIT) return;
// NSLog(@"insertText: %@",string);
mstring = [NSMutableString stringWithString:string];
max = [string length];
for(i=0; i<max; i++) {
if ([mstring characterAtIndex:i] == 0xa5) {
[mstring replaceCharactersInRange:NSMakeRange(i, 1) withString:@"\\"];
}
}
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession insertText:%@]",
__FILE__, __LINE__, mstring);
#endif
data = [mstring dataUsingEncoding:[TERMINAL encoding]
allowLossyConversion:YES];
if (data != nil)
[self writeTask:data];
// let the update thred update display if a key is being held down
/*if([TEXTVIEW keyIsARepeat] == NO)
[self updateDisplay];*/
}
- (void)insertNewline:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession insertNewline:%@]",
__FILE__, __LINE__, sender);
#endif
[self insertText:@"\n"];
}
- (void)insertTab:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession insertTab:%@]",
__FILE__, __LINE__, sender);
#endif
[self insertText:@"\t"];
}
- (void)moveUp:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession moveUp:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[TERMINAL keyArrowUp:0]];
}
- (void)moveDown:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession moveDown:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[TERMINAL keyArrowDown:0]];
}
- (void)moveLeft:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession moveLeft:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[TERMINAL keyArrowLeft:0]];
}
- (void)moveRight:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession moveRight:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[TERMINAL keyArrowRight:0]];
}
- (void)pageUp:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession pageUp:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[TERMINAL keyPageUp]];
}
- (void)pageDown:(id)sender
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession pageDown:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[TERMINAL keyPageDown]];
}
- (void)paste:(id)sender
{
NSPasteboard *board;
NSMutableString *str;
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession paste:...]", __FILE__, __LINE__);
#endif
board = [NSPasteboard generalPasteboard];
NSParameterAssert(board != nil );
str = [[[NSMutableString alloc] initWithString:[board stringForType:NSStringPboardType]] autorelease];
if ([sender tag]) // paste with escape;
{
[str replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
[str replaceOccurrencesOfString:@"'" withString:@"\\'" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
[str replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
[str replaceOccurrencesOfString:@" " withString:@"\\ " options:NSLiteralSearch range:NSMakeRange(0, [str length])];
}
[self pasteString: str];
}
- (void) pasteString: (NSString *) aString
{
if ([aString length] > 0)
{
NSString *tempString = [aString stringReplaceSubstringFrom:@"\r\n" to:@"\r"];
[self writeTask: [[tempString stringReplaceSubstringFrom:@"\n" to:@"\r"]
dataUsingEncoding:[TERMINAL encoding]
allowLossyConversion:YES]];
}
else
NSBeep();
}
- (void)deleteBackward:(id)sender
{
unsigned char p = 0x08; // Ctrl+H
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession deleteBackward:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[NSData dataWithBytes:&p length:1]];
}
- (void)deleteForward:(id)sender
{
unsigned char p = 0x7F; // DEL
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession deleteForward:%@]",
__FILE__, __LINE__, sender);
#endif
[self writeTask:[NSData dataWithBytes:&p length:1]];
}
- (void) textViewDidChangeSelection: (NSNotification *) aNotification
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s(%d):-[PTYSession textViewDidChangeSelection]",
__FILE__, __LINE__);
#endif
if([[PreferencePanel sharedInstance] copySelection])
[TEXTVIEW copy: self];
}
- (void) textViewResized: (NSNotification *) aNotification;
{
#if DEBUG_METHOD_TRACE
NSLog(@"%s: textView = 0x%x", __PRETTY_FUNCTION__, TEXTVIEW);
#endif
int w, h;
w = (int)(([[SCROLLVIEW contentView] frame].size.width - MARGIN * 2)/[parent charWidth]);
h = (int)(([[SCROLLVIEW contentView] frame].size.height)/[parent charHeight]);
//NSLog(@"%s: w = %d; h = %d; old w = %d; old h = %d", __PRETTY_FUNCTION__, w, h, [SCREEN width], [SCREEN height]);
[SCREEN resizeWidth:w height:h];
[SHELL setWidth:w height:h];
}
- (void) setLabelAttribute
{
struct timeval now;
gettimeofday(&now, NULL);
if ([self exited])
{
// dead
[parent setLabelColor: deadStateColor forTabViewItem: tabViewItem];
if(isProcessing)
[self setIsProcessing: NO];
}
else if([[tabViewItem tabView] selectedTabViewItem] != tabViewItem)
{
if (now.tv_sec > lastOutput.tv_sec+2) {
if(isProcessing)
[self setIsProcessing: NO];
if (newOutput)
{
// Idle after new output
#if 0
if (!growlIdle && now.tv_sec > lastOutput.tv_sec+1) {
[gd growlNotify:NSLocalizedStringFromTableInBundle(@"Idle",@"iTerm", [NSBundle bundleForClass: [self class]], @"Growl Alerts")
withDescription:[NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"Session %@ #%d becomes idle.",@"iTerm", [NSBundle bundleForClass: [self class]], @"Growl Alerts"),[self name],[self realObjectCount]]
andNotification:@"Idle"];
growlIdle = YES;
growlNewOutput = NO;
}
#endif
[parent setLabelColor: idleStateColor forTabViewItem: tabViewItem];
}
else
{
// normal state
[parent setLabelColor: normalStateColor forTabViewItem: tabViewItem];
}
}
else
{
if (newOutput) {
if(isProcessing == NO && ![[PreferencePanel sharedInstance] useCompactLabel])
[self setIsProcessing: YES];
#if 0
if (!growlNewOutput && ![parent sendInputToAllSessions]) {
[gd growlNotify:NSLocalizedStringFromTableInBundle(@"New Output",@"iTerm", [NSBundle bundleForClass: [self class]], @"Growl Alerts")
withDescription:[NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"New Output was received in %@ #%d.",@"iTerm", [NSBundle bundleForClass: [self class]], @"Growl Alerts"),[self name],[self realObjectCount]]
andNotification:@"New Output"];
growlNewOutput=YES;
}
#endif
[parent setLabelColor: newOutputStateColor forTabViewItem: tabViewItem];
}
}
}
else {
// front tab
if(isProcessing)
[self setIsProcessing: NO];
growlNewOutput=NO;
newOutput = NO;
[parent setLabelColor: chosenStateColor forTabViewItem: tabViewItem];
}
//[self setBell:NO];