]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Add scroll functionality for mobile
[mirror_xterm.js.git] / src / xterm.js
1 /**
2 * xterm.js: xterm, in the browser
3 * Originally forked from (with the author's permission):
4 * Fabrice Bellard's javascript vt100 for jslinux:
5 * http://bellard.org/jslinux/
6 * Copyright (c) 2011 Fabrice Bellard
7 * The original design remains. The terminal itself
8 * has been extended to include xterm CSI codes, among
9 * other features.
10 * @license MIT
11 */
12
13 import { CompositionHelper } from './CompositionHelper';
14 import { EventEmitter } from './EventEmitter';
15 import { Viewport } from './Viewport';
16 import { rightClickHandler, moveTextAreaUnderMouseCursor, pasteHandler, copyHandler } from './handlers/Clipboard';
17 import { CircularList } from './utils/CircularList';
18 import { C0 } from './EscapeSequences';
19 import { InputHandler } from './InputHandler';
20 import { Parser } from './Parser';
21 import { Renderer } from './Renderer';
22 import { Linkifier } from './Linkifier';
23 import { SelectionManager } from './SelectionManager';
24 import { CharMeasure } from './utils/CharMeasure';
25 import * as Browser from './utils/Browser';
26 import * as Mouse from './utils/Mouse';
27 import { CHARSETS } from './Charsets';
28 import { getRawByteCoords } from './utils/Mouse';
29
30 /**
31 * Terminal Emulation References:
32 * http://vt100.net/
33 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
34 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
35 * http://invisible-island.net/vttest/
36 * http://www.inwap.com/pdp10/ansicode.txt
37 * http://linux.die.net/man/4/console_codes
38 * http://linux.die.net/man/7/urxvt
39 */
40
41 // Let it work inside Node.js for automated testing purposes.
42 var document = (typeof window != 'undefined') ? window.document : null;
43
44 /**
45 * The amount of write requests to queue before sending an XOFF signal to the
46 * pty process. This number must be small in order for ^C and similar sequences
47 * to be responsive.
48 */
49 var WRITE_BUFFER_PAUSE_THRESHOLD = 5;
50
51 /**
52 * The number of writes to perform in a single batch before allowing the
53 * renderer to catch up with a 0ms setTimeout.
54 */
55 var WRITE_BATCH_SIZE = 300;
56
57 /**
58 * The time between cursor blinks. This is driven by JS rather than a CSS
59 * animation due to a bug in Chromium that causes it to use excessive CPU time.
60 * See https://github.com/Microsoft/vscode/issues/22900
61 */
62 var CURSOR_BLINK_INTERVAL = 600;
63
64 /**
65 * Terminal
66 */
67
68 /**
69 * Creates a new `Terminal` object.
70 *
71 * @param {object} options An object containing a set of options, the available options are:
72 * - `cursorBlink` (boolean): Whether the terminal cursor blinks
73 * - `cols` (number): The number of columns of the terminal (horizontal size)
74 * - `rows` (number): The number of rows of the terminal (vertical size)
75 *
76 * @public
77 * @class Xterm Xterm
78 * @alias module:xterm/src/xterm
79 */
80 function Terminal(options) {
81 var self = this;
82
83 if (!(this instanceof Terminal)) {
84 return new Terminal(arguments[0], arguments[1], arguments[2]);
85 }
86
87 self.browser = Browser;
88 self.cancel = Terminal.cancel;
89
90 EventEmitter.call(this);
91
92 if (typeof options === 'number') {
93 options = {
94 cols: arguments[0],
95 rows: arguments[1],
96 handler: arguments[2]
97 };
98 }
99
100 options = options || {};
101
102
103 Object.keys(Terminal.defaults).forEach(function(key) {
104 if (options[key] == null) {
105 options[key] = Terminal.options[key];
106
107 if (Terminal[key] !== Terminal.defaults[key]) {
108 options[key] = Terminal[key];
109 }
110 }
111 self[key] = options[key];
112 });
113
114 if (options.colors.length === 8) {
115 options.colors = options.colors.concat(Terminal._colors.slice(8));
116 } else if (options.colors.length === 16) {
117 options.colors = options.colors.concat(Terminal._colors.slice(16));
118 } else if (options.colors.length === 10) {
119 options.colors = options.colors.slice(0, -2).concat(
120 Terminal._colors.slice(8, -2), options.colors.slice(-2));
121 } else if (options.colors.length === 18) {
122 options.colors = options.colors.concat(
123 Terminal._colors.slice(16, -2), options.colors.slice(-2));
124 }
125 this.colors = options.colors;
126
127 this.options = options;
128
129 // this.context = options.context || window;
130 // this.document = options.document || document;
131 this.parent = options.body || options.parent || (
132 document ? document.getElementsByTagName('body')[0] : null
133 );
134
135 this.cols = options.cols || options.geometry[0];
136 this.rows = options.rows || options.geometry[1];
137 this.geometry = [this.cols, this.rows];
138
139 if (options.handler) {
140 this.on('data', options.handler);
141 }
142
143 /**
144 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
145 * buffer
146 */
147 this.ybase = 0;
148
149 /**
150 * The scroll position of the viewport
151 */
152 this.ydisp = 0;
153
154 /**
155 * The cursor's x position after ybase
156 */
157 this.x = 0;
158
159 /**
160 * The cursor's y position after ybase
161 */
162 this.y = 0;
163
164 this.cursorState = 0;
165 this.cursorHidden = false;
166 this.convertEol;
167 this.queue = '';
168 this.scrollTop = 0;
169 this.scrollBottom = this.rows - 1;
170 this.customKeyEventHandler = null;
171 this.cursorBlinkInterval = null;
172
173 // modes
174 this.applicationKeypad = false;
175 this.applicationCursor = false;
176 this.originMode = false;
177 this.insertMode = false;
178 this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
179 this.normal = null;
180
181 // charset
182 this.charset = null;
183 this.gcharset = null;
184 this.glevel = 0;
185 this.charsets = [null];
186
187 // mouse properties
188 this.decLocator;
189 this.x10Mouse;
190 this.vt200Mouse;
191 this.vt300Mouse;
192 this.normalMouse;
193 this.mouseEvents;
194 this.sendFocus;
195 this.utfMouse;
196 this.sgrMouse;
197 this.urxvtMouse;
198
199 // misc
200 this.element;
201 this.children;
202 this.refreshStart;
203 this.refreshEnd;
204 this.savedX;
205 this.savedY;
206 this.savedCols;
207
208 // stream
209 this.readable = true;
210 this.writable = true;
211
212 this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
213 this.curAttr = this.defAttr;
214
215 this.params = [];
216 this.currentParam = 0;
217 this.prefix = '';
218 this.postfix = '';
219
220 this.inputHandler = new InputHandler(this);
221 this.parser = new Parser(this.inputHandler, this);
222 // Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
223 this.renderer = this.renderer || null;
224 this.selectionManager = this.selectionManager || null;
225 this.linkifier = this.linkifier || new Linkifier();
226
227 // user input states
228 this.writeBuffer = [];
229 this.writeInProgress = false;
230
231 /**
232 * Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
233 * This is a distinct state from writeStopped so that if the user requested
234 * XOFF via ^S that it will not automatically resume when the writeBuffer goes
235 * below threshold.
236 */
237 this.xoffSentToCatchUp = false;
238
239 /** Whether writing has been stopped as a result of XOFF */
240 this.writeStopped = false;
241
242 // leftover surrogate high from previous write invocation
243 this.surrogate_high = '';
244
245 /**
246 * An array of all lines in the entire buffer, including the prompt. The lines are array of
247 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
248 */
249 this.lines = new CircularList(this.scrollback);
250 var i = this.rows;
251 while (i--) {
252 this.lines.push(this.blankLine());
253 }
254 // Ensure the selection manager has the correct buffer
255 if (this.selectionManager) {
256 this.selectionManager.setBuffer(this.lines);
257 }
258
259 this.tabs;
260 this.setupStops();
261
262 // Store if user went browsing history in scrollback
263 this.userScrolling = false;
264 }
265
266 inherits(Terminal, EventEmitter);
267
268 /**
269 * back_color_erase feature for xterm.
270 */
271 Terminal.prototype.eraseAttr = function() {
272 // if (this.is('screen')) return this.defAttr;
273 return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
274 };
275
276 /**
277 * Colors
278 */
279
280 // Colors 0-15
281 Terminal.tangoColors = [
282 // dark:
283 '#2e3436',
284 '#cc0000',
285 '#4e9a06',
286 '#c4a000',
287 '#3465a4',
288 '#75507b',
289 '#06989a',
290 '#d3d7cf',
291 // bright:
292 '#555753',
293 '#ef2929',
294 '#8ae234',
295 '#fce94f',
296 '#729fcf',
297 '#ad7fa8',
298 '#34e2e2',
299 '#eeeeec'
300 ];
301
302 // Colors 0-15 + 16-255
303 // Much thanks to TooTallNate for writing this.
304 Terminal.colors = (function() {
305 var colors = Terminal.tangoColors.slice()
306 , r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
307 , i;
308
309 // 16-231
310 i = 0;
311 for (; i < 216; i++) {
312 out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
313 }
314
315 // 232-255 (grey)
316 i = 0;
317 for (; i < 24; i++) {
318 r = 8 + i * 10;
319 out(r, r, r);
320 }
321
322 function out(r, g, b) {
323 colors.push('#' + hex(r) + hex(g) + hex(b));
324 }
325
326 function hex(c) {
327 c = c.toString(16);
328 return c.length < 2 ? '0' + c : c;
329 }
330
331 return colors;
332 })();
333
334 Terminal._colors = Terminal.colors.slice();
335
336 Terminal.vcolors = (function() {
337 var out = []
338 , colors = Terminal.colors
339 , i = 0
340 , color;
341
342 for (; i < 256; i++) {
343 color = parseInt(colors[i].substring(1), 16);
344 out.push([
345 (color >> 16) & 0xff,
346 (color >> 8) & 0xff,
347 color & 0xff
348 ]);
349 }
350
351 return out;
352 })();
353
354 /**
355 * Options
356 */
357
358 Terminal.defaults = {
359 colors: Terminal.colors,
360 theme: 'default',
361 convertEol: false,
362 termName: 'xterm',
363 geometry: [80, 24],
364 cursorBlink: false,
365 cursorStyle: 'block',
366 visualBell: false,
367 popOnBell: false,
368 scrollback: 1000,
369 screenKeys: false,
370 debug: false,
371 cancelEvents: false,
372 disableStdin: false,
373 useFlowControl: false,
374 tabStopWidth: 8
375 // programFeatures: false,
376 // focusKeys: false,
377 };
378
379 Terminal.options = {};
380
381 Terminal.focus = null;
382
383 each(keys(Terminal.defaults), function(key) {
384 Terminal[key] = Terminal.defaults[key];
385 Terminal.options[key] = Terminal.defaults[key];
386 });
387
388 /**
389 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
390 */
391 Terminal.prototype.focus = function() {
392 return this.textarea.focus();
393 };
394
395 /**
396 * Retrieves an option's value from the terminal.
397 * @param {string} key The option key.
398 */
399 Terminal.prototype.getOption = function(key, value) {
400 if (!(key in Terminal.defaults)) {
401 throw new Error('No option with key "' + key + '"');
402 }
403
404 if (typeof this.options[key] !== 'undefined') {
405 return this.options[key];
406 }
407
408 return this[key];
409 };
410
411 /**
412 * Sets an option on the terminal.
413 * @param {string} key The option key.
414 * @param {string} value The option value.
415 */
416 Terminal.prototype.setOption = function(key, value) {
417 if (!(key in Terminal.defaults)) {
418 throw new Error('No option with key "' + key + '"');
419 }
420 switch (key) {
421 case 'scrollback':
422 if (value < this.rows) {
423 let msg = 'Setting the scrollback value less than the number of rows ';
424
425 msg += `(${this.rows}) is not allowed.`;
426
427 console.warn(msg);
428 return false;
429 }
430
431 if (this.options[key] !== value) {
432 if (this.lines.length > value) {
433 const amountToTrim = this.lines.length - value;
434 const needsRefresh = (this.ydisp - amountToTrim < 0);
435 this.lines.trimStart(amountToTrim);
436 this.ybase = Math.max(this.ybase - amountToTrim, 0);
437 this.ydisp = Math.max(this.ydisp - amountToTrim, 0);
438 if (needsRefresh) {
439 this.refresh(0, this.rows - 1);
440 }
441 }
442 this.lines.maxLength = value;
443 this.viewport.syncScrollArea();
444 }
445 break;
446 }
447 this[key] = value;
448 this.options[key] = value;
449 switch (key) {
450 case 'cursorBlink': this.setCursorBlinking(value); break;
451 case 'cursorStyle':
452 // Style 'block' applies with no class
453 this.element.classList.toggle(`xterm-cursor-style-underline`, value === 'underline');
454 this.element.classList.toggle(`xterm-cursor-style-bar`, value === 'bar');
455 break;
456 case 'tabStopWidth': this.setupStops(); break;
457 }
458 };
459
460 Terminal.prototype.restartCursorBlinking = function () {
461 this.setCursorBlinking(this.options.cursorBlink);
462 };
463
464 Terminal.prototype.setCursorBlinking = function (enabled) {
465 this.element.classList.toggle('xterm-cursor-blink', enabled);
466 this.clearCursorBlinkingInterval();
467 if (enabled) {
468 var self = this;
469 this.cursorBlinkInterval = setInterval(function () {
470 self.element.classList.toggle('xterm-cursor-blink-on');
471 }, CURSOR_BLINK_INTERVAL);
472 }
473 };
474
475 Terminal.prototype.clearCursorBlinkingInterval = function () {
476 this.element.classList.remove('xterm-cursor-blink-on');
477 if (this.cursorBlinkInterval) {
478 clearInterval(this.cursorBlinkInterval);
479 this.cursorBlinkInterval = null;
480 }
481 };
482
483 /**
484 * Binds the desired focus behavior on a given terminal object.
485 *
486 * @static
487 */
488 Terminal.bindFocus = function (term) {
489 on(term.textarea, 'focus', function (ev) {
490 if (term.sendFocus) {
491 term.send(C0.ESC + '[I');
492 }
493 term.element.classList.add('focus');
494 term.showCursor();
495 term.restartCursorBlinking.apply(term);
496 Terminal.focus = term;
497 term.emit('focus', {terminal: term});
498 });
499 };
500
501 /**
502 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
503 */
504 Terminal.prototype.blur = function() {
505 return this.textarea.blur();
506 };
507
508 /**
509 * Binds the desired blur behavior on a given terminal object.
510 *
511 * @static
512 */
513 Terminal.bindBlur = function (term) {
514 on(term.textarea, 'blur', function (ev) {
515 term.refresh(term.y, term.y);
516 if (term.sendFocus) {
517 term.send(C0.ESC + '[O');
518 }
519 term.element.classList.remove('focus');
520 term.clearCursorBlinkingInterval.apply(term);
521 Terminal.focus = null;
522 term.emit('blur', {terminal: term});
523 });
524 };
525
526 /**
527 * Initialize default behavior
528 */
529 Terminal.prototype.initGlobal = function() {
530 var term = this;
531
532 Terminal.bindKeys(this);
533 Terminal.bindFocus(this);
534 Terminal.bindBlur(this);
535
536 // Bind clipboard functionality
537 on(this.element, 'copy', event => {
538 // If mouse events are active it means the selection manager is disabled and
539 // copy should be handled by the host program.
540 if (this.mouseEvents) {
541 return;
542 }
543 copyHandler(event, term, this.selectionManager);
544 });
545 const pasteHandlerWrapper = event => pasteHandler(event, term);
546 on(this.textarea, 'paste', pasteHandlerWrapper);
547 on(this.element, 'paste', pasteHandlerWrapper);
548
549 // Handle right click context menus
550 if (term.browser.isFirefox) {
551 // Firefox doesn't appear to fire the contextmenu event on right click
552 on(this.element, 'mousedown', event => {
553 if (event.button == 2) {
554 rightClickHandler(event, this.textarea, this.selectionManager);
555 }
556 });
557 } else {
558 on(this.element, 'contextmenu', event => {
559 rightClickHandler(event, this.textarea, this.selectionManager);
560 });
561 }
562
563 // Move the textarea under the cursor when middle clicking on Linux to ensure
564 // middle click to paste selection works. This only appears to work in Chrome
565 // at the time is writing.
566 if (term.browser.isLinux) {
567 // Use auxclick event over mousedown the latter doesn't seem to work. Note
568 // that the regular click event doesn't fire for the middle mouse button.
569 on(this.element, 'auxclick', event => {
570 if (event.button === 1) {
571 moveTextAreaUnderMouseCursor(event, this.textarea, this.selectionManager);
572 }
573 });
574 }
575 };
576
577 /**
578 * Apply key handling to the terminal
579 */
580 Terminal.bindKeys = function(term) {
581 on(term.element, 'keydown', function(ev) {
582 if (document.activeElement != this) {
583 return;
584 }
585 term.keyDown(ev);
586 }, true);
587
588 on(term.element, 'keypress', function(ev) {
589 if (document.activeElement != this) {
590 return;
591 }
592 term.keyPress(ev);
593 }, true);
594
595 on(term.element, 'keyup', function(ev) {
596 if (!wasMondifierKeyOnlyEvent(ev)) {
597 term.focus(term);
598 }
599 }, true);
600
601 on(term.textarea, 'keydown', function(ev) {
602 term.keyDown(ev);
603 }, true);
604
605 on(term.textarea, 'keypress', function(ev) {
606 term.keyPress(ev);
607 // Truncate the textarea's value, since it is not needed
608 this.value = '';
609 }, true);
610
611 on(term.textarea, 'compositionstart', term.compositionHelper.compositionstart.bind(term.compositionHelper));
612 on(term.textarea, 'compositionupdate', term.compositionHelper.compositionupdate.bind(term.compositionHelper));
613 on(term.textarea, 'compositionend', term.compositionHelper.compositionend.bind(term.compositionHelper));
614 term.on('refresh', term.compositionHelper.updateCompositionElements.bind(term.compositionHelper));
615 term.on('refresh', function (data) {
616 term.queueLinkification(data.start, data.end)
617 });
618 };
619
620
621 /**
622 * Insert the given row to the terminal or produce a new one
623 * if no row argument is passed. Return the inserted row.
624 * @param {HTMLElement} row (optional) The row to append to the terminal.
625 */
626 Terminal.prototype.insertRow = function (row) {
627 if (typeof row != 'object') {
628 row = document.createElement('div');
629 }
630
631 this.rowContainer.appendChild(row);
632 this.children.push(row);
633
634 return row;
635 };
636
637 /**
638 * Opens the terminal within an element.
639 *
640 * @param {HTMLElement} parent The element to create the terminal within.
641 * @param {boolean} focus Focus the terminal, after it gets instantiated in the DOM
642 */
643 Terminal.prototype.open = function(parent, focus) {
644 var self=this, i=0, div;
645
646 this.parent = parent || this.parent;
647
648 if (!this.parent) {
649 throw new Error('Terminal requires a parent element.');
650 }
651
652 // Grab global elements
653 this.context = this.parent.ownerDocument.defaultView;
654 this.document = this.parent.ownerDocument;
655 this.body = this.document.getElementsByTagName('body')[0];
656
657 //Create main element container
658 this.element = this.document.createElement('div');
659 this.element.classList.add('terminal');
660 this.element.classList.add('xterm');
661 this.element.classList.add('xterm-theme-' + this.theme);
662 this.setCursorBlinking(this.options.cursorBlink);
663
664 this.element.setAttribute('tabindex', 0);
665
666 this.viewportElement = document.createElement('div');
667 this.viewportElement.classList.add('xterm-viewport');
668 this.element.appendChild(this.viewportElement);
669 this.viewportScrollArea = document.createElement('div');
670 this.viewportScrollArea.classList.add('xterm-scroll-area');
671 this.viewportElement.appendChild(this.viewportScrollArea);
672
673 // Create the selection container.
674 this.selectionContainer = document.createElement('div');
675 this.selectionContainer.classList.add('xterm-selection');
676 this.element.appendChild(this.selectionContainer);
677
678 // Create the container that will hold the lines of the terminal and then
679 // produce the lines the lines.
680 this.rowContainer = document.createElement('div');
681 this.rowContainer.classList.add('xterm-rows');
682 this.element.appendChild(this.rowContainer);
683 this.children = [];
684 this.linkifier.attachToDom(document, this.children);
685
686 // Create the container that will hold helpers like the textarea for
687 // capturing DOM Events. Then produce the helpers.
688 this.helperContainer = document.createElement('div');
689 this.helperContainer.classList.add('xterm-helpers');
690 // TODO: This should probably be inserted once it's filled to prevent an additional layout
691 this.element.appendChild(this.helperContainer);
692 this.textarea = document.createElement('textarea');
693 this.textarea.classList.add('xterm-helper-textarea');
694 this.textarea.setAttribute('autocorrect', 'off');
695 this.textarea.setAttribute('autocapitalize', 'off');
696 this.textarea.setAttribute('spellcheck', 'false');
697 this.textarea.tabIndex = 0;
698 this.textarea.addEventListener('focus', function() {
699 self.emit('focus', {terminal: self});
700 });
701 this.textarea.addEventListener('blur', function() {
702 self.emit('blur', {terminal: self});
703 });
704 this.helperContainer.appendChild(this.textarea);
705
706 this.compositionView = document.createElement('div');
707 this.compositionView.classList.add('composition-view');
708 this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
709 this.helperContainer.appendChild(this.compositionView);
710
711 this.charSizeStyleElement = document.createElement('style');
712 this.helperContainer.appendChild(this.charSizeStyleElement);
713
714 for (; i < this.rows; i++) {
715 this.insertRow();
716 }
717 this.parent.appendChild(this.element);
718
719 this.charMeasure = new CharMeasure(document, this.helperContainer);
720 this.charMeasure.on('charsizechanged', function () {
721 self.updateCharSizeStyles();
722 });
723 this.charMeasure.measure();
724
725 this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasure);
726 this.renderer = new Renderer(this);
727 this.selectionManager = new SelectionManager(this, this.lines, this.rowContainer, this.charMeasure);
728 this.selectionManager.on('refresh', data => {
729 this.renderer.refreshSelection(data.start, data.end);
730 });
731 this.selectionManager.on('newselection', text => {
732 // If there's a new selection, put it into the textarea, focus and select it
733 // in order to register it as a selection on the OS. This event is fired
734 // only on Linux to enable middle click to paste selection.
735 this.textarea.value = text;
736 this.textarea.focus();
737 this.textarea.select();
738 });
739 this.on('scroll', () => this.selectionManager.refresh());
740 this.viewportElement.addEventListener('scroll', () => this.selectionManager.refresh());
741
742 // Setup loop that draws to screen
743 this.refresh(0, this.rows - 1);
744
745 // Initialize global actions that
746 // need to be taken on the document.
747 this.initGlobal();
748
749 /**
750 * Automatic focus functionality.
751 * TODO: Default to `false` starting with xterm.js 3.0.
752 */
753 if (typeof focus == 'undefined') {
754 let message = 'You did not pass the `focus` argument in `Terminal.prototype.open()`.\n';
755
756 message += 'The `focus` argument now defaults to `true` but starting with xterm.js 3.0 ';
757 message += 'it will default to `false`.';
758
759 console.warn(message);
760 focus = true;
761 }
762
763 if (focus) {
764 this.focus();
765 }
766
767 on(this.element, 'click', function() {
768 var selection = document.getSelection(),
769 collapsed = selection.isCollapsed,
770 isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
771 if (!isRange) {
772 self.focus();
773 }
774 });
775
776 // Listen for mouse events and translate
777 // them into terminal mouse protocols.
778 this.bindMouse();
779
780 /**
781 * This event is emitted when terminal has completed opening.
782 *
783 * @event open
784 */
785 this.emit('open');
786 };
787
788
789 /**
790 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
791 * @param {string} addon The name of the addon to load
792 * @static
793 */
794 Terminal.loadAddon = function(addon, callback) {
795 if (typeof exports === 'object' && typeof module === 'object') {
796 // CommonJS
797 return require('./addons/' + addon + '/' + addon);
798 } else if (typeof define == 'function') {
799 // RequireJS
800 return require(['./addons/' + addon + '/' + addon], callback);
801 } else {
802 console.error('Cannot load a module without a CommonJS or RequireJS environment.');
803 return false;
804 }
805 };
806
807 /**
808 * Updates the helper CSS class with any changes necessary after the terminal's
809 * character width has been changed.
810 */
811 Terminal.prototype.updateCharSizeStyles = function() {
812 this.charSizeStyleElement.textContent =
813 `.xterm-wide-char{width:${this.charMeasure.width * 2}px;}` +
814 `.xterm-normal-char{width:${this.charMeasure.width}px;}` +
815 `.xterm-rows > div{height:${this.charMeasure.height}px;}`;
816 }
817
818 /**
819 * XTerm mouse events
820 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
821 * To better understand these
822 * the xterm code is very helpful:
823 * Relevant files:
824 * button.c, charproc.c, misc.c
825 * Relevant functions in xterm/button.c:
826 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
827 */
828 Terminal.prototype.bindMouse = function() {
829 var el = this.element, self = this, pressed = 32;
830
831 // mouseup, mousedown, wheel
832 // left click: ^[[M 3<^[[M#3<
833 // wheel up: ^[[M`3>
834 function sendButton(ev) {
835 var button
836 , pos;
837
838 // get the xterm-style button
839 button = getButton(ev);
840
841 // get mouse coordinates
842 pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
843 if (!pos) return;
844
845 sendEvent(button, pos);
846
847 switch (ev.overrideType || ev.type) {
848 case 'mousedown':
849 pressed = button;
850 break;
851 case 'mouseup':
852 // keep it at the left
853 // button, just in case.
854 pressed = 32;
855 break;
856 case 'wheel':
857 // nothing. don't
858 // interfere with
859 // `pressed`.
860 break;
861 }
862 }
863
864 // motion example of a left click:
865 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
866 function sendMove(ev) {
867 var button = pressed
868 , pos;
869
870 pos = getRawByteCoords(ev, self.rowContainer, self.charMeasure, self.cols, self.rows);
871 if (!pos) return;
872
873 // buttons marked as motions
874 // are incremented by 32
875 button += 32;
876
877 sendEvent(button, pos);
878 }
879
880 // encode button and
881 // position to characters
882 function encode(data, ch) {
883 if (!self.utfMouse) {
884 if (ch === 255) return data.push(0);
885 if (ch > 127) ch = 127;
886 data.push(ch);
887 } else {
888 if (ch === 2047) return data.push(0);
889 if (ch < 127) {
890 data.push(ch);
891 } else {
892 if (ch > 2047) ch = 2047;
893 data.push(0xC0 | (ch >> 6));
894 data.push(0x80 | (ch & 0x3F));
895 }
896 }
897 }
898
899 // send a mouse event:
900 // regular/utf8: ^[[M Cb Cx Cy
901 // urxvt: ^[[ Cb ; Cx ; Cy M
902 // sgr: ^[[ Cb ; Cx ; Cy M/m
903 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
904 // locator: CSI P e ; P b ; P r ; P c ; P p & w
905 function sendEvent(button, pos) {
906 // self.emit('mouse', {
907 // x: pos.x - 32,
908 // y: pos.x - 32,
909 // button: button
910 // });
911
912 if (self.vt300Mouse) {
913 // NOTE: Unstable.
914 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
915 button &= 3;
916 pos.x -= 32;
917 pos.y -= 32;
918 var data = C0.ESC + '[24';
919 if (button === 0) data += '1';
920 else if (button === 1) data += '3';
921 else if (button === 2) data += '5';
922 else if (button === 3) return;
923 else data += '0';
924 data += '~[' + pos.x + ',' + pos.y + ']\r';
925 self.send(data);
926 return;
927 }
928
929 if (self.decLocator) {
930 // NOTE: Unstable.
931 button &= 3;
932 pos.x -= 32;
933 pos.y -= 32;
934 if (button === 0) button = 2;
935 else if (button === 1) button = 4;
936 else if (button === 2) button = 6;
937 else if (button === 3) button = 3;
938 self.send(C0.ESC + '['
939 + button
940 + ';'
941 + (button === 3 ? 4 : 0)
942 + ';'
943 + pos.y
944 + ';'
945 + pos.x
946 + ';'
947 + (pos.page || 0)
948 + '&w');
949 return;
950 }
951
952 if (self.urxvtMouse) {
953 pos.x -= 32;
954 pos.y -= 32;
955 pos.x++;
956 pos.y++;
957 self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
958 return;
959 }
960
961 if (self.sgrMouse) {
962 pos.x -= 32;
963 pos.y -= 32;
964 self.send(C0.ESC + '[<'
965 + (((button & 3) === 3 ? button & ~3 : button) - 32)
966 + ';'
967 + pos.x
968 + ';'
969 + pos.y
970 + ((button & 3) === 3 ? 'm' : 'M'));
971 return;
972 }
973
974 var data = [];
975
976 encode(data, button);
977 encode(data, pos.x);
978 encode(data, pos.y);
979
980 self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, data));
981 }
982
983 function getButton(ev) {
984 var button
985 , shift
986 , meta
987 , ctrl
988 , mod;
989
990 // two low bits:
991 // 0 = left
992 // 1 = middle
993 // 2 = right
994 // 3 = release
995 // wheel up/down:
996 // 1, and 2 - with 64 added
997 switch (ev.overrideType || ev.type) {
998 case 'mousedown':
999 button = ev.button != null
1000 ? +ev.button
1001 : ev.which != null
1002 ? ev.which - 1
1003 : null;
1004
1005 if (self.browser.isMSIE) {
1006 button = button === 1 ? 0 : button === 4 ? 1 : button;
1007 }
1008 break;
1009 case 'mouseup':
1010 button = 3;
1011 break;
1012 case 'DOMMouseScroll':
1013 button = ev.detail < 0
1014 ? 64
1015 : 65;
1016 break;
1017 case 'wheel':
1018 button = ev.wheelDeltaY > 0
1019 ? 64
1020 : 65;
1021 break;
1022 }
1023
1024 // next three bits are the modifiers:
1025 // 4 = shift, 8 = meta, 16 = control
1026 shift = ev.shiftKey ? 4 : 0;
1027 meta = ev.metaKey ? 8 : 0;
1028 ctrl = ev.ctrlKey ? 16 : 0;
1029 mod = shift | meta | ctrl;
1030
1031 // no mods
1032 if (self.vt200Mouse) {
1033 // ctrl only
1034 mod &= ctrl;
1035 } else if (!self.normalMouse) {
1036 mod = 0;
1037 }
1038
1039 // increment to SP
1040 button = (32 + (mod << 2)) + button;
1041
1042 return button;
1043 }
1044
1045 on(el, 'mousedown', function(ev) {
1046 if (!self.mouseEvents) return;
1047
1048 // send the button
1049 sendButton(ev);
1050
1051 // ensure focus
1052 self.focus();
1053
1054 // fix for odd bug
1055 //if (self.vt200Mouse && !self.normalMouse) {
1056 if (self.vt200Mouse) {
1057 ev.overrideType = 'mouseup';
1058 sendButton(ev);
1059 return self.cancel(ev);
1060 }
1061
1062 // bind events
1063 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
1064
1065 // x10 compatibility mode can't send button releases
1066 if (!self.x10Mouse) {
1067 on(self.document, 'mouseup', function up(ev) {
1068 sendButton(ev);
1069 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
1070 off(self.document, 'mouseup', up);
1071 return self.cancel(ev);
1072 });
1073 }
1074
1075 return self.cancel(ev);
1076 });
1077
1078 //if (self.normalMouse) {
1079 // on(self.document, 'mousemove', sendMove);
1080 //}
1081
1082 on(el, 'wheel', function(ev) {
1083 if (!self.mouseEvents) return;
1084 if (self.x10Mouse
1085 || self.vt300Mouse
1086 || self.decLocator) return;
1087 sendButton(ev);
1088 return self.cancel(ev);
1089 });
1090
1091 // allow wheel scrolling in
1092 // the shell for example
1093 on(el, 'wheel', function(ev) {
1094 if (self.mouseEvents) return;
1095 self.viewport.onWheel(ev);
1096 return self.cancel(ev);
1097 });
1098
1099 on(el, 'touchstart', function(ev) {
1100 if (self.mouseEvents) return;
1101 self.viewport.onTouchStart(ev);
1102 return self.cancel(ev);
1103 });
1104
1105 on(el, 'touchmove', function(ev) {
1106 if (self.mouseEvents) return;
1107 self.viewport.onTouchMove(ev);
1108 return self.cancel(ev);
1109 });
1110 };
1111
1112 /**
1113 * Destroys the terminal.
1114 */
1115 Terminal.prototype.destroy = function() {
1116 this.readable = false;
1117 this.writable = false;
1118 this._events = {};
1119 this.handler = function() {};
1120 this.write = function() {};
1121 if (this.element && this.element.parentNode) {
1122 this.element.parentNode.removeChild(this.element);
1123 }
1124 //this.emit('close');
1125 };
1126
1127 /**
1128 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1129 * opportunity.
1130 * @param {number} start The row to start from (between 0 and this.rows - 1).
1131 * @param {number} end The row to end at (between start and this.rows - 1).
1132 */
1133 Terminal.prototype.refresh = function(start, end) {
1134 if (this.renderer) {
1135 this.renderer.queueRefresh(start, end);
1136 }
1137 };
1138
1139 /**
1140 * Queues linkification for the specified rows.
1141 * @param {number} start The row to start from (between 0 and this.rows - 1).
1142 * @param {number} end The row to end at (between start and this.rows - 1).
1143 */
1144 Terminal.prototype.queueLinkification = function(start, end) {
1145 if (this.linkifier) {
1146 for (let i = start; i <= end; i++) {
1147 this.linkifier.linkifyRow(i);
1148 }
1149 }
1150 };
1151
1152 /**
1153 * Display the cursor element
1154 */
1155 Terminal.prototype.showCursor = function() {
1156 if (!this.cursorState) {
1157 this.cursorState = 1;
1158 this.refresh(this.y, this.y);
1159 }
1160 };
1161
1162 /**
1163 * Scroll the terminal down 1 row, creating a blank line.
1164 * @param {boolean} isWrapped Whether the new line is wrapped from the previous
1165 * line.
1166 */
1167 Terminal.prototype.scroll = function(isWrapped) {
1168 var row;
1169
1170 // Make room for the new row in lines
1171 if (this.lines.length === this.lines.maxLength) {
1172 this.lines.trimStart(1);
1173 this.ybase--;
1174 if (this.ydisp !== 0) {
1175 this.ydisp--;
1176 }
1177 }
1178
1179 this.ybase++;
1180
1181 // TODO: Why is this done twice?
1182 if (!this.userScrolling) {
1183 this.ydisp = this.ybase;
1184 }
1185
1186 // last line
1187 row = this.ybase + this.rows - 1;
1188
1189 // subtract the bottom scroll region
1190 row -= this.rows - 1 - this.scrollBottom;
1191
1192 if (row === this.lines.length) {
1193 // Optimization: pushing is faster than splicing when they amount to the same behavior
1194 this.lines.push(this.blankLine(undefined, isWrapped));
1195 } else {
1196 // add our new line
1197 this.lines.splice(row, 0, this.blankLine(undefined, isWrapped));
1198 }
1199
1200 if (this.scrollTop !== 0) {
1201 if (this.ybase !== 0) {
1202 this.ybase--;
1203 if (!this.userScrolling) {
1204 this.ydisp = this.ybase;
1205 }
1206 }
1207 this.lines.splice(this.ybase + this.scrollTop, 1);
1208 }
1209
1210 // this.maxRange();
1211 this.updateRange(this.scrollTop);
1212 this.updateRange(this.scrollBottom);
1213
1214 /**
1215 * This event is emitted whenever the terminal is scrolled.
1216 * The one parameter passed is the new y display position.
1217 *
1218 * @event scroll
1219 */
1220 this.emit('scroll', this.ydisp);
1221 };
1222
1223 /**
1224 * Scroll the display of the terminal
1225 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1226 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1227 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1228 * viewport originally.
1229 */
1230 Terminal.prototype.scrollDisp = function(disp, suppressScrollEvent) {
1231 if (disp < 0) {
1232 if (this.ydisp === 0) {
1233 return;
1234 }
1235 this.userScrolling = true;
1236 } else if (disp + this.ydisp >= this.ybase) {
1237 this.userScrolling = false;
1238 }
1239
1240 this.ydisp += disp;
1241
1242 if (this.ydisp > this.ybase) {
1243 this.ydisp = this.ybase;
1244 } else if (this.ydisp < 0) {
1245 this.ydisp = 0;
1246 }
1247
1248 if (!suppressScrollEvent) {
1249 this.emit('scroll', this.ydisp);
1250 }
1251
1252 this.refresh(0, this.rows - 1);
1253 };
1254
1255 /**
1256 * Scroll the display of the terminal by a number of pages.
1257 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1258 */
1259 Terminal.prototype.scrollPages = function(pageCount) {
1260 this.scrollDisp(pageCount * (this.rows - 1));
1261 };
1262
1263 /**
1264 * Scrolls the display of the terminal to the top.
1265 */
1266 Terminal.prototype.scrollToTop = function() {
1267 this.scrollDisp(-this.ydisp);
1268 };
1269
1270 /**
1271 * Scrolls the display of the terminal to the bottom.
1272 */
1273 Terminal.prototype.scrollToBottom = function() {
1274 this.scrollDisp(this.ybase - this.ydisp);
1275 };
1276
1277 /**
1278 * Writes text to the terminal.
1279 * @param {string} data The text to write to the terminal.
1280 */
1281 Terminal.prototype.write = function(data) {
1282 this.writeBuffer.push(data);
1283
1284 // Send XOFF to pause the pty process if the write buffer becomes too large so
1285 // xterm.js can catch up before more data is sent. This is necessary in order
1286 // to keep signals such as ^C responsive.
1287 if (this.options.useFlowControl && !this.xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
1288 // XOFF - stop pty pipe
1289 // XON will be triggered by emulator before processing data chunk
1290 this.send(C0.DC3);
1291 this.xoffSentToCatchUp = true;
1292 }
1293
1294 if (!this.writeInProgress && this.writeBuffer.length > 0) {
1295 // Kick off a write which will write all data in sequence recursively
1296 this.writeInProgress = true;
1297 // Kick off an async innerWrite so more writes can come in while processing data
1298 var self = this;
1299 setTimeout(function () {
1300 self.innerWrite();
1301 });
1302 }
1303 };
1304
1305 Terminal.prototype.innerWrite = function() {
1306 var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
1307 while (writeBatch.length > 0) {
1308 var data = writeBatch.shift();
1309 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
1310
1311 // If XOFF was sent in order to catch up with the pty process, resume it if
1312 // the writeBuffer is empty to allow more data to come in.
1313 if (this.xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
1314 this.send(C0.DC1);
1315 this.xoffSentToCatchUp = false;
1316 }
1317
1318 this.refreshStart = this.y;
1319 this.refreshEnd = this.y;
1320
1321 // HACK: Set the parser state based on it's state at the time of return.
1322 // This works around the bug #662 which saw the parser state reset in the
1323 // middle of parsing escape sequence in two chunks. For some reason the
1324 // state of the parser resets to 0 after exiting parser.parse. This change
1325 // just sets the state back based on the correct return statement.
1326 var state = this.parser.parse(data);
1327 this.parser.setState(state);
1328
1329 this.updateRange(this.y);
1330 this.refresh(this.refreshStart, this.refreshEnd);
1331 }
1332 if (this.writeBuffer.length > 0) {
1333 // Allow renderer to catch up before processing the next batch
1334 var self = this;
1335 setTimeout(function () {
1336 self.innerWrite();
1337 }, 0);
1338 } else {
1339 this.writeInProgress = false;
1340 }
1341 };
1342
1343 /**
1344 * Writes text to the terminal, followed by a break line character (\n).
1345 * @param {string} data The text to write to the terminal.
1346 */
1347 Terminal.prototype.writeln = function(data) {
1348 this.write(data + '\r\n');
1349 };
1350
1351 /**
1352 * DEPRECATED: only for backward compatibility. Please use attachCustomKeyEventHandler() instead.
1353 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1354 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1355 * the default action. The function returns whether the event should be processed by xterm.js.
1356 */
1357 Terminal.prototype.attachCustomKeydownHandler = function(customKeydownHandler) {
1358 let message = 'attachCustomKeydownHandler() is DEPRECATED and will be removed soon. Please use attachCustomKeyEventHandler() instead.';
1359 console.warn(message);
1360 this.attachCustomKeyEventHandler(customKeydownHandler);
1361 };
1362
1363 /**
1364 * Attaches a custom key event handler which is run before keys are processed, giving consumers of
1365 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1366 * should not.
1367 * @param {function} customKeyEventHandler The custom KeyboardEvent handler to attach. This is a
1368 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1369 * the default action. The function returns whether the event should be processed by xterm.js.
1370 */
1371 Terminal.prototype.attachCustomKeyEventHandler = function(customKeyEventHandler) {
1372 this.customKeyEventHandler = customKeyEventHandler;
1373 };
1374
1375 /**
1376 * Attaches a http(s) link handler, forcing web links to behave differently to
1377 * regular <a> tags. This will trigger a refresh as links potentially need to be
1378 * reconstructed. Calling this with null will remove the handler.
1379 * @param {LinkMatcherHandler} handler The handler callback function.
1380 */
1381 Terminal.prototype.setHypertextLinkHandler = function(handler) {
1382 if (!this.linkifier) {
1383 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1384 }
1385 this.linkifier.setHypertextLinkHandler(handler);
1386 // Refresh to force links to refresh
1387 this.refresh(0, this.rows - 1);
1388 };
1389
1390 /**
1391 * Attaches a validation callback for hypertext links. This is useful to use
1392 * validation logic or to do something with the link's element and url.
1393 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1394 * be cleared with null.
1395 */
1396 Terminal.prototype.setHypertextValidationCallback = function(callback) {
1397 if (!this.linkifier) {
1398 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1399 }
1400 this.linkifier.setHypertextValidationCallback(callback);
1401 // Refresh to force links to refresh
1402 this.refresh(0, this.rows - 1);
1403 };
1404
1405 /**
1406 * Registers a link matcher, allowing custom link patterns to be matched and
1407 * handled.
1408 * @param {RegExp} regex The regular expression to search for, specifically
1409 * this searches the textContent of the rows. You will want to use \s to match
1410 * a space ' ' character for example.
1411 * @param {LinkMatcherHandler} handler The callback when the link is called.
1412 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1413 * @return {number} The ID of the new matcher, this can be used to deregister.
1414 */
1415 Terminal.prototype.registerLinkMatcher = function(regex, handler, options) {
1416 if (this.linkifier) {
1417 var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
1418 this.refresh(0, this.rows - 1);
1419 return matcherId;
1420 }
1421 };
1422
1423 /**
1424 * Deregisters a link matcher if it has been registered.
1425 * @param {number} matcherId The link matcher's ID (returned after register)
1426 */
1427 Terminal.prototype.deregisterLinkMatcher = function(matcherId) {
1428 if (this.linkifier) {
1429 if (this.linkifier.deregisterLinkMatcher(matcherId)) {
1430 this.refresh(0, this.rows - 1);
1431 }
1432 }
1433 };
1434
1435 /**
1436 * Gets whether the terminal has an active selection.
1437 */
1438 Terminal.prototype.hasSelection = function() {
1439 return this.selectionManager.hasSelection;
1440 };
1441
1442 /**
1443 * Gets the terminal's current selection, this is useful for implementing copy
1444 * behavior outside of xterm.js.
1445 */
1446 Terminal.prototype.getSelection = function() {
1447 return this.selectionManager.selectionText;
1448 };
1449
1450 /**
1451 * Clears the current terminal selection.
1452 */
1453 Terminal.prototype.clearSelection = function() {
1454 this.selectionManager.clearSelection();
1455 };
1456
1457 /**
1458 * Selects all text within the terminal.
1459 */
1460 Terminal.prototype.selectAll = function() {
1461 this.selectionManager.selectAll();
1462 };
1463
1464 /**
1465 * Handle a keydown event
1466 * Key Resources:
1467 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1468 * @param {KeyboardEvent} ev The keydown event to be handled.
1469 */
1470 Terminal.prototype.keyDown = function(ev) {
1471 if (this.customKeyEventHandler && this.customKeyEventHandler(ev) === false) {
1472 return false;
1473 }
1474
1475 this.restartCursorBlinking();
1476
1477 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
1478 if (this.ybase !== this.ydisp) {
1479 this.scrollToBottom();
1480 }
1481 return false;
1482 }
1483
1484 var self = this;
1485 var result = this.evaluateKeyEscapeSequence(ev);
1486
1487 if (result.key === C0.DC3) { // XOFF
1488 this.writeStopped = true;
1489 } else if (result.key === C0.DC1) { // XON
1490 this.writeStopped = false;
1491 }
1492
1493 if (result.scrollDisp) {
1494 this.scrollDisp(result.scrollDisp);
1495 return this.cancel(ev, true);
1496 }
1497
1498 if (isThirdLevelShift(this, ev)) {
1499 return true;
1500 }
1501
1502 if (result.cancel) {
1503 // The event is canceled at the end already, is this necessary?
1504 this.cancel(ev, true);
1505 }
1506
1507 if (!result.key) {
1508 return true;
1509 }
1510
1511 this.emit('keydown', ev);
1512 this.emit('key', result.key, ev);
1513 this.showCursor();
1514 this.handler(result.key);
1515
1516 return this.cancel(ev, true);
1517 };
1518
1519 /**
1520 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1521 * returned value is the new key code to pass to the PTY.
1522 *
1523 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1524 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1525 */
1526 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
1527 var result = {
1528 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1529 // canceled at the end of keyDown
1530 cancel: false,
1531 // The new key even to emit
1532 key: undefined,
1533 // The number of characters to scroll, if this is defined it will cancel the event
1534 scrollDisp: undefined
1535 };
1536 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
1537 switch (ev.keyCode) {
1538 case 8:
1539 // backspace
1540 if (ev.shiftKey) {
1541 result.key = C0.BS; // ^H
1542 break;
1543 }
1544 result.key = C0.DEL; // ^?
1545 break;
1546 case 9:
1547 // tab
1548 if (ev.shiftKey) {
1549 result.key = C0.ESC + '[Z';
1550 break;
1551 }
1552 result.key = C0.HT;
1553 result.cancel = true;
1554 break;
1555 case 13:
1556 // return/enter
1557 result.key = C0.CR;
1558 result.cancel = true;
1559 break;
1560 case 27:
1561 // escape
1562 result.key = C0.ESC;
1563 result.cancel = true;
1564 break;
1565 case 37:
1566 // left-arrow
1567 if (modifiers) {
1568 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
1569 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1570 // http://unix.stackexchange.com/a/108106
1571 // macOS uses different escape sequences than linux
1572 if (result.key == C0.ESC + '[1;3D') {
1573 result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
1574 }
1575 } else if (this.applicationCursor) {
1576 result.key = C0.ESC + 'OD';
1577 } else {
1578 result.key = C0.ESC + '[D';
1579 }
1580 break;
1581 case 39:
1582 // right-arrow
1583 if (modifiers) {
1584 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
1585 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1586 // http://unix.stackexchange.com/a/108106
1587 // macOS uses different escape sequences than linux
1588 if (result.key == C0.ESC + '[1;3C') {
1589 result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
1590 }
1591 } else if (this.applicationCursor) {
1592 result.key = C0.ESC + 'OC';
1593 } else {
1594 result.key = C0.ESC + '[C';
1595 }
1596 break;
1597 case 38:
1598 // up-arrow
1599 if (modifiers) {
1600 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
1601 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1602 // http://unix.stackexchange.com/a/108106
1603 if (result.key == C0.ESC + '[1;3A') {
1604 result.key = C0.ESC + '[1;5A';
1605 }
1606 } else if (this.applicationCursor) {
1607 result.key = C0.ESC + 'OA';
1608 } else {
1609 result.key = C0.ESC + '[A';
1610 }
1611 break;
1612 case 40:
1613 // down-arrow
1614 if (modifiers) {
1615 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
1616 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1617 // http://unix.stackexchange.com/a/108106
1618 if (result.key == C0.ESC + '[1;3B') {
1619 result.key = C0.ESC + '[1;5B';
1620 }
1621 } else if (this.applicationCursor) {
1622 result.key = C0.ESC + 'OB';
1623 } else {
1624 result.key = C0.ESC + '[B';
1625 }
1626 break;
1627 case 45:
1628 // insert
1629 if (!ev.shiftKey && !ev.ctrlKey) {
1630 // <Ctrl> or <Shift> + <Insert> are used to
1631 // copy-paste on some systems.
1632 result.key = C0.ESC + '[2~';
1633 }
1634 break;
1635 case 46:
1636 // delete
1637 if (modifiers) {
1638 result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
1639 } else {
1640 result.key = C0.ESC + '[3~';
1641 }
1642 break;
1643 case 36:
1644 // home
1645 if (modifiers)
1646 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
1647 else if (this.applicationCursor)
1648 result.key = C0.ESC + 'OH';
1649 else
1650 result.key = C0.ESC + '[H';
1651 break;
1652 case 35:
1653 // end
1654 if (modifiers)
1655 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
1656 else if (this.applicationCursor)
1657 result.key = C0.ESC + 'OF';
1658 else
1659 result.key = C0.ESC + '[F';
1660 break;
1661 case 33:
1662 // page up
1663 if (ev.shiftKey) {
1664 result.scrollDisp = -(this.rows - 1);
1665 } else {
1666 result.key = C0.ESC + '[5~';
1667 }
1668 break;
1669 case 34:
1670 // page down
1671 if (ev.shiftKey) {
1672 result.scrollDisp = this.rows - 1;
1673 } else {
1674 result.key = C0.ESC + '[6~';
1675 }
1676 break;
1677 case 112:
1678 // F1-F12
1679 if (modifiers) {
1680 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
1681 } else {
1682 result.key = C0.ESC + 'OP';
1683 }
1684 break;
1685 case 113:
1686 if (modifiers) {
1687 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
1688 } else {
1689 result.key = C0.ESC + 'OQ';
1690 }
1691 break;
1692 case 114:
1693 if (modifiers) {
1694 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
1695 } else {
1696 result.key = C0.ESC + 'OR';
1697 }
1698 break;
1699 case 115:
1700 if (modifiers) {
1701 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
1702 } else {
1703 result.key = C0.ESC + 'OS';
1704 }
1705 break;
1706 case 116:
1707 if (modifiers) {
1708 result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
1709 } else {
1710 result.key = C0.ESC + '[15~';
1711 }
1712 break;
1713 case 117:
1714 if (modifiers) {
1715 result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
1716 } else {
1717 result.key = C0.ESC + '[17~';
1718 }
1719 break;
1720 case 118:
1721 if (modifiers) {
1722 result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
1723 } else {
1724 result.key = C0.ESC + '[18~';
1725 }
1726 break;
1727 case 119:
1728 if (modifiers) {
1729 result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
1730 } else {
1731 result.key = C0.ESC + '[19~';
1732 }
1733 break;
1734 case 120:
1735 if (modifiers) {
1736 result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
1737 } else {
1738 result.key = C0.ESC + '[20~';
1739 }
1740 break;
1741 case 121:
1742 if (modifiers) {
1743 result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
1744 } else {
1745 result.key = C0.ESC + '[21~';
1746 }
1747 break;
1748 case 122:
1749 if (modifiers) {
1750 result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
1751 } else {
1752 result.key = C0.ESC + '[23~';
1753 }
1754 break;
1755 case 123:
1756 if (modifiers) {
1757 result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
1758 } else {
1759 result.key = C0.ESC + '[24~';
1760 }
1761 break;
1762 default:
1763 // a-z and space
1764 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
1765 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1766 result.key = String.fromCharCode(ev.keyCode - 64);
1767 } else if (ev.keyCode === 32) {
1768 // NUL
1769 result.key = String.fromCharCode(0);
1770 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
1771 // escape, file sep, group sep, record sep, unit sep
1772 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
1773 } else if (ev.keyCode === 56) {
1774 // delete
1775 result.key = String.fromCharCode(127);
1776 } else if (ev.keyCode === 219) {
1777 // ^[ - Control Sequence Introducer (CSI)
1778 result.key = String.fromCharCode(27);
1779 } else if (ev.keyCode === 220) {
1780 // ^\ - String Terminator (ST)
1781 result.key = String.fromCharCode(28);
1782 } else if (ev.keyCode === 221) {
1783 // ^] - Operating System Command (OSC)
1784 result.key = String.fromCharCode(29);
1785 }
1786 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
1787 // On Mac this is a third level shift. Use <Esc> instead.
1788 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1789 result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
1790 } else if (ev.keyCode === 192) {
1791 result.key = C0.ESC + '`';
1792 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
1793 result.key = C0.ESC + (ev.keyCode - 48);
1794 }
1795 } else if (this.browser.isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {
1796 if (ev.keyCode === 65) { // cmd + a
1797 this.selectAll();
1798 }
1799 }
1800 break;
1801 }
1802
1803 return result;
1804 };
1805
1806 /**
1807 * Set the G level of the terminal
1808 * @param g
1809 */
1810 Terminal.prototype.setgLevel = function(g) {
1811 this.glevel = g;
1812 this.charset = this.charsets[g];
1813 };
1814
1815 /**
1816 * Set the charset for the given G level of the terminal
1817 * @param g
1818 * @param charset
1819 */
1820 Terminal.prototype.setgCharset = function(g, charset) {
1821 this.charsets[g] = charset;
1822 if (this.glevel === g) {
1823 this.charset = charset;
1824 }
1825 };
1826
1827 /**
1828 * Handle a keypress event.
1829 * Key Resources:
1830 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1831 * @param {KeyboardEvent} ev The keypress event to be handled.
1832 */
1833 Terminal.prototype.keyPress = function(ev) {
1834 var key;
1835
1836 if (this.customKeyEventHandler && this.customKeyEventHandler(ev) === false) {
1837 return false;
1838 }
1839
1840 this.cancel(ev);
1841
1842 if (ev.charCode) {
1843 key = ev.charCode;
1844 } else if (ev.which == null) {
1845 key = ev.keyCode;
1846 } else if (ev.which !== 0 && ev.charCode !== 0) {
1847 key = ev.which;
1848 } else {
1849 return false;
1850 }
1851
1852 if (!key || (
1853 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
1854 )) {
1855 return false;
1856 }
1857
1858 key = String.fromCharCode(key);
1859
1860 this.emit('keypress', key, ev);
1861 this.emit('key', key, ev);
1862 this.showCursor();
1863 this.handler(key);
1864
1865 return true;
1866 };
1867
1868 /**
1869 * Send data for handling to the terminal
1870 * @param {string} data
1871 */
1872 Terminal.prototype.send = function(data) {
1873 var self = this;
1874
1875 if (!this.queue) {
1876 setTimeout(function() {
1877 self.handler(self.queue);
1878 self.queue = '';
1879 }, 1);
1880 }
1881
1882 this.queue += data;
1883 };
1884
1885 /**
1886 * Ring the bell.
1887 * Note: We could do sweet things with webaudio here
1888 */
1889 Terminal.prototype.bell = function() {
1890 if (!this.visualBell) return;
1891 var self = this;
1892 this.element.style.borderColor = 'white';
1893 setTimeout(function() {
1894 self.element.style.borderColor = '';
1895 }, 10);
1896 if (this.popOnBell) this.focus();
1897 };
1898
1899 /**
1900 * Log the current state to the console.
1901 */
1902 Terminal.prototype.log = function() {
1903 if (!this.debug) return;
1904 if (!this.context.console || !this.context.console.log) return;
1905 var args = Array.prototype.slice.call(arguments);
1906 this.context.console.log.apply(this.context.console, args);
1907 };
1908
1909 /**
1910 * Log the current state as error to the console.
1911 */
1912 Terminal.prototype.error = function() {
1913 if (!this.debug) return;
1914 if (!this.context.console || !this.context.console.error) return;
1915 var args = Array.prototype.slice.call(arguments);
1916 this.context.console.error.apply(this.context.console, args);
1917 };
1918
1919 /**
1920 * Resizes the terminal.
1921 *
1922 * @param {number} x The number of columns to resize to.
1923 * @param {number} y The number of rows to resize to.
1924 */
1925 Terminal.prototype.resize = function(x, y) {
1926 if (isNaN(x) || isNaN(y)) {
1927 return;
1928 }
1929
1930 if (y > this.getOption('scrollback')) {
1931 this.setOption('scrollback', y)
1932 }
1933
1934 var line
1935 , el
1936 , i
1937 , j
1938 , ch
1939 , addToY;
1940
1941 if (x === this.cols && y === this.rows) {
1942 return;
1943 }
1944
1945 if (x < 1) x = 1;
1946 if (y < 1) y = 1;
1947
1948 // resize cols
1949 j = this.cols;
1950 if (j < x) {
1951 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
1952 i = this.lines.length;
1953 while (i--) {
1954 while (this.lines.get(i).length < x) {
1955 this.lines.get(i).push(ch);
1956 }
1957 }
1958 }
1959
1960 this.cols = x;
1961 this.setupStops(this.cols);
1962
1963 // resize rows
1964 j = this.rows;
1965 addToY = 0;
1966 if (j < y) {
1967 el = this.element;
1968 while (j++ < y) {
1969 // y is rows, not this.y
1970 if (this.lines.length < y + this.ybase) {
1971 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
1972 // There is room above the buffer and there are no empty elements below the line,
1973 // scroll up
1974 this.ybase--;
1975 addToY++;
1976 if (this.ydisp > 0) {
1977 // Viewport is at the top of the buffer, must increase downwards
1978 this.ydisp--;
1979 }
1980 } else {
1981 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1982 // are blank lines after the cursor
1983 this.lines.push(this.blankLine());
1984 }
1985 }
1986 if (this.children.length < y) {
1987 this.insertRow();
1988 }
1989 }
1990 } else { // (j > y)
1991 while (j-- > y) {
1992 if (this.lines.length > y + this.ybase) {
1993 if (this.lines.length > this.ybase + this.y + 1) {
1994 // The line is a blank line below the cursor, remove it
1995 this.lines.pop();
1996 } else {
1997 // The line is the cursor, scroll down
1998 this.ybase++;
1999 this.ydisp++;
2000 }
2001 }
2002 if (this.children.length > y) {
2003 el = this.children.shift();
2004 if (!el) continue;
2005 el.parentNode.removeChild(el);
2006 }
2007 }
2008 }
2009 this.rows = y;
2010
2011 // Make sure that the cursor stays on screen
2012 if (this.y >= y) {
2013 this.y = y - 1;
2014 }
2015 if (addToY) {
2016 this.y += addToY;
2017 }
2018
2019 if (this.x >= x) {
2020 this.x = x - 1;
2021 }
2022
2023 this.scrollTop = 0;
2024 this.scrollBottom = y - 1;
2025
2026 this.charMeasure.measure();
2027
2028 this.refresh(0, this.rows - 1);
2029
2030 this.normal = null;
2031
2032 this.geometry = [this.cols, this.rows];
2033 this.emit('resize', {terminal: this, cols: x, rows: y});
2034 };
2035
2036 /**
2037 * Updates the range of rows to refresh
2038 * @param {number} y The number of rows to refresh next.
2039 */
2040 Terminal.prototype.updateRange = function(y) {
2041 if (y < this.refreshStart) this.refreshStart = y;
2042 if (y > this.refreshEnd) this.refreshEnd = y;
2043 // if (y > this.refreshEnd) {
2044 // this.refreshEnd = y;
2045 // if (y > this.rows - 1) {
2046 // this.refreshEnd = this.rows - 1;
2047 // }
2048 // }
2049 };
2050
2051 /**
2052 * Set the range of refreshing to the maximum value
2053 */
2054 Terminal.prototype.maxRange = function() {
2055 this.refreshStart = 0;
2056 this.refreshEnd = this.rows - 1;
2057 };
2058
2059
2060
2061 /**
2062 * Setup the tab stops.
2063 * @param {number} i
2064 */
2065 Terminal.prototype.setupStops = function(i) {
2066 if (i != null) {
2067 if (!this.tabs[i]) {
2068 i = this.prevStop(i);
2069 }
2070 } else {
2071 this.tabs = {};
2072 i = 0;
2073 }
2074
2075 for (; i < this.cols; i += this.getOption('tabStopWidth')) {
2076 this.tabs[i] = true;
2077 }
2078 };
2079
2080
2081 /**
2082 * Move the cursor to the previous tab stop from the given position (default is current).
2083 * @param {number} x The position to move the cursor to the previous tab stop.
2084 */
2085 Terminal.prototype.prevStop = function(x) {
2086 if (x == null) x = this.x;
2087 while (!this.tabs[--x] && x > 0);
2088 return x >= this.cols
2089 ? this.cols - 1
2090 : x < 0 ? 0 : x;
2091 };
2092
2093
2094 /**
2095 * Move the cursor one tab stop forward from the given position (default is current).
2096 * @param {number} x The position to move the cursor one tab stop forward.
2097 */
2098 Terminal.prototype.nextStop = function(x) {
2099 if (x == null) x = this.x;
2100 while (!this.tabs[++x] && x < this.cols);
2101 return x >= this.cols
2102 ? this.cols - 1
2103 : x < 0 ? 0 : x;
2104 };
2105
2106
2107 /**
2108 * Erase in the identified line everything from "x" to the end of the line (right).
2109 * @param {number} x The column from which to start erasing to the end of the line.
2110 * @param {number} y The line in which to operate.
2111 */
2112 Terminal.prototype.eraseRight = function(x, y) {
2113 var line = this.lines.get(this.ybase + y);
2114 if (!line) {
2115 return;
2116 }
2117 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2118 for (; x < this.cols; x++) {
2119 line[x] = ch;
2120 }
2121 this.updateRange(y);
2122 };
2123
2124
2125
2126 /**
2127 * Erase in the identified line everything from "x" to the start of the line (left).
2128 * @param {number} x The column from which to start erasing to the start of the line.
2129 * @param {number} y The line in which to operate.
2130 */
2131 Terminal.prototype.eraseLeft = function(x, y) {
2132 var line = this.lines.get(this.ybase + y);
2133 if (!line) {
2134 return;
2135 }
2136 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2137 x++;
2138 while (x--) {
2139 line[x] = ch;
2140 }
2141 this.updateRange(y);
2142 };
2143
2144 /**
2145 * Clears the entire buffer, making the prompt line the new first line.
2146 */
2147 Terminal.prototype.clear = function() {
2148 if (this.ybase === 0 && this.y === 0) {
2149 // Don't clear if it's already clear
2150 return;
2151 }
2152 this.lines.set(0, this.lines.get(this.ybase + this.y));
2153 this.lines.length = 1;
2154 this.ydisp = 0;
2155 this.ybase = 0;
2156 this.y = 0;
2157 for (var i = 1; i < this.rows; i++) {
2158 this.lines.push(this.blankLine());
2159 }
2160 this.refresh(0, this.rows - 1);
2161 this.emit('scroll', this.ydisp);
2162 };
2163
2164 /**
2165 * Erase all content in the given line
2166 * @param {number} y The line to erase all of its contents.
2167 */
2168 Terminal.prototype.eraseLine = function(y) {
2169 this.eraseRight(0, y);
2170 };
2171
2172
2173 /**
2174 * Return the data array of a blank line
2175 * @param {number} cur First bunch of data for each "blank" character.
2176 * @param {boolean} isWrapped Whether the new line is wrapped from the previous line.
2177 */
2178 Terminal.prototype.blankLine = function(cur, isWrapped) {
2179 var attr = cur
2180 ? this.eraseAttr()
2181 : this.defAttr;
2182
2183 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
2184 , line = []
2185 , i = 0;
2186
2187 // TODO: It is not ideal that this is a property on an array, a buffer line
2188 // class should be added that will hold this data and other useful functions.
2189 if (isWrapped) {
2190 line.isWrapped = isWrapped;
2191 }
2192
2193 for (; i < this.cols; i++) {
2194 line[i] = ch;
2195 }
2196
2197 return line;
2198 };
2199
2200
2201 /**
2202 * If cur return the back color xterm feature attribute. Else return defAttr.
2203 * @param {object} cur
2204 */
2205 Terminal.prototype.ch = function(cur) {
2206 return cur
2207 ? [this.eraseAttr(), ' ', 1]
2208 : [this.defAttr, ' ', 1];
2209 };
2210
2211
2212 /**
2213 * Evaluate if the current erminal is the given argument.
2214 * @param {object} term The terminal to evaluate
2215 */
2216 Terminal.prototype.is = function(term) {
2217 var name = this.termName;
2218 return (name + '').indexOf(term) === 0;
2219 };
2220
2221
2222 /**
2223 * Emit the 'data' event and populate the given data.
2224 * @param {string} data The data to populate in the event.
2225 */
2226 Terminal.prototype.handler = function(data) {
2227 // Prevents all events to pty process if stdin is disabled
2228 if (this.options.disableStdin) {
2229 return;
2230 }
2231
2232 // Input is being sent to the terminal, the terminal should focus the prompt.
2233 if (this.ybase !== this.ydisp) {
2234 this.scrollToBottom();
2235 }
2236 this.emit('data', data);
2237 };
2238
2239
2240 /**
2241 * Emit the 'title' event and populate the given title.
2242 * @param {string} title The title to populate in the event.
2243 */
2244 Terminal.prototype.handleTitle = function(title) {
2245 /**
2246 * This event is emitted when the title of the terminal is changed
2247 * from inside the terminal. The parameter is the new title.
2248 *
2249 * @event title
2250 */
2251 this.emit('title', title);
2252 };
2253
2254
2255 /**
2256 * ESC
2257 */
2258
2259 /**
2260 * ESC D Index (IND is 0x84).
2261 */
2262 Terminal.prototype.index = function() {
2263 this.y++;
2264 if (this.y > this.scrollBottom) {
2265 this.y--;
2266 this.scroll();
2267 }
2268 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2269 if (this.x >= this.cols) {
2270 this.x--;
2271 }
2272 };
2273
2274
2275 /**
2276 * ESC M Reverse Index (RI is 0x8d).
2277 *
2278 * Move the cursor up one row, inserting a new blank line if necessary.
2279 */
2280 Terminal.prototype.reverseIndex = function() {
2281 var j;
2282 if (this.y === this.scrollTop) {
2283 // possibly move the code below to term.reverseScroll();
2284 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2285 // blankLine(true) is xterm/linux behavior
2286 this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
2287 this.lines.set(this.y + this.ybase, this.blankLine(true));
2288 this.updateRange(this.scrollTop);
2289 this.updateRange(this.scrollBottom);
2290 } else {
2291 this.y--;
2292 }
2293 };
2294
2295
2296 /**
2297 * ESC c Full Reset (RIS).
2298 */
2299 Terminal.prototype.reset = function() {
2300 this.options.rows = this.rows;
2301 this.options.cols = this.cols;
2302 var customKeyEventHandler = this.customKeyEventHandler;
2303 var cursorBlinkInterval = this.cursorBlinkInterval;
2304 Terminal.call(this, this.options);
2305 this.customKeyEventHandler = customKeyEventHandler;
2306 this.cursorBlinkInterval = cursorBlinkInterval;
2307 this.refresh(0, this.rows - 1);
2308 this.viewport.syncScrollArea();
2309 };
2310
2311
2312 /**
2313 * ESC H Tab Set (HTS is 0x88).
2314 */
2315 Terminal.prototype.tabSet = function() {
2316 this.tabs[this.x] = true;
2317 };
2318
2319 /**
2320 * Helpers
2321 */
2322
2323 function on(el, type, handler, capture) {
2324 if (!Array.isArray(el)) {
2325 el = [el];
2326 }
2327 el.forEach(function (element) {
2328 element.addEventListener(type, handler, capture || false);
2329 });
2330 }
2331
2332 function off(el, type, handler, capture) {
2333 el.removeEventListener(type, handler, capture || false);
2334 }
2335
2336 function cancel(ev, force) {
2337 if (!this.cancelEvents && !force) {
2338 return;
2339 }
2340 ev.preventDefault();
2341 ev.stopPropagation();
2342 return false;
2343 }
2344
2345 function inherits(child, parent) {
2346 function f() {
2347 this.constructor = child;
2348 }
2349 f.prototype = parent.prototype;
2350 child.prototype = new f;
2351 }
2352
2353 function indexOf(obj, el) {
2354 var i = obj.length;
2355 while (i--) {
2356 if (obj[i] === el) return i;
2357 }
2358 return -1;
2359 }
2360
2361 function isThirdLevelShift(term, ev) {
2362 var thirdLevelKey =
2363 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
2364 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
2365
2366 if (ev.type == 'keypress') {
2367 return thirdLevelKey;
2368 }
2369
2370 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2371 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
2372 }
2373
2374 // Expose to InputHandler (temporary)
2375 Terminal.prototype.matchColor = matchColor;
2376
2377 function matchColor(r1, g1, b1) {
2378 var hash = (r1 << 16) | (g1 << 8) | b1;
2379
2380 if (matchColor._cache[hash] != null) {
2381 return matchColor._cache[hash];
2382 }
2383
2384 var ldiff = Infinity
2385 , li = -1
2386 , i = 0
2387 , c
2388 , r2
2389 , g2
2390 , b2
2391 , diff;
2392
2393 for (; i < Terminal.vcolors.length; i++) {
2394 c = Terminal.vcolors[i];
2395 r2 = c[0];
2396 g2 = c[1];
2397 b2 = c[2];
2398
2399 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
2400
2401 if (diff === 0) {
2402 li = i;
2403 break;
2404 }
2405
2406 if (diff < ldiff) {
2407 ldiff = diff;
2408 li = i;
2409 }
2410 }
2411
2412 return matchColor._cache[hash] = li;
2413 }
2414
2415 matchColor._cache = {};
2416
2417 // http://stackoverflow.com/questions/1633828
2418 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
2419 return Math.pow(30 * (r1 - r2), 2)
2420 + Math.pow(59 * (g1 - g2), 2)
2421 + Math.pow(11 * (b1 - b2), 2);
2422 };
2423
2424 function each(obj, iter, con) {
2425 if (obj.forEach) return obj.forEach(iter, con);
2426 for (var i = 0; i < obj.length; i++) {
2427 iter.call(con, obj[i], i, obj);
2428 }
2429 }
2430
2431 function wasMondifierKeyOnlyEvent(ev) {
2432 return ev.keyCode === 16 || // Shift
2433 ev.keyCode === 17 || // Ctrl
2434 ev.keyCode === 18; // Alt
2435 }
2436
2437 function keys(obj) {
2438 if (Object.keys) return Object.keys(obj);
2439 var key, keys = [];
2440 for (key in obj) {
2441 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2442 keys.push(key);
2443 }
2444 }
2445 return keys;
2446 }
2447
2448 /**
2449 * Expose
2450 */
2451
2452 Terminal.EventEmitter = EventEmitter;
2453 Terminal.inherits = inherits;
2454
2455 /**
2456 * Adds an event listener to the terminal.
2457 *
2458 * @param {string} event The name of the event. TODO: Document all event types
2459 * @param {function} callback The function to call when the event is triggered.
2460 */
2461 Terminal.on = on;
2462 Terminal.off = off;
2463 Terminal.cancel = cancel;
2464
2465 module.exports = Terminal;