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