-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Terminal.ts
2347 lines (2080 loc) · 69 KB
/
Terminal.ts
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
/**
* xterm.js: xterm, in the browser
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
* @license MIT
*
* Terminal Emulation References:
* http://vt100.net/
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* http://invisible-island.net/vttest/
* http://www.inwap.com/pdp10/ansicode.txt
* http://linux.die.net/man/4/console_codes
* http://linux.die.net/man/7/urxvt
*/
import { BufferSet } from './BufferSet';
import { Buffer } from './Buffer';
import { CompositionHelper } from './CompositionHelper';
import { EventEmitter } from './EventEmitter';
import { Viewport } from './Viewport';
import { rightClickHandler, moveTextAreaUnderMouseCursor, pasteHandler, copyHandler } from './handlers/Clipboard';
import { CircularList } from './utils/CircularList';
import { C0 } from './EscapeSequences';
import { InputHandler } from './InputHandler';
import { Parser } from './Parser';
import { Renderer } from './Renderer';
import { Linkifier } from './Linkifier';
import { SelectionManager } from './SelectionManager';
import { CharMeasure } from './utils/CharMeasure';
import * as Browser from './utils/Browser';
import * as Mouse from './utils/Mouse';
import { CHARSETS } from './Charsets';
import { getRawByteCoords } from './utils/Mouse';
import { CustomKeyEventHandler, Charset, LinkMatcherHandler, LinkMatcherValidationCallback, CharData, LineData } from './Types';
import { ITerminal, IBrowser, ITerminalOptions, IInputHandlingTerminal, ILinkMatcherOptions, IViewport, ICompositionHelper } from './Interfaces';
import { BellSound } from './utils/Sounds';
// Declare for RequireJS in loadAddon
declare var define: any;
// Let it work inside Node.js for automated testing purposes.
const document = (typeof window !== 'undefined') ? window.document : null;
/**
* The amount of write requests to queue before sending an XOFF signal to the
* pty process. This number must be small in order for ^C and similar sequences
* to be responsive.
*/
const WRITE_BUFFER_PAUSE_THRESHOLD = 5;
/**
* The number of writes to perform in a single batch before allowing the
* renderer to catch up with a 0ms setTimeout.
*/
const WRITE_BATCH_SIZE = 300;
/**
* The time between cursor blinks. This is driven by JS rather than a CSS
* animation due to a bug in Chromium that causes it to use excessive CPU time.
* See https://github.com/Microsoft/vscode/issues/22900
*/
const CURSOR_BLINK_INTERVAL = 600;
// TODO: Most of the color code should be removed after truecolor is implemented
// Colors 0-15
const tangoColors: string[] = [
// dark:
'#2e3436',
'#cc0000',
'#4e9a06',
'#c4a000',
'#3465a4',
'#75507b',
'#06989a',
'#d3d7cf',
// bright:
'#555753',
'#ef2929',
'#8ae234',
'#fce94f',
'#729fcf',
'#ad7fa8',
'#34e2e2',
'#eeeeec'
];
// Colors 0-15 + 16-255
// Much thanks to TooTallNate for writing this.
const defaultColors: string[] = (function(): string[] {
let colors = tangoColors.slice();
let r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
let i;
// 16-231
i = 0;
for (; i < 216; i++) {
out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
}
// 232-255 (grey)
i = 0;
let c: number;
for (; i < 24; i++) {
c = 8 + i * 10;
out(c, c, c);
}
function out(r: number, g: number, b: number): void {
colors.push('#' + hex(r) + hex(g) + hex(b));
}
function hex(c: number): string {
let s = c.toString(16);
return s.length < 2 ? '0' + s : s;
}
return colors;
})();
const _colors: string[] = defaultColors.slice();
const vcolors: number[][] = (function(): number[][] {
const out: number[][] = [];
let color;
for (let i = 0; i < 256; i++) {
color = parseInt(defaultColors[i].substring(1), 16);
out.push([
(color >> 16) & 0xff,
(color >> 8) & 0xff,
color & 0xff
]);
}
return out;
})();
const DEFAULT_OPTIONS: ITerminalOptions = {
colors: defaultColors,
convertEol: false,
termName: 'xterm',
geometry: [80, 24],
cursorBlink: false,
cursorStyle: 'block',
bellSound: BellSound,
bellStyle: 'none',
scrollback: 1000,
screenKeys: false,
debug: false,
cancelEvents: false,
disableStdin: false,
useFlowControl: false,
tabStopWidth: 8
// programFeatures: false,
// focusKeys: false,
};
export class Terminal extends EventEmitter implements ITerminal, IInputHandlingTerminal {
public textarea: HTMLTextAreaElement;
public element: HTMLElement;
public rowContainer: HTMLElement;
/**
* The HTMLElement that the terminal is created in, set by Terminal.open.
*/
private parent: HTMLElement;
private context: Window;
private document: Document;
private body: HTMLBodyElement;
private viewportScrollArea: HTMLElement;
private viewportElement: HTMLElement;
public selectionContainer: HTMLElement;
private helperContainer: HTMLElement;
private compositionView: HTMLElement;
private charSizeStyleElement: HTMLStyleElement;
private bellAudioElement: HTMLAudioElement;
private visualBellTimer: number;
public browser: IBrowser = <any>Browser;
public options: ITerminalOptions;
private colors: any;
// TODO: This can be changed to an enum or boolean, 0 and 1 seem to be the only options
public cursorState: number;
public cursorHidden: boolean;
public convertEol: boolean;
private sendDataQueue: string;
private customKeyEventHandler: CustomKeyEventHandler;
// The ID from a setInterval that tracks the blink animation. This animation
// is done in JS due to a Chromium bug with CSS animations that thrashed the
// CPU.
private cursorBlinkInterval: NodeJS.Timer;
// modes
public applicationKeypad: boolean;
public applicationCursor: boolean;
public originMode: boolean;
public insertMode: boolean;
public wraparoundMode: boolean; // defaults: xterm - true, vt100 - false
// charset
// The current charset
public charset: Charset;
public gcharset: number;
public glevel: number;
public charsets: Charset[];
// mouse properties
private decLocator: boolean; // This is unstable and never set
public x10Mouse: boolean;
public vt200Mouse: boolean;
private vt300Mouse: boolean; // This is unstable and never set
public normalMouse: boolean;
public mouseEvents: boolean;
public sendFocus: boolean;
public utfMouse: boolean;
public sgrMouse: boolean;
public urxvtMouse: boolean;
// misc
public children: HTMLElement[];
private refreshStart: number;
private refreshEnd: number;
public savedCols: number;
// stream
private readable: boolean;
private writable: boolean;
public defAttr: number;
public curAttr: number;
public params: (string | number)[];
public currentParam: string | number;
public prefix: string;
public postfix: string;
// user input states
public writeBuffer: string[];
private writeInProgress: boolean;
/**
* Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
* This is a distinct state from writeStopped so that if the user requested
* XOFF via ^S that it will not automatically resume when the writeBuffer goes
* below threshold.
*/
private xoffSentToCatchUp: boolean;
/** Whether writing has been stopped as a result of XOFF */
private writeStopped: boolean;
// leftover surrogate high from previous write invocation
private surrogate_high: string;
// Store if user went browsing history in scrollback
private userScrolling: boolean;
private inputHandler: InputHandler;
private parser: Parser;
private renderer: Renderer;
public selectionManager: SelectionManager;
private linkifier: Linkifier;
public buffers: BufferSet;
public buffer: Buffer;
public viewport: IViewport;
private compositionHelper: ICompositionHelper;
public charMeasure: CharMeasure;
public cols: number;
public rows: number;
public geometry: [/*cols*/number, /*rows*/number];
/**
* Creates a new `Terminal` object.
*
* @param {object} options An object containing a set of options, the available options are:
* - `cursorBlink` (boolean): Whether the terminal cursor blinks
* - `cols` (number): The number of columns of the terminal (horizontal size)
* - `rows` (number): The number of rows of the terminal (vertical size)
*
* @public
* @class Xterm Xterm
* @alias module:xterm/src/xterm
*/
constructor(
options: ITerminalOptions = {}
) {
super();
this.options = options;
this.setup();
}
private setup(): void {
Object.keys(DEFAULT_OPTIONS).forEach((key) => {
if (this.options[key] == null) {
this.options[key] = DEFAULT_OPTIONS[key];
}
// TODO: We should move away from duplicate options on the Terminal object
this[key] = this.options[key];
});
if (this.options.colors.length === 8) {
this.options.colors = this.options.colors.concat(_colors.slice(8));
} else if (this.options.colors.length === 16) {
this.options.colors = this.options.colors.concat(_colors.slice(16));
} else if (this.options.colors.length === 10) {
this.options.colors = this.options.colors.slice(0, -2).concat(
_colors.slice(8, -2), this.options.colors.slice(-2));
} else if (this.options.colors.length === 18) {
this.options.colors = this.options.colors.concat(
_colors.slice(16, -2), this.options.colors.slice(-2));
}
this.colors = this.options.colors;
// this.context = options.context || window;
// this.document = options.document || document;
// TODO: WHy not document.body?
this.parent = document ? document.body : null;
this.cols = this.options.cols || this.options.geometry[0];
this.rows = this.options.rows || this.options.geometry[1];
this.geometry = [this.cols, this.rows];
if (this.options.handler) {
this.on('data', this.options.handler);
}
this.cursorState = 0;
this.cursorHidden = false;
this.sendDataQueue = '';
this.customKeyEventHandler = null;
this.cursorBlinkInterval = null;
// modes
this.applicationKeypad = false;
this.applicationCursor = false;
this.originMode = false;
this.insertMode = false;
this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
// charset
this.charset = null;
this.gcharset = null;
this.glevel = 0;
// TODO: Can this be just []?
this.charsets = [null];
this.readable = true;
this.writable = true;
this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
this.curAttr = (0 << 18) | (257 << 9) | (256 << 0);
this.params = [];
this.currentParam = 0;
this.prefix = '';
this.postfix = '';
// user input states
this.writeBuffer = [];
this.writeInProgress = false;
this.xoffSentToCatchUp = false;
this.writeStopped = false;
this.surrogate_high = '';
this.userScrolling = false;
this.inputHandler = new InputHandler(this);
this.parser = new Parser(this.inputHandler, this);
// Reuse renderer if the Terminal is being recreated via a reset call.
this.renderer = this.renderer || null;
this.selectionManager = this.selectionManager || null;
this.linkifier = this.linkifier || new Linkifier();
// Create the terminal's buffers and set the current buffer
this.buffers = new BufferSet(this);
this.buffer = this.buffers.active; // Convenience shortcut;
this.buffers.on('activate', (buffer: Buffer) => {
this.buffer = buffer;
});
// Ensure the selection manager has the correct buffer
if (this.selectionManager) {
this.selectionManager.setBuffer(this.buffer);
}
this.setupStops();
}
/**
* back_color_erase feature for xterm.
*/
public eraseAttr(): number {
// if (this.is('screen')) return this.defAttr;
return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
}
/**
* Focus the terminal. Delegates focus handling to the terminal's DOM element.
*/
public focus(): void {
this.textarea.focus();
}
/**
* Retrieves an option's value from the terminal.
* @param {string} key The option key.
*/
public getOption(key: string): any {
if (!(key in DEFAULT_OPTIONS)) {
throw new Error('No option with key "' + key + '"');
}
if (typeof this.options[key] !== 'undefined') {
return this.options[key];
}
return this[key];
}
/**
* Sets an option on the terminal.
* @param {string} key The option key.
* @param {any} value The option value.
*/
public setOption(key: string, value: any): void {
if (!(key in DEFAULT_OPTIONS)) {
throw new Error('No option with key "' + key + '"');
}
switch (key) {
case 'bellStyle':
if (!value) {
value = 'none';
}
break;
case 'cursorStyle':
if (!value) {
value = 'block';
}
break;
case 'tabStopWidth':
if (value < 1) {
console.warn(`tabStopWidth cannot be less than 1, value: ${value}`);
return;
}
break;
case 'scrollback':
if (value < 0) {
console.warn(`scrollback cannot be less than 0, value: ${value}`);
return;
}
if (this.options[key] !== value) {
const newBufferLength = this.rows + value;
if (this.buffer.lines.length > newBufferLength) {
const amountToTrim = this.buffer.lines.length - newBufferLength;
const needsRefresh = (this.buffer.ydisp - amountToTrim < 0);
this.buffer.lines.trimStart(amountToTrim);
this.buffer.ybase = Math.max(this.buffer.ybase - amountToTrim, 0);
this.buffer.ydisp = Math.max(this.buffer.ydisp - amountToTrim, 0);
if (needsRefresh) {
this.refresh(0, this.rows - 1);
}
}
}
break;
}
this[key] = value;
this.options[key] = value;
switch (key) {
case 'cursorBlink': this.setCursorBlinking(value); break;
case 'cursorStyle':
this.element.classList.toggle(`xterm-cursor-style-block`, value === 'block');
this.element.classList.toggle(`xterm-cursor-style-underline`, value === 'underline');
this.element.classList.toggle(`xterm-cursor-style-bar`, value === 'bar');
break;
case 'scrollback':
this.buffers.resize(this.cols, this.rows);
this.viewport.syncScrollArea();
break;
case 'tabStopWidth': this.setupStops(); break;
case 'bellSound':
case 'bellStyle': this.syncBellSound(); break;
}
}
private restartCursorBlinking(): void {
this.setCursorBlinking(this.options.cursorBlink);
}
private setCursorBlinking(enabled: boolean): void {
this.element.classList.toggle('xterm-cursor-blink', enabled);
this.clearCursorBlinkingInterval();
if (enabled) {
this.cursorBlinkInterval = setInterval(() => {
this.element.classList.toggle('xterm-cursor-blink-on');
}, CURSOR_BLINK_INTERVAL);
}
}
private clearCursorBlinkingInterval(): void {
this.element.classList.remove('xterm-cursor-blink-on');
if (this.cursorBlinkInterval) {
clearInterval(this.cursorBlinkInterval);
this.cursorBlinkInterval = null;
}
}
/**
* Binds the desired focus behavior on a given terminal object.
*/
private bindFocus(): void {
globalOn(this.textarea, 'focus', (ev) => {
if (this.sendFocus) {
this.send(C0.ESC + '[I');
}
this.element.classList.add('focus');
this.showCursor();
this.restartCursorBlinking.apply(this);
// TODO: Why pass terminal here?
this.emit('focus');
});
};
/**
* Blur the terminal, calling the blur function on the terminal's underlying
* textarea.
*/
public blur(): void {
return this.textarea.blur();
}
/**
* Binds the desired blur behavior on a given terminal object.
*/
private bindBlur(): void {
on(this.textarea, 'blur', (ev) => {
this.refresh(this.buffer.y, this.buffer.y);
if (this.sendFocus) {
this.send(C0.ESC + '[O');
}
this.element.classList.remove('focus');
this.clearCursorBlinkingInterval.apply(this);
// TODO: Why pass terminal here?
this.emit('blur');
});
}
/**
* Initialize default behavior
*/
private initGlobal(): void {
this.bindKeys();
this.bindFocus();
this.bindBlur();
// Bind clipboard functionality
on(this.element, 'copy', (event: ClipboardEvent) => {
// If mouse events are active it means the selection manager is disabled and
// copy should be handled by the host program.
if (!this.hasSelection()) {
return;
}
copyHandler(event, this, this.selectionManager);
});
const pasteHandlerWrapper = event => pasteHandler(event, this);
on(this.textarea, 'paste', pasteHandlerWrapper);
on(this.element, 'paste', pasteHandlerWrapper);
// Handle right click context menus
if (Browser.isFirefox) {
// Firefox doesn't appear to fire the contextmenu event on right click
on(this.element, 'mousedown', (event: MouseEvent) => {
if (event.button === 2) {
rightClickHandler(event, this.textarea, this.selectionManager);
}
});
} else {
on(this.element, 'contextmenu', (event: MouseEvent) => {
rightClickHandler(event, this.textarea, this.selectionManager);
});
}
// Move the textarea under the cursor when middle clicking on Linux to ensure
// middle click to paste selection works. This only appears to work in Chrome
// at the time is writing.
if (Browser.isLinux) {
// Use auxclick event over mousedown the latter doesn't seem to work. Note
// that the regular click event doesn't fire for the middle mouse button.
on(this.element, 'auxclick', (event: MouseEvent) => {
if (event.button === 1) {
moveTextAreaUnderMouseCursor(event, this.textarea);
}
});
}
}
/**
* Apply key handling to the terminal
*/
private bindKeys(): void {
const self = this;
on(this.element, 'keydown', function (ev: KeyboardEvent): void {
if (document.activeElement !== this) {
return;
}
self._keyDown(ev);
}, true);
on(this.element, 'keypress', function (ev: KeyboardEvent): void {
if (document.activeElement !== this) {
return;
}
self._keyPress(ev);
}, true);
on(this.element, 'keyup', (ev: KeyboardEvent) => {
if (!wasMondifierKeyOnlyEvent(ev)) {
this.focus();
}
}, true);
on(this.textarea, 'keydown', (ev: KeyboardEvent) => {
this._keyDown(ev);
}, true);
on(this.textarea, 'keypress', (ev: KeyboardEvent) => {
this._keyPress(ev);
// Truncate the textarea's value, since it is not needed
this.textarea.value = '';
}, true);
on(this.textarea, 'compositionstart', () => this.compositionHelper.compositionstart());
on(this.textarea, 'compositionupdate', (e: CompositionEvent) => this.compositionHelper.compositionupdate(e));
on(this.textarea, 'compositionend', () => this.compositionHelper.compositionend());
this.on('refresh', () => this.compositionHelper.updateCompositionElements());
this.on('refresh', (data) => this.queueLinkification(data.start, data.end));
}
/**
* Insert the given row to the terminal or produce a new one
* if no row argument is passed. Return the inserted row.
* @param {HTMLElement} row (optional) The row to append to the terminal.
*/
private insertRow(row?: HTMLElement): HTMLElement {
if (typeof row !== 'object') {
row = document.createElement('div');
}
this.rowContainer.appendChild(row);
this.children.push(row);
return row;
};
/**
* Opens the terminal within an element.
*
* @param {HTMLElement} parent The element to create the terminal within.
*/
public open(parent: HTMLElement): void {
let i = 0;
let div;
this.parent = parent || this.parent;
if (!this.parent) {
throw new Error('Terminal requires a parent element.');
}
// Grab global elements
this.context = this.parent.ownerDocument.defaultView;
this.document = this.parent.ownerDocument;
this.body = <HTMLBodyElement>this.document.body;
// Create main element container
this.element = this.document.createElement('div');
this.element.classList.add('terminal');
this.element.classList.add('xterm');
this.element.classList.add(`xterm-cursor-style-${this.options.cursorStyle}`);
this.setCursorBlinking(this.options.cursorBlink);
this.element.setAttribute('tabindex', '0');
this.viewportElement = document.createElement('div');
this.viewportElement.classList.add('xterm-viewport');
this.element.appendChild(this.viewportElement);
this.viewportScrollArea = document.createElement('div');
this.viewportScrollArea.classList.add('xterm-scroll-area');
this.viewportElement.appendChild(this.viewportScrollArea);
// preload audio
this.syncBellSound();
// Create the selection container.
this.selectionContainer = document.createElement('div');
this.selectionContainer.classList.add('xterm-selection');
this.element.appendChild(this.selectionContainer);
// Create the container that will hold the lines of the terminal and then
// produce the lines the lines.
this.rowContainer = document.createElement('div');
this.rowContainer.classList.add('xterm-rows');
this.element.appendChild(this.rowContainer);
this.children = [];
this.linkifier.attachToDom(document, this.children);
// Create the container that will hold helpers like the textarea for
// capturing DOM Events. Then produce the helpers.
this.helperContainer = document.createElement('div');
this.helperContainer.classList.add('xterm-helpers');
// TODO: This should probably be inserted once it's filled to prevent an additional layout
this.element.appendChild(this.helperContainer);
this.textarea = document.createElement('textarea');
this.textarea.classList.add('xterm-helper-textarea');
this.textarea.setAttribute('autocorrect', 'off');
this.textarea.setAttribute('autocapitalize', 'off');
this.textarea.setAttribute('spellcheck', 'false');
this.textarea.tabIndex = 0;
this.textarea.addEventListener('focus', () => this.emit('focus'));
this.textarea.addEventListener('blur', () => this.emit('blur'));
this.helperContainer.appendChild(this.textarea);
this.compositionView = document.createElement('div');
this.compositionView.classList.add('composition-view');
this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
this.helperContainer.appendChild(this.compositionView);
this.charSizeStyleElement = document.createElement('style');
this.helperContainer.appendChild(this.charSizeStyleElement);
for (; i < this.rows; i++) {
this.insertRow();
}
this.parent.appendChild(this.element);
this.charMeasure = new CharMeasure(document, this.helperContainer);
this.charMeasure.on('charsizechanged', () => {
this.updateCharSizeStyles();
});
this.charMeasure.measure();
this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasure);
this.renderer = new Renderer(this);
this.selectionManager = new SelectionManager(this, this.buffer, this.rowContainer, this.charMeasure);
this.selectionManager.on('refresh', data => {
this.renderer.refreshSelection(data.start, data.end);
});
this.selectionManager.on('newselection', text => {
// If there's a new selection, put it into the textarea, focus and select it
// in order to register it as a selection on the OS. This event is fired
// only on Linux to enable middle click to paste selection.
this.textarea.value = text;
this.textarea.focus();
this.textarea.select();
});
this.on('scroll', () => this.selectionManager.refresh());
this.viewportElement.addEventListener('scroll', () => this.selectionManager.refresh());
// Setup loop that draws to screen
this.refresh(0, this.rows - 1);
// Initialize global actions that need to be taken on the document.
this.initGlobal();
// Listen for mouse events and translate
// them into terminal mouse protocols.
this.bindMouse();
}
/**
* Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
* @param {string} addon The name of the addon to load
* @static
*/
public static loadAddon(addon: string, callback?: Function): boolean | any {
// TODO: Improve return type and documentation
if (typeof exports === 'object' && typeof module === 'object') {
// CommonJS
return require('./addons/' + addon + '/' + addon);
} else if (typeof define === 'function') {
// RequireJS
return (<any>require)(['./addons/' + addon + '/' + addon], callback);
} else {
console.error('Cannot load a module without a CommonJS or RequireJS environment.');
return false;
}
}
/**
* Updates the helper CSS class with any changes necessary after the terminal's
* character width has been changed.
*/
public updateCharSizeStyles(): void {
this.charSizeStyleElement.textContent =
`.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
`.xterm-normal-char{width:${this.charMeasure.width}px;}` +
`.xterm-rows > div{height:${this.charMeasure.height}px;}`;
}
/**
* XTerm mouse events
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
* To better understand these
* the xterm code is very helpful:
* Relevant files:
* button.c, charproc.c, misc.c
* Relevant functions in xterm/button.c:
* BtnCode, EmitButtonCode, EditorButton, SendMousePosition
*/
public bindMouse(): void {
const el = this.element;
const self = this;
let pressed = 32;
// mouseup, mousedown, wheel
// left click: ^[[M 3<^[[M#3<
// wheel up: ^[[M`3>
function sendButton(ev: MouseEvent | WheelEvent): void {
let button;
let pos;
// get the xterm-style button
button = getButton(ev);
// get mouse coordinates
pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
if (!pos) return;
sendEvent(button, pos);
switch ((<any>ev).overrideType || ev.type) {
case 'mousedown':
pressed = button;
break;
case 'mouseup':
// keep it at the left
// button, just in case.
pressed = 32;
break;
case 'wheel':
// nothing. don't
// interfere with
// `pressed`.
break;
}
}
// motion example of a left click:
// ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
function sendMove(ev: MouseEvent): void {
let button = pressed;
let pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
if (!pos) return;
// buttons marked as motions
// are incremented by 32
button += 32;
sendEvent(button, pos);
}
// encode button and
// position to characters
function encode(data: number[], ch: number): void {
if (!self.utfMouse) {
if (ch === 255) {
data.push(0);
return;
}
if (ch > 127) ch = 127;
data.push(ch);
} else {
if (ch === 2047) {
data.push(0);
return;
}
if (ch < 127) {
data.push(ch);
} else {
if (ch > 2047) ch = 2047;
data.push(0xC0 | (ch >> 6));
data.push(0x80 | (ch & 0x3F));
}
}
}
// send a mouse event:
// regular/utf8: ^[[M Cb Cx Cy
// urxvt: ^[[ Cb ; Cx ; Cy M
// sgr: ^[[ Cb ; Cx ; Cy M/m
// vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
// locator: CSI P e ; P b ; P r ; P c ; P p & w
function sendEvent(button: number, pos: {x: number, y: number}): void {
// self.emit('mouse', {
// x: pos.x - 32,
// y: pos.x - 32,
// button: button
// });
if (self.vt300Mouse) {
// NOTE: Unstable.
// http://www.vt100.net/docs/vt3xx-gp/chapter15.html
button &= 3;
pos.x -= 32;
pos.y -= 32;
let data = C0.ESC + '[24';
if (button === 0) data += '1';
else if (button === 1) data += '3';
else if (button === 2) data += '5';
else if (button === 3) return;
else data += '0';
data += '~[' + pos.x + ',' + pos.y + ']\r';
self.send(data);
return;
}
if (self.decLocator) {
// NOTE: Unstable.
button &= 3;
pos.x -= 32;
pos.y -= 32;
if (button === 0) button = 2;
else if (button === 1) button = 4;
else if (button === 2) button = 6;
else if (button === 3) button = 3;
self.send(C0.ESC + '['
+ button
+ ';'
+ (button === 3 ? 4 : 0)
+ ';'
+ pos.y
+ ';'
+ pos.x
+ ';'
// Not sure what page is meant to be
+ (<any>pos).page || 0
+ '&w');
return;
}
if (self.urxvtMouse) {
pos.x -= 32;
pos.y -= 32;
pos.x++;
pos.y++;
self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
return;
}
if (self.sgrMouse) {
pos.x -= 32;
pos.y -= 32;
self.send(C0.ESC + '[<'
+ (((button & 3) === 3 ? button & ~3 : button) - 32)
+ ';'
+ pos.x
+ ';'
+ pos.y
+ ((button & 3) === 3 ? 'm' : 'M'));
return;
}
let data: number[] = [];
encode(data, button);
encode(data, pos.x);
encode(data, pos.y);
self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, data));
}
function getButton(ev: MouseEvent): number {
let button;
let shift;
let meta;
let ctrl;
let mod;
// two low bits:
// 0 = left
// 1 = middle
// 2 = right
// 3 = release
// wheel up/down:
// 1, and 2 - with 64 added
switch ((<any>ev).overrideType || ev.type) {
case 'mousedown':
button = ev.button != null
? +ev.button
: ev.which != null
? ev.which - 1