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