-
Notifications
You must be signed in to change notification settings - Fork 33
/
hterm_vt.js
3475 lines (3085 loc) · 88.4 KB
/
hterm_vt.js
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
// Copyright 2012 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {lib} from '../../libdot/index.js';
import {hterm} from '../index.js';
/**
* Constructor for the VT escape sequence interpreter.
*
* The interpreter operates on a terminal object capable of performing cursor
* move operations, painting characters, etc.
*
* This interpreter is intended to be compatible with xterm, though it
* ignores some of the more esoteric escape sequences.
*
* Control sequences are documented in hterm/docs/ControlSequences.md.
*
* @param {!hterm.Terminal} terminal Terminal to use with the interpreter.
* @constructor
*/
hterm.VT = function(terminal) {
/**
* The display terminal object associated with this virtual terminal.
*/
this.terminal = terminal;
terminal.onMouse = this.onTerminalMouse_.bind(this);
this.mouseReport = this.MOUSE_REPORT_DISABLED;
this.mouseCoordinates = this.MOUSE_COORDINATES_X10;
// We only want to report mouse moves between cells, not between pixels.
this.lastMouseDragResponse_ = null;
// Parse state left over from the last parse. You should use the parseState
// instance passed into your parse routine, rather than reading
// this.parseState_ directly.
this.parseState_ = new hterm.VT.ParseState(this.parseUnknown_);
// Any "leading modifiers" for the escape sequence, such as '?', ' ', or the
// other modifiers handled in this.parseCSI_.
this.leadingModifier_ = '';
// Any "trailing modifiers". Same character set as a leading modifier,
// except these are found after the numeric arguments.
this.trailingModifier_ = '';
// Whether or not to respect the escape codes for setting terminal width.
this.allowColumnWidthChanges_ = false;
// The amount of time we're willing to wait for the end of an OSC sequence.
this.oscTimeLimit_ = 20000;
/**
* Whether to accept the 8-bit control characters.
*
* An 8-bit control character is one with the eighth bit set. These
* didn't work on 7-bit terminals so they all have two byte equivalents.
* Most hosts still only use the two-byte versions.
*
* We ignore 8-bit control codes by default. This is in order to avoid
* issues with "accidental" usage of codes that need to be terminated.
* The "accident" usually involves cat'ing binary data.
*/
this.enable8BitControl = false;
/**
* Whether to allow the OSC 52 sequence to write to the system clipboard.
*/
this.enableClipboardWrite = true;
/**
* Respect the host's attempt to change the cursor blink status using
* the DEC Private mode 12.
*/
this.enableDec12 = false;
/**
* Respect the host's attempt to clear the scrollback buffer using CSI-J-3.
*/
this.enableCsiJ3 = true;
/**
* If true, emit warnings when we encounter a control character or escape
* sequence that we don't recognize or explicitly ignore.
*
* We disable this by default as the console logging can be expensive when
* dumping binary files (e.g. `cat /dev/zero`) to the point where you can't
* recover w/out restarting.
*/
this.warnUnimplemented = false;
/**
* The set of available character maps (used by G0...G3 below).
*/
this.characterMaps = new hterm.VT.CharacterMaps();
/**
* The default G0...G3 character maps.
* We default to the US/ASCII map everywhere as that aligns with other
* terminals, and it makes it harder to accidentally switch to the graphics
* character map (Ctrl+N). Any program that wants to use the graphics map
* will usually select it anyways since there's no guarantee what state any
* of the maps are in at any particular time.
*/
this.G0 = this.G1 = this.G2 = this.G3 =
this.characterMaps.getMap('B');
/**
* The 7-bit visible character set.
*
* This is a mapping from inbound data to display glyph. The GL set
* contains the 94 bytes from 0x21 to 0x7e.
*
* The default GL set is 'B', US ASCII.
*/
this.GL = 'G0';
/**
* The 8-bit visible character set.
*
* This is a mapping from inbound data to display glyph. The GR set
* contains the 94 bytes from 0xa1 to 0xfe.
*/
this.GR = 'G0';
/**
* The current encoding of the terminal.
*
* We only support ECMA-35 and UTF-8, so go with a boolean here.
* The encoding can be locked too.
*/
this.codingSystemUtf8_ = false;
this.codingSystemLocked_ = false;
// Construct a regular expression to match the known one-byte control chars.
// This is used in parseUnknown_ to quickly scan a string for the next
// control character.
this.cc1Pattern_ = null;
this.updateEncodingState_();
};
/**
* No mouse events.
*/
hterm.VT.prototype.MOUSE_REPORT_DISABLED = 0;
/**
* DECSET mode 9.
*
* Report mouse down events only.
*/
hterm.VT.prototype.MOUSE_REPORT_PRESS = 1;
/**
* DECSET mode 1000.
*
* Report mouse down/up events only.
*/
hterm.VT.prototype.MOUSE_REPORT_CLICK = 2;
/**
* DECSET mode 1002.
*
* Report mouse down/up and movement while a button is down.
*/
hterm.VT.prototype.MOUSE_REPORT_DRAG = 3;
/**
* DEC mode for X10 coorindates (the default).
*/
hterm.VT.prototype.MOUSE_COORDINATES_X10 = 0;
/**
* DEC mode 1005 for UTF-8 coorindates.
*/
hterm.VT.prototype.MOUSE_COORDINATES_UTF8 = 1;
/**
* DEC mode 1006 for SGR coorindates.
*/
hterm.VT.prototype.MOUSE_COORDINATES_SGR = 2;
/**
* ParseState constructor.
*
* This object tracks the current state of the parse. It has fields for the
* current buffer, position in the buffer, and the parse function.
*
* @param {function(!hterm.VT.ParseState)=} defaultFunction The default parser
* function.
* @param {?string=} buf Optional string to use as the current buffer.
* @constructor
*/
hterm.VT.ParseState = function(defaultFunction, buf = null) {
this.defaultFunction = defaultFunction;
this.buf = buf;
this.pos = 0;
this.func = defaultFunction;
this.args = [];
// Whether any of the arguments in the args array have subarguments.
// e.g. All CSI sequences are integer arguments separated by semi-colons,
// so subarguments are further colon separated.
this.subargs = null;
};
/**
* Reset the parser function, buffer, and position.
*
* @param {string=} buf Optional string to use as the current buffer.
*/
hterm.VT.ParseState.prototype.reset = function(buf = '') {
this.resetParseFunction();
this.resetBuf(buf);
this.resetArguments();
};
/**
* Reset the parser function only.
*/
hterm.VT.ParseState.prototype.resetParseFunction = function() {
this.func = this.defaultFunction;
};
/**
* Reset the buffer and position only.
*
* @param {?string=} buf Optional new value for buf, defaults to null.
*/
hterm.VT.ParseState.prototype.resetBuf = function(buf = null) {
this.buf = buf;
this.pos = 0;
};
/**
* Reset the arguments list only.
*
* Typically we reset arguments before parsing a sequence that uses them rather
* than always trying to make sure they're in a good state. This can lead to
* confusion during debugging where args from a previous sequence appear to be
* "sticking around" in other sequences (which in reality don't use args).
*
* @param {string=} arg_zero Optional initial value for args[0].
*/
hterm.VT.ParseState.prototype.resetArguments = function(arg_zero = undefined) {
this.args.length = 0;
if (arg_zero !== undefined) {
this.args[0] = arg_zero;
}
};
/**
* Parse an argument as an integer.
*
* This assumes the inputs are already in the proper format. e.g. This won't
* handle non-numeric arguments.
*
* An "0" argument is treated the same as "" which means the default value will
* be applied. This is what most terminal sequences expect.
*
* @param {string} argstr The argument to parse directly.
* @param {number=} defaultValue Default value if argstr is empty.
* @return {number} The parsed value.
*/
hterm.VT.ParseState.prototype.parseInt = function(argstr, defaultValue) {
if (defaultValue === undefined) {
defaultValue = 0;
}
if (argstr) {
const ret = parseInt(argstr, 10);
// An argument of zero is treated as the default value.
return ret == 0 ? defaultValue : ret;
}
return defaultValue;
};
/**
* Get an argument as an integer.
*
* @param {number} argnum The argument number to retrieve.
* @param {number=} defaultValue Default value if the argument is empty.
* @return {number} The parsed value.
*/
hterm.VT.ParseState.prototype.iarg = function(argnum, defaultValue) {
return this.parseInt(this.args[argnum], defaultValue);
};
/**
* Check whether an argument has subarguments.
*
* @param {number} argnum The argument number to check.
* @return {boolean} Whether the argument has subarguments.
*/
hterm.VT.ParseState.prototype.argHasSubargs = function(argnum) {
return !!(this.subargs && this.subargs[argnum]);
};
/**
* Mark an argument as having subarguments.
*
* @param {number} argnum The argument number that has subarguments.
*/
hterm.VT.ParseState.prototype.argSetSubargs = function(argnum) {
if (this.subargs === null) {
this.subargs = {};
}
this.subargs[argnum] = true;
};
/**
* Advance the parse position.
*
* @param {number} count The number of bytes to advance.
*/
hterm.VT.ParseState.prototype.advance = function(count) {
this.pos += count;
};
/**
* Return the remaining portion of the buffer without affecting the parse
* position.
*
* @return {string} The remaining portion of the buffer.
*/
hterm.VT.ParseState.prototype.peekRemainingBuf = function() {
return this.buf.substr(this.pos);
};
/**
* Return the next single character in the buffer without affecting the parse
* position.
*
* @return {string} The next character in the buffer.
*/
hterm.VT.ParseState.prototype.peekChar = function() {
return this.buf.substr(this.pos, 1);
};
/**
* Return the next single character in the buffer and advance the parse
* position one byte.
*
* @return {string} The next character in the buffer.
*/
hterm.VT.ParseState.prototype.consumeChar = function() {
return this.buf.substr(this.pos++, 1);
};
/**
* Return true if the buffer is empty, or the position is past the end.
*
* @return {boolean} Whether the buffer is empty, or the position is past the
* end.
*/
hterm.VT.ParseState.prototype.isComplete = function() {
return this.buf == null || this.buf.length <= this.pos;
};
/**
* Reset the parse state.
*/
hterm.VT.prototype.resetParseState = function() {
this.parseState_.reset();
};
/**
* Reset the VT back to baseline state.
*/
hterm.VT.prototype.reset = function() {
this.G0 = this.G1 = this.G2 = this.G3 =
this.characterMaps.getMap('B');
this.GL = 'G0';
this.GR = 'G0';
this.mouseReport = this.MOUSE_REPORT_DISABLED;
this.mouseCoordinates = this.MOUSE_COORDINATES_X10;
this.lastMouseDragResponse_ = null;
};
/**
* Handle terminal mouse events.
*
* See the "Mouse Tracking" section of [xterm].
*
* @param {!MouseEvent} e
*/
hterm.VT.prototype.onTerminalMouse_ = function(e) {
// Short circuit a few events to avoid unnecessary processing.
if (this.mouseReport == this.MOUSE_REPORT_DISABLED) {
return;
} else if (this.mouseReport != this.MOUSE_REPORT_DRAG &&
e.type == 'mousemove') {
return;
}
// Temporary storage for our response.
let response;
// Modifier key state.
let mod = 0;
if (this.mouseReport != this.MOUSE_REPORT_PRESS) {
if (e.shiftKey) {
mod |= 4;
}
if (e.metaKey || (this.terminal.keyboard.altIsMeta && e.altKey)) {
mod |= 8;
}
if (e.ctrlKey) {
mod |= 16;
}
}
// X & Y coordinate reporting.
let x;
let y;
// Normally X10 has a limit of 255, but since we only want to emit UTF-8 valid
// streams, we limit ourselves to 127 to avoid setting the 8th bit. If we do
// re-enable this, we should re-enable the hterm_vt_tests.js too.
let limit = 127;
switch (this.mouseCoordinates) {
case this.MOUSE_COORDINATES_UTF8:
// UTF-8 mode is the same as X10 but with higher limits.
limit = 2047;
case this.MOUSE_COORDINATES_X10:
// X10 reports coordinates by encoding into strings.
x = String.fromCharCode(lib.f.clamp(e.terminalColumn + 32, 32, limit));
y = String.fromCharCode(lib.f.clamp(e.terminalRow + 32, 32, limit));
break;
case this.MOUSE_COORDINATES_SGR:
// SGR reports coordinates by transmitting the numbers directly.
x = e.terminalColumn;
y = e.terminalRow;
break;
}
let b;
switch (e.type) {
case 'wheel':
// Mouse wheel is treated as button 1 or 2 plus an additional 64.
b = (((e.deltaY * -1) > 0) ? 0 : 1) + 64;
b |= mod;
if (this.mouseCoordinates == this.MOUSE_COORDINATES_SGR) {
response = `\x1b[<${b};${x};${y}M`;
} else {
// X10 based modes (including UTF8) add 32 for legacy encoding reasons.
response = '\x1b[M' + String.fromCharCode(b + 32) + x + y;
}
// Keep the terminal from scrolling.
e.preventDefault();
break;
case 'mousedown':
// Buttons are encoded as button number.
b = Math.min(e.button, 2);
// X10 based modes (including UTF8) add 32 for legacy encoding reasons.
if (this.mouseCoordinates != this.MOUSE_COORDINATES_SGR) {
b += 32;
}
// And mix in the modifier keys.
b |= mod;
if (this.mouseCoordinates == this.MOUSE_COORDINATES_SGR) {
response = `\x1b[<${b};${x};${y}M`;
} else {
response = '\x1b[M' + String.fromCharCode(b) + x + y;
}
break;
case 'mouseup':
if (this.mouseReport != this.MOUSE_REPORT_PRESS) {
if (this.mouseCoordinates == this.MOUSE_COORDINATES_SGR) {
// SGR mode can report the released button.
response = `\x1b[<${e.button};${x};${y}m`;
} else {
// X10 mode has no indication of which button was released.
response = '\x1b[M\x23' + x + y;
}
}
break;
case 'mousemove':
if (this.mouseReport == this.MOUSE_REPORT_DRAG && e.buttons) {
// Standard button bits. The XTerm protocol only reports the first
// button press (e.g. if left & right are pressed, right is ignored),
// and it only supports the first three buttons. If none of them are
// pressed, then XTerm flags it as a release. We'll do the same.
// X10 based modes (including UTF8) add 32 for legacy encoding reasons.
b = this.mouseCoordinates == this.MOUSE_COORDINATES_SGR ? 0 : 32;
// Priority here matches XTerm: left, middle, right.
if (e.buttons & 0x1) {
// Report left button.
b += 0;
} else if (e.buttons & 0x4) {
// Report middle button.
b += 1;
} else if (e.buttons & 0x2) {
// Report right button.
b += 2;
} else {
// Release higher buttons.
b += 3;
}
// Add 32 to indicate mouse motion.
b += 32;
// And mix in the modifier keys.
b |= mod;
if (this.mouseCoordinates == this.MOUSE_COORDINATES_SGR) {
response = `\x1b[<${b};${x};${y}M`;
} else {
response = '\x1b[M' + String.fromCharCode(b) + x + y;
}
// If we were going to report the same cell because we moved pixels
// within, suppress the report. This is what xterm does and cuts
// down on duplicate messages.
if (this.lastMouseDragResponse_ == response) {
response = '';
} else {
this.lastMouseDragResponse_ = response;
}
}
break;
case 'click':
case 'dblclick':
break;
default:
console.error('Unknown mouse event: ' + e.type, e);
break;
}
if (response) {
this.terminal.io.sendString(response);
}
};
/**
* Interpret a string of characters, displaying the results on the associated
* terminal object.
*
* @param {string} buf The buffer to interpret.
*/
hterm.VT.prototype.interpret = function(buf) {
this.parseState_.resetBuf(buf);
while (!this.parseState_.isComplete()) {
const func = this.parseState_.func;
const pos = this.parseState_.pos;
const buf = this.parseState_.buf;
this.parseState_.func.call(this, this.parseState_);
if (this.parseState_.func == func && this.parseState_.pos == pos &&
this.parseState_.buf == buf) {
throw new Error('Parser did not alter the state!');
}
}
};
/**
* Set the encoding of the terminal.
*
* @param {string} encoding The name of the encoding to set.
*/
hterm.VT.prototype.setEncoding = function(encoding) {
switch (encoding) {
default:
console.warn('Invalid value for "terminal-encoding": ' + encoding);
// Fall through.
case 'iso-2022':
this.codingSystemUtf8_ = false;
this.codingSystemLocked_ = false;
break;
case 'utf-8-locked':
this.codingSystemUtf8_ = true;
this.codingSystemLocked_ = true;
break;
case 'utf-8':
this.codingSystemUtf8_ = true;
this.codingSystemLocked_ = false;
break;
}
this.updateEncodingState_();
};
/**
* Refresh internal state when the encoding changes.
*/
hterm.VT.prototype.updateEncodingState_ = function() {
// If we're in UTF8 mode, don't suport 8-bit escape sequences as we'll never
// see those -- everything should be UTF8!
const cc1 = Object.keys(hterm.VT.CC1)
.filter((e) => !this.codingSystemUtf8_ || e.charCodeAt() < 0x80)
.map((e) => '\\x' + lib.f.zpad(e.charCodeAt().toString(16), 2))
.join('');
this.cc1Pattern_ = new RegExp(`[${cc1}]`);
};
/**
* The default parse function.
*
* This will scan the string for the first 1-byte control character (C0/C1
* characters from [CTRL]). Any plain text coming before the code will be
* printed to the terminal, then the control character will be dispatched.
*
* @param {!hterm.VT.ParseState} parseState The current parse state.
*/
hterm.VT.prototype.parseUnknown_ = function(parseState) {
const print = (str) => {
if (!this.codingSystemUtf8_ && this[this.GL].GL) {
str = this[this.GL].GL(str);
}
this.terminal.print(str);
};
// Search for the next contiguous block of plain text.
const buf = parseState.peekRemainingBuf();
const nextControl = buf.search(this.cc1Pattern_);
if (nextControl == 0) {
// We've stumbled right into a control character.
this.dispatch('CC1', buf.substr(0, 1), parseState);
parseState.advance(1);
return;
}
if (nextControl == -1) {
// There are no control characters in this string.
print(buf);
parseState.reset();
return;
}
print(buf.substr(0, nextControl));
this.dispatch('CC1', buf.substr(nextControl, 1), parseState);
parseState.advance(nextControl + 1);
};
/**
* Parse a Control Sequence Introducer code and dispatch it.
*
* See [CSI] for some useful information about these codes.
*
* @param {!hterm.VT.ParseState} parseState The current parse state.
*/
hterm.VT.prototype.parseCSI_ = function(parseState) {
const ch = parseState.peekChar();
const args = parseState.args;
const finishParsing = () => {
// Resetting the arguments isn't strictly necessary, but it makes debugging
// less confusing (otherwise args will stick around until the next sequence
// that needs arguments).
parseState.resetArguments();
// We need to clear subargs since we explicitly set it.
parseState.subargs = null;
parseState.resetParseFunction();
};
if (ch >= '@' && ch <= '~') {
// This is the final character.
this.dispatch('CSI', this.leadingModifier_ + this.trailingModifier_ + ch,
parseState);
finishParsing();
} else if (ch == ';') {
// Parameter delimiter.
if (this.trailingModifier_) {
// Parameter delimiter after the trailing modifier. That's a paddlin'.
finishParsing();
} else {
if (!args.length) {
// They omitted the first param, we need to supply it.
args.push('');
}
args.push('');
}
} else if (ch >= '0' && ch <= '9' || ch == ':') {
// Next byte in the current parameter.
if (this.trailingModifier_) {
// Numeric parameter after the trailing modifier. That's a paddlin'.
finishParsing();
} else {
if (!args.length) {
args[0] = ch;
} else {
args[args.length - 1] += ch;
}
// Possible sub-parameters.
if (ch == ':') {
parseState.argSetSubargs(args.length - 1);
}
}
} else if (ch >= ' ' && ch <= '?') {
// Modifier character.
if (!args.length) {
this.leadingModifier_ += ch;
} else {
this.trailingModifier_ += ch;
}
} else if (this.cc1Pattern_.test(ch)) {
// Control character.
this.dispatch('CC1', ch, parseState);
} else {
// Unexpected character in sequence, bail out.
finishParsing();
}
parseState.advance(1);
};
/**
* Parse a Device Control String and dispatch it.
*
* See [DCS] for some useful information about these codes.
*
* @param {!hterm.VT.ParseState} parseState The current parse state.
*/
hterm.VT.prototype.parseDCS_ = function(parseState) {
const ch = parseState.peekChar();
const args = parseState.args;
const finishParsing = () => {
// Resetting the arguments isn't strictly necessary, but it makes debugging
// less confusing (otherwise args will stick around until the next sequence
// that needs arguments).
parseState.resetArguments();
parseState.resetParseFunction();
};
if (ch >= '@' && ch <= '~') {
// This is the final character.
parseState.advance(1);
this.dispatch('DCS', this.leadingModifier_ + this.trailingModifier_ + ch,
parseState);
// Don't reset the parser function if it's being handled.
// The dispatched method must handle ST termination itself.
if (parseState.func === this.parseDCS_) {
parseState.func = this.parseUntilStringTerminator_;
}
return;
} else if (ch === ';') {
// Parameter delimiter.
if (this.trailingModifier_) {
// Parameter delimiter after the trailing modifier. Abort parsing.
finishParsing();
} else {
if (!args.length) {
// They omitted the first param, we need to supply it.
args.push('');
}
args.push('');
}
} else if (ch >= '0' && ch <= '9') {
// Next byte in the current parameter.
if (this.trailingModifier_) {
// Numeric parameter after the trailing modifier. Abort parsing.
finishParsing();
} else {
if (!args.length) {
args[0] = ch;
} else {
args[args.length - 1] += ch;
}
}
} else if (ch >= ' ' && ch <= '?') {
// Modifier character.
if (!args.length) {
this.leadingModifier_ += ch;
} else {
this.trailingModifier_ += ch;
}
} else if (this.cc1Pattern_.test(ch)) {
// Control character.
this.dispatch('CC1', ch, parseState);
} else {
// Unexpected character in sequence, bail out.
finishParsing();
}
parseState.advance(1);
};
/**
* Parse tmux control mode data, which is terminated with ST.
*
* @param {!hterm.VT.ParseState} parseState
*/
hterm.VT.prototype.parseTmuxControlModeData_ = function(parseState) {
const args = parseState.args;
if (!args.length) {
// This stores the unfinished line.
args[0] = '';
}
// Consume as many lines as possible.
while (true) {
const args0InitialLength = args[0].length;
const buf = args[0] + parseState.peekRemainingBuf();
args[0] = '';
// Find either ST or line break.
// eslint-disable-next-line no-control-regex
const index = buf.search(/\x1b\\|\r\n/);
if (index === -1) {
parseState.args[0] = buf;
parseState.resetBuf();
return;
}
const data = buf.slice(0, index);
parseState.advance(index + 2 - args0InitialLength);
// Check if buf ends with ST.
if (buf[index] === '\x1b') {
if (data) {
console.error(`unexpected data before ST: ${data}`);
}
this.terminal.onTmuxControlModeLine(null);
parseState.resetArguments();
parseState.resetParseFunction();
return;
}
// buf ends with line break.
this.terminal.onTmuxControlModeLine(data);
}
};
/**
* Skip over the string until the next String Terminator (ST, 'ESC \') or
* Bell (BEL, '\x07').
*
* The string is accumulated in parseState.args[0]. Make sure to reset the
* arguments (with parseState.resetArguments) before starting the parse.
*
* You can detect that parsing in complete by checking that the parse
* function has changed back to the default parse function.
*
* @param {!hterm.VT.ParseState} parseState The current parse state.
* @return {boolean} If true, parsing is ongoing or complete. If false, we've
* exceeded the max string sequence.
*/
hterm.VT.prototype.parseUntilStringTerminator_ = function(parseState) {
let buf = parseState.peekRemainingBuf();
const args = parseState.args;
// Since we might modify parse state buffer locally, if we want to advance
// the parse state buffer later on, we need to know how many chars we added.
let bufInserted = 0;
if (!args.length) {
args[0] = '';
args[1] = new Date().getTime();
} else {
// If our saved buffer ends with an escape, it's because we were hoping
// it's an ST split across two buffers. Move it from our saved buffer
// to the start of our current buffer for processing anew.
if (args[0].slice(-1) == '\x1b') {
args[0] = args[0].slice(0, -1);
buf = '\x1b' + buf;
bufInserted = 1;
}
}
// eslint-disable-next-line no-control-regex
const nextTerminator = buf.search(/[\x1b\x07]/);
const terminator = buf[nextTerminator];
let foundTerminator;
// If the next escape we see is not a start of a ST, fall through. This will
// either be invalid (embedded escape), or we'll queue it up (wait for \\).
if (terminator == '\x1b' && buf[nextTerminator + 1] != '\\') {
foundTerminator = false;
} else {
foundTerminator = (nextTerminator != -1);
}
if (!foundTerminator) {
// No terminator here, have to wait for the next string.
args[0] += buf;
let abortReason;
// Special case: If our buffering happens to split the ST (\e\\), we have to
// buffer the content temporarily. So don't reject a trailing escape here,
// instead we let it timeout or be rejected in the next pass.
if (terminator == '\x1b' && nextTerminator != buf.length - 1) {
abortReason = 'embedded escape: ' + nextTerminator;
}
// We stuffed a Date into args[1] above.
const elapsedTime = new Date().getTime() - args[1];
if (elapsedTime > this.oscTimeLimit_) {
abortReason = `timeout expired: ${elapsedTime}s`;
}
if (abortReason) {
if (this.warnUnimplemented) {
console.log('parseUntilStringTerminator_: aborting: ' + abortReason,
args[0]);
}
parseState.reset(args[0]);
return false;
}
parseState.advance(buf.length - bufInserted);
return true;
}
args[0] += buf.substr(0, nextTerminator);
parseState.resetParseFunction();
parseState.advance(nextTerminator +
(terminator == '\x1b' ? 2 : 1) - bufInserted);
return true;
};
/**
* Dispatch to the function that handles a given CC1, ESC, or CSI or VT52 code.
*
* @param {string} type
* @param {string} code
* @param {!hterm.VT.ParseState} parseState The current parse state.
*/
hterm.VT.prototype.dispatch = function(type, code, parseState) {
const handler = hterm.VT[type][code];
if (!handler) {
if (this.warnUnimplemented) {
console.warn(`Unknown ${type} code: ${JSON.stringify(code)}`);
}
return;
}
if (handler == hterm.VT.ignore) {
if (this.warnUnimplemented) {
console.warn(`Ignored ${type} code: ${JSON.stringify(code)}`);
}
return;
}
if (parseState.subargs && !handler.supportsSubargs) {
if (this.warnUnimplemented) {
console.warn(`Ignored ${type} code w/subargs: ${JSON.stringify(code)}`);
}
return;
}
if (type == 'CC1' && code > '\x7f' && !this.enable8BitControl) {
// It's kind of a hack to put this here, but...
//
// If we're dispatching a 'CC1' code, and it's got the eighth bit set,
// but we're not supposed to handle 8-bit codes? Just ignore it.
//
// This prevents an errant (DCS, '\x90'), (OSC, '\x9d'), (PM, '\x9e') or
// (APC, '\x9f') from locking up the terminal waiting for its expected
// (ST, '\x9c') or (BEL, '\x07').
console.warn('Ignoring 8-bit control code: 0x' +
code.charCodeAt(0).toString(16));
return;
}
handler.apply(this, [parseState, code]);
};
/**
* Set one of the ANSI defined terminal mode bits.
*
* Invoked in response to SM/RM.