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