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