]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Temp fix until mouse getCoords PR merged
[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, term.selectionManager);
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, self.rowContainer, self.charMeasure);
805 if (!pos) return;
806
807 // Temp fix until getcoords PR is pushed
808 pos.x = pos[0];
809 pos.y = pos[1];
810 if (pos.x < 0) pos.x = 0;
811 if (pos.x > self.cols) pos.x = self.cols;
812 if (pos.y < 0) pos.y = 0;
813 if (pos.y > self.rows) pos.y = self.rows;
814 pos.x += 32;
815 pos.y += 32;
816
817 sendEvent(button, pos);
818
819 switch (ev.overrideType || ev.type) {
820 case 'mousedown':
821 pressed = button;
822 break;
823 case 'mouseup':
824 // keep it at the left
825 // button, just in case.
826 pressed = 32;
827 break;
828 case 'wheel':
829 // nothing. don't
830 // interfere with
831 // `pressed`.
832 break;
833 }
834 }
835
836 // motion example of a left click:
837 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
838 function sendMove(ev) {
839 var button = pressed
840 , pos;
841
842 pos = Mouse.getCoords(ev, self.rowContainer, self.charMeasure);
843 if (!pos) return;
844
845 // Temp fix until getcoords PR is pushed
846 pos.x = pos[0];
847 pos.y = pos[1];
848 if (pos.x < 0) pos.x = 0;
849 if (pos.x > self.cols) pos.x = self.cols;
850 if (pos.y < 0) pos.y = 0;
851 if (pos.y > self.rows) pos.y = self.rows;
852 pos.x += 32;
853 pos.y += 32;
854
855 // buttons marked as motions
856 // are incremented by 32
857 button += 32;
858
859 sendEvent(button, pos);
860 }
861
862 // encode button and
863 // position to characters
864 function encode(data, ch) {
865 if (!self.utfMouse) {
866 if (ch === 255) return data.push(0);
867 if (ch > 127) ch = 127;
868 data.push(ch);
869 } else {
870 if (ch === 2047) return data.push(0);
871 if (ch < 127) {
872 data.push(ch);
873 } else {
874 if (ch > 2047) ch = 2047;
875 data.push(0xC0 | (ch >> 6));
876 data.push(0x80 | (ch & 0x3F));
877 }
878 }
879 }
880
881 // send a mouse event:
882 // regular/utf8: ^[[M Cb Cx Cy
883 // urxvt: ^[[ Cb ; Cx ; Cy M
884 // sgr: ^[[ Cb ; Cx ; Cy M/m
885 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
886 // locator: CSI P e ; P b ; P r ; P c ; P p & w
887 function sendEvent(button, pos) {
888 // self.emit('mouse', {
889 // x: pos.x - 32,
890 // y: pos.x - 32,
891 // button: button
892 // });
893
894 if (self.vt300Mouse) {
895 // NOTE: Unstable.
896 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
897 button &= 3;
898 pos.x -= 32;
899 pos.y -= 32;
900 var data = C0.ESC + '[24';
901 if (button === 0) data += '1';
902 else if (button === 1) data += '3';
903 else if (button === 2) data += '5';
904 else if (button === 3) return;
905 else data += '0';
906 data += '~[' + pos.x + ',' + pos.y + ']\r';
907 self.send(data);
908 return;
909 }
910
911 if (self.decLocator) {
912 // NOTE: Unstable.
913 button &= 3;
914 pos.x -= 32;
915 pos.y -= 32;
916 if (button === 0) button = 2;
917 else if (button === 1) button = 4;
918 else if (button === 2) button = 6;
919 else if (button === 3) button = 3;
920 self.send(C0.ESC + '['
921 + button
922 + ';'
923 + (button === 3 ? 4 : 0)
924 + ';'
925 + pos.y
926 + ';'
927 + pos.x
928 + ';'
929 + (pos.page || 0)
930 + '&w');
931 return;
932 }
933
934 if (self.urxvtMouse) {
935 pos.x -= 32;
936 pos.y -= 32;
937 pos.x++;
938 pos.y++;
939 self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
940 return;
941 }
942
943 if (self.sgrMouse) {
944 pos.x -= 32;
945 pos.y -= 32;
946 self.send(C0.ESC + '[<'
947 + (((button & 3) === 3 ? button & ~3 : button) - 32)
948 + ';'
949 + pos.x
950 + ';'
951 + pos.y
952 + ((button & 3) === 3 ? 'm' : 'M'));
953 return;
954 }
955
956 var data = [];
957
958 encode(data, button);
959 encode(data, pos.x);
960 encode(data, pos.y);
961
962 self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, data));
963 }
964
965 function getButton(ev) {
966 var button
967 , shift
968 , meta
969 , ctrl
970 , mod;
971
972 // two low bits:
973 // 0 = left
974 // 1 = middle
975 // 2 = right
976 // 3 = release
977 // wheel up/down:
978 // 1, and 2 - with 64 added
979 switch (ev.overrideType || ev.type) {
980 case 'mousedown':
981 button = ev.button != null
982 ? +ev.button
983 : ev.which != null
984 ? ev.which - 1
985 : null;
986
987 if (self.browser.isMSIE) {
988 button = button === 1 ? 0 : button === 4 ? 1 : button;
989 }
990 break;
991 case 'mouseup':
992 button = 3;
993 break;
994 case 'DOMMouseScroll':
995 button = ev.detail < 0
996 ? 64
997 : 65;
998 break;
999 case 'wheel':
1000 button = ev.wheelDeltaY > 0
1001 ? 64
1002 : 65;
1003 break;
1004 }
1005
1006 // next three bits are the modifiers:
1007 // 4 = shift, 8 = meta, 16 = control
1008 shift = ev.shiftKey ? 4 : 0;
1009 meta = ev.metaKey ? 8 : 0;
1010 ctrl = ev.ctrlKey ? 16 : 0;
1011 mod = shift | meta | ctrl;
1012
1013 // no mods
1014 if (self.vt200Mouse) {
1015 // ctrl only
1016 mod &= ctrl;
1017 } else if (!self.normalMouse) {
1018 mod = 0;
1019 }
1020
1021 // increment to SP
1022 button = (32 + (mod << 2)) + button;
1023
1024 return button;
1025 }
1026
1027 // mouse coordinates measured in cols/rows
1028 // function getCoords(ev) {
1029 // var x, y, w, h, el;
1030
1031 // // ignore browsers without pageX for now
1032 // if (ev.pageX == null) return;
1033
1034 // x = ev.pageX;
1035 // y = ev.pageY;
1036 // el = self.rowContainer;
1037
1038 // // should probably check offsetParent
1039 // // but this is more portable
1040 // while (el && el !== self.document.documentElement) {
1041 // x -= el.offsetLeft;
1042 // y -= el.offsetTop;
1043 // el = 'offsetParent' in el
1044 // ? el.offsetParent
1045 // : el.parentNode;
1046 // }
1047
1048 // // convert to cols/rows
1049 // x = Math.ceil(x / self.charMeasure.width);
1050 // y = Math.ceil(y / self.charMeasure.height);
1051
1052 // // be sure to avoid sending
1053 // // bad positions to the program
1054 // if (x < 0) x = 0;
1055 // if (x > self.cols) x = self.cols;
1056 // if (y < 0) y = 0;
1057 // if (y > self.rows) y = self.rows;
1058
1059 // // xterm sends raw bytes and
1060 // // starts at 32 (SP) for each.
1061 // x += 32;
1062 // y += 32;
1063
1064 // return {
1065 // x: x,
1066 // y: y,
1067 // type: 'wheel'
1068 // };
1069 // }
1070
1071 on(el, 'mousedown', function(ev) {
1072 if (!self.mouseEvents) return;
1073
1074 // send the button
1075 sendButton(ev);
1076
1077 // ensure focus
1078 self.focus();
1079
1080 // fix for odd bug
1081 //if (self.vt200Mouse && !self.normalMouse) {
1082 if (self.vt200Mouse) {
1083 ev.overrideType = 'mouseup';
1084 sendButton(ev);
1085 return self.cancel(ev);
1086 }
1087
1088 // bind events
1089 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
1090
1091 // x10 compatibility mode can't send button releases
1092 if (!self.x10Mouse) {
1093 on(self.document, 'mouseup', function up(ev) {
1094 sendButton(ev);
1095 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
1096 off(self.document, 'mouseup', up);
1097 return self.cancel(ev);
1098 });
1099 }
1100
1101 return self.cancel(ev);
1102 });
1103
1104 //if (self.normalMouse) {
1105 // on(self.document, 'mousemove', sendMove);
1106 //}
1107
1108 on(el, 'wheel', function(ev) {
1109 if (!self.mouseEvents) return;
1110 if (self.x10Mouse
1111 || self.vt300Mouse
1112 || self.decLocator) return;
1113 sendButton(ev);
1114 return self.cancel(ev);
1115 });
1116
1117 // allow wheel scrolling in
1118 // the shell for example
1119 on(el, 'wheel', function(ev) {
1120 if (self.mouseEvents) return;
1121 self.viewport.onWheel(ev);
1122 return self.cancel(ev);
1123 });
1124 };
1125
1126 /**
1127 * Destroys the terminal.
1128 */
1129 Terminal.prototype.destroy = function() {
1130 this.readable = false;
1131 this.writable = false;
1132 this._events = {};
1133 this.handler = function() {};
1134 this.write = function() {};
1135 if (this.element && this.element.parentNode) {
1136 this.element.parentNode.removeChild(this.element);
1137 }
1138 //this.emit('close');
1139 };
1140
1141 /**
1142 * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
1143 * opportunity.
1144 * @param {number} start The row to start from (between 0 and this.rows - 1).
1145 * @param {number} end The row to end at (between start and this.rows - 1).
1146 */
1147 Terminal.prototype.refresh = function(start, end) {
1148 if (this.renderer) {
1149 this.renderer.queueRefresh(start, end);
1150 }
1151 };
1152
1153 /**
1154 * Queues linkification for the specified rows.
1155 * @param {number} start The row to start from (between 0 and this.rows - 1).
1156 * @param {number} end The row to end at (between start and this.rows - 1).
1157 */
1158 Terminal.prototype.queueLinkification = function(start, end) {
1159 if (this.linkifier) {
1160 for (let i = start; i <= end; i++) {
1161 this.linkifier.linkifyRow(i);
1162 }
1163 }
1164 }
1165
1166 /**
1167 * Display the cursor element
1168 */
1169 Terminal.prototype.showCursor = function() {
1170 if (!this.cursorState) {
1171 this.cursorState = 1;
1172 this.refresh(this.y, this.y);
1173 }
1174 };
1175
1176 /**
1177 * Scroll the terminal down 1 row, creating a blank line.
1178 */
1179 Terminal.prototype.scroll = function() {
1180 var row;
1181
1182 // Make room for the new row in lines
1183 if (this.lines.length === this.lines.maxLength) {
1184 this.lines.trimStart(1);
1185 this.ybase--;
1186 if (this.ydisp !== 0) {
1187 this.ydisp--;
1188 }
1189 }
1190
1191 this.ybase++;
1192
1193 // TODO: Why is this done twice?
1194 if (!this.userScrolling) {
1195 this.ydisp = this.ybase;
1196 }
1197
1198 // last line
1199 row = this.ybase + this.rows - 1;
1200
1201 // subtract the bottom scroll region
1202 row -= this.rows - 1 - this.scrollBottom;
1203
1204 if (row === this.lines.length) {
1205 // Optimization: pushing is faster than splicing when they amount to the same behavior
1206 this.lines.push(this.blankLine());
1207 } else {
1208 // add our new line
1209 this.lines.splice(row, 0, this.blankLine());
1210 }
1211
1212 if (this.scrollTop !== 0) {
1213 if (this.ybase !== 0) {
1214 this.ybase--;
1215 if (!this.userScrolling) {
1216 this.ydisp = this.ybase;
1217 }
1218 }
1219 this.lines.splice(this.ybase + this.scrollTop, 1);
1220 }
1221
1222 // this.maxRange();
1223 this.updateRange(this.scrollTop);
1224 this.updateRange(this.scrollBottom);
1225
1226 /**
1227 * This event is emitted whenever the terminal is scrolled.
1228 * The one parameter passed is the new y display position.
1229 *
1230 * @event scroll
1231 */
1232 this.emit('scroll', this.ydisp);
1233 };
1234
1235 /**
1236 * Scroll the display of the terminal
1237 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1238 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1239 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1240 * viewport originally.
1241 */
1242 Terminal.prototype.scrollDisp = function(disp, suppressScrollEvent) {
1243 if (disp < 0) {
1244 this.userScrolling = true;
1245 } else if (disp + this.ydisp >= this.ybase) {
1246 this.userScrolling = false;
1247 }
1248
1249 this.ydisp += disp;
1250
1251 if (this.ydisp > this.ybase) {
1252 this.ydisp = this.ybase;
1253 } else if (this.ydisp < 0) {
1254 this.ydisp = 0;
1255 }
1256
1257 if (!suppressScrollEvent) {
1258 this.emit('scroll', this.ydisp);
1259 }
1260
1261 this.refresh(0, this.rows - 1);
1262 };
1263
1264 /**
1265 * Scroll the display of the terminal by a number of pages.
1266 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1267 */
1268 Terminal.prototype.scrollPages = function(pageCount) {
1269 this.scrollDisp(pageCount * (this.rows - 1));
1270 }
1271
1272 /**
1273 * Scrolls the display of the terminal to the top.
1274 */
1275 Terminal.prototype.scrollToTop = function() {
1276 this.scrollDisp(-this.ydisp);
1277 }
1278
1279 /**
1280 * Scrolls the display of the terminal to the bottom.
1281 */
1282 Terminal.prototype.scrollToBottom = function() {
1283 this.scrollDisp(this.ybase - this.ydisp);
1284 }
1285
1286 /**
1287 * Writes text to the terminal.
1288 * @param {string} text The text to write to the terminal.
1289 */
1290 Terminal.prototype.write = function(data) {
1291 this.writeBuffer.push(data);
1292
1293 // Send XOFF to pause the pty process if the write buffer becomes too large so
1294 // xterm.js can catch up before more data is sent. This is necessary in order
1295 // to keep signals such as ^C responsive.
1296 if (this.options.useFlowControl && !this.xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
1297 // XOFF - stop pty pipe
1298 // XON will be triggered by emulator before processing data chunk
1299 this.send(C0.DC3);
1300 this.xoffSentToCatchUp = true;
1301 }
1302
1303 if (!this.writeInProgress && this.writeBuffer.length > 0) {
1304 // Kick off a write which will write all data in sequence recursively
1305 this.writeInProgress = true;
1306 // Kick off an async innerWrite so more writes can come in while processing data
1307 var self = this;
1308 setTimeout(function () {
1309 self.innerWrite();
1310 });
1311 }
1312 }
1313
1314 Terminal.prototype.innerWrite = function() {
1315 var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
1316 while (writeBatch.length > 0) {
1317 var data = writeBatch.shift();
1318 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
1319
1320 // If XOFF was sent in order to catch up with the pty process, resume it if
1321 // the writeBuffer is empty to allow more data to come in.
1322 if (this.xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
1323 this.send(C0.DC1);
1324 this.xoffSentToCatchUp = false;
1325 }
1326
1327 this.refreshStart = this.y;
1328 this.refreshEnd = this.y;
1329
1330 this.parser.parse(data);
1331
1332 this.updateRange(this.y);
1333 this.refresh(this.refreshStart, this.refreshEnd);
1334 }
1335 if (this.writeBuffer.length > 0) {
1336 // Allow renderer to catch up before processing the next batch
1337 var self = this;
1338 setTimeout(function () {
1339 self.innerWrite();
1340 }, 0);
1341 } else {
1342 this.writeInProgress = false;
1343 }
1344 };
1345
1346 /**
1347 * Writes text to the terminal, followed by a break line character (\n).
1348 * @param {string} text The text to write to the terminal.
1349 */
1350 Terminal.prototype.writeln = function(data) {
1351 this.write(data + '\r\n');
1352 };
1353
1354 /**
1355 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
1356 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
1357 * should not.
1358 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
1359 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
1360 * the default action. The function returns whether the event should be processed by xterm.js.
1361 */
1362 Terminal.prototype.attachCustomKeydownHandler = function(customKeydownHandler) {
1363 this.customKeydownHandler = customKeydownHandler;
1364 }
1365
1366 /**
1367 * Attaches a http(s) link handler, forcing web links to behave differently to
1368 * regular <a> tags. This will trigger a refresh as links potentially need to be
1369 * reconstructed. Calling this with null will remove the handler.
1370 * @param {LinkHandler} handler The handler callback function.
1371 */
1372 Terminal.prototype.setHypertextLinkHandler = function(handler) {
1373 if (!this.linkifier) {
1374 throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
1375 }
1376 this.linkifier.setHypertextLinkHandler(handler);
1377 // Refresh to force links to refresh
1378 this.refresh(0, this.rows - 1);
1379 }
1380
1381 /**
1382 * Attaches a validation callback for hypertext links. This is useful to use
1383 * validation logic or to do something with the link's element and url.
1384 * @param {LinkMatcherValidationCallback} callback The callback to use, this can
1385 * be cleared with null.
1386 */
1387 Terminal.prototype.setHypertextValidationCallback = function(handler) {
1388 if (!this.linkifier) {
1389 throw new Error('Cannot attach a hypertext validation callback before Terminal.open is called');
1390 }
1391 this.linkifier.setHypertextValidationCallback(handler);
1392 // Refresh to force links to refresh
1393 this.refresh(0, this.rows - 1);
1394 }
1395
1396 /**
1397 * Registers a link matcher, allowing custom link patterns to be matched and
1398 * handled.
1399 * @param {RegExp} regex The regular expression to search for, specifically
1400 * this searches the textContent of the rows. You will want to use \s to match
1401 * a space ' ' character for example.
1402 * @param {LinkHandler} handler The callback when the link is called.
1403 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1404 * @return {number} The ID of the new matcher, this can be used to deregister.
1405 */
1406 Terminal.prototype.registerLinkMatcher = function(regex, handler, options) {
1407 if (this.linkifier) {
1408 var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
1409 this.refresh(0, this.rows - 1);
1410 return matcherId;
1411 }
1412 }
1413
1414 /**
1415 * Deregisters a link matcher if it has been registered.
1416 * @param {number} matcherId The link matcher's ID (returned after register)
1417 */
1418 Terminal.prototype.deregisterLinkMatcher = function(matcherId) {
1419 if (this.linkifier) {
1420 if (this.linkifier.deregisterLinkMatcher(matcherId)) {
1421 this.refresh(0, this.rows - 1);
1422 }
1423 }
1424 }
1425
1426 /**
1427 * Handle a keydown event
1428 * Key Resources:
1429 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1430 * @param {KeyboardEvent} ev The keydown event to be handled.
1431 */
1432 Terminal.prototype.keyDown = function(ev) {
1433 if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
1434 return false;
1435 }
1436
1437 this.restartCursorBlinking();
1438
1439 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
1440 if (this.ybase !== this.ydisp) {
1441 this.scrollToBottom();
1442 }
1443 return false;
1444 }
1445
1446 var self = this;
1447 var result = this.evaluateKeyEscapeSequence(ev);
1448
1449 if (result.key === C0.DC3) { // XOFF
1450 this.writeStopped = true;
1451 } else if (result.key === C0.DC1) { // XON
1452 this.writeStopped = false;
1453 }
1454
1455 if (result.scrollDisp) {
1456 this.scrollDisp(result.scrollDisp);
1457 return this.cancel(ev, true);
1458 }
1459
1460 if (isThirdLevelShift(this, ev)) {
1461 return true;
1462 }
1463
1464 if (result.cancel) {
1465 // The event is canceled at the end already, is this necessary?
1466 this.cancel(ev, true);
1467 }
1468
1469 if (!result.key) {
1470 return true;
1471 }
1472
1473 this.emit('keydown', ev);
1474 this.emit('key', result.key, ev);
1475 this.showCursor();
1476 this.handler(result.key);
1477
1478 return this.cancel(ev, true);
1479 };
1480
1481 /**
1482 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1483 * returned value is the new key code to pass to the PTY.
1484 *
1485 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1486 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1487 */
1488 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
1489 var result = {
1490 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1491 // canceled at the end of keyDown
1492 cancel: false,
1493 // The new key even to emit
1494 key: undefined,
1495 // The number of characters to scroll, if this is defined it will cancel the event
1496 scrollDisp: undefined
1497 };
1498 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
1499 switch (ev.keyCode) {
1500 case 8:
1501 // backspace
1502 if (ev.shiftKey) {
1503 result.key = C0.BS; // ^H
1504 break;
1505 }
1506 result.key = C0.DEL; // ^?
1507 break;
1508 case 9:
1509 // tab
1510 if (ev.shiftKey) {
1511 result.key = C0.ESC + '[Z';
1512 break;
1513 }
1514 result.key = C0.HT;
1515 result.cancel = true;
1516 break;
1517 case 13:
1518 // return/enter
1519 result.key = C0.CR;
1520 result.cancel = true;
1521 break;
1522 case 27:
1523 // escape
1524 result.key = C0.ESC;
1525 result.cancel = true;
1526 break;
1527 case 37:
1528 // left-arrow
1529 if (modifiers) {
1530 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
1531 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1532 // http://unix.stackexchange.com/a/108106
1533 // macOS uses different escape sequences than linux
1534 if (result.key == C0.ESC + '[1;3D') {
1535 result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
1536 }
1537 } else if (this.applicationCursor) {
1538 result.key = C0.ESC + 'OD';
1539 } else {
1540 result.key = C0.ESC + '[D';
1541 }
1542 break;
1543 case 39:
1544 // right-arrow
1545 if (modifiers) {
1546 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
1547 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1548 // http://unix.stackexchange.com/a/108106
1549 // macOS uses different escape sequences than linux
1550 if (result.key == C0.ESC + '[1;3C') {
1551 result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
1552 }
1553 } else if (this.applicationCursor) {
1554 result.key = C0.ESC + 'OC';
1555 } else {
1556 result.key = C0.ESC + '[C';
1557 }
1558 break;
1559 case 38:
1560 // up-arrow
1561 if (modifiers) {
1562 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
1563 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1564 // http://unix.stackexchange.com/a/108106
1565 if (result.key == C0.ESC + '[1;3A') {
1566 result.key = C0.ESC + '[1;5A';
1567 }
1568 } else if (this.applicationCursor) {
1569 result.key = C0.ESC + 'OA';
1570 } else {
1571 result.key = C0.ESC + '[A';
1572 }
1573 break;
1574 case 40:
1575 // down-arrow
1576 if (modifiers) {
1577 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
1578 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1579 // http://unix.stackexchange.com/a/108106
1580 if (result.key == C0.ESC + '[1;3B') {
1581 result.key = C0.ESC + '[1;5B';
1582 }
1583 } else if (this.applicationCursor) {
1584 result.key = C0.ESC + 'OB';
1585 } else {
1586 result.key = C0.ESC + '[B';
1587 }
1588 break;
1589 case 45:
1590 // insert
1591 if (!ev.shiftKey && !ev.ctrlKey) {
1592 // <Ctrl> or <Shift> + <Insert> are used to
1593 // copy-paste on some systems.
1594 result.key = C0.ESC + '[2~';
1595 }
1596 break;
1597 case 46:
1598 // delete
1599 if (modifiers) {
1600 result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
1601 } else {
1602 result.key = C0.ESC + '[3~';
1603 }
1604 break;
1605 case 36:
1606 // home
1607 if (modifiers)
1608 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
1609 else if (this.applicationCursor)
1610 result.key = C0.ESC + 'OH';
1611 else
1612 result.key = C0.ESC + '[H';
1613 break;
1614 case 35:
1615 // end
1616 if (modifiers)
1617 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
1618 else if (this.applicationCursor)
1619 result.key = C0.ESC + 'OF';
1620 else
1621 result.key = C0.ESC + '[F';
1622 break;
1623 case 33:
1624 // page up
1625 if (ev.shiftKey) {
1626 result.scrollDisp = -(this.rows - 1);
1627 } else {
1628 result.key = C0.ESC + '[5~';
1629 }
1630 break;
1631 case 34:
1632 // page down
1633 if (ev.shiftKey) {
1634 result.scrollDisp = this.rows - 1;
1635 } else {
1636 result.key = C0.ESC + '[6~';
1637 }
1638 break;
1639 case 112:
1640 // F1-F12
1641 if (modifiers) {
1642 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
1643 } else {
1644 result.key = C0.ESC + 'OP';
1645 }
1646 break;
1647 case 113:
1648 if (modifiers) {
1649 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
1650 } else {
1651 result.key = C0.ESC + 'OQ';
1652 }
1653 break;
1654 case 114:
1655 if (modifiers) {
1656 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
1657 } else {
1658 result.key = C0.ESC + 'OR';
1659 }
1660 break;
1661 case 115:
1662 if (modifiers) {
1663 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
1664 } else {
1665 result.key = C0.ESC + 'OS';
1666 }
1667 break;
1668 case 116:
1669 if (modifiers) {
1670 result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
1671 } else {
1672 result.key = C0.ESC + '[15~';
1673 }
1674 break;
1675 case 117:
1676 if (modifiers) {
1677 result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
1678 } else {
1679 result.key = C0.ESC + '[17~';
1680 }
1681 break;
1682 case 118:
1683 if (modifiers) {
1684 result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
1685 } else {
1686 result.key = C0.ESC + '[18~';
1687 }
1688 break;
1689 case 119:
1690 if (modifiers) {
1691 result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
1692 } else {
1693 result.key = C0.ESC + '[19~';
1694 }
1695 break;
1696 case 120:
1697 if (modifiers) {
1698 result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
1699 } else {
1700 result.key = C0.ESC + '[20~';
1701 }
1702 break;
1703 case 121:
1704 if (modifiers) {
1705 result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
1706 } else {
1707 result.key = C0.ESC + '[21~';
1708 }
1709 break;
1710 case 122:
1711 if (modifiers) {
1712 result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
1713 } else {
1714 result.key = C0.ESC + '[23~';
1715 }
1716 break;
1717 case 123:
1718 if (modifiers) {
1719 result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
1720 } else {
1721 result.key = C0.ESC + '[24~';
1722 }
1723 break;
1724 default:
1725 // a-z and space
1726 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
1727 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1728 result.key = String.fromCharCode(ev.keyCode - 64);
1729 } else if (ev.keyCode === 32) {
1730 // NUL
1731 result.key = String.fromCharCode(0);
1732 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
1733 // escape, file sep, group sep, record sep, unit sep
1734 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
1735 } else if (ev.keyCode === 56) {
1736 // delete
1737 result.key = String.fromCharCode(127);
1738 } else if (ev.keyCode === 219) {
1739 // ^[ - Control Sequence Introducer (CSI)
1740 result.key = String.fromCharCode(27);
1741 } else if (ev.keyCode === 220) {
1742 // ^\ - String Terminator (ST)
1743 result.key = String.fromCharCode(28);
1744 } else if (ev.keyCode === 221) {
1745 // ^] - Operating System Command (OSC)
1746 result.key = String.fromCharCode(29);
1747 }
1748 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
1749 // On Mac this is a third level shift. Use <Esc> instead.
1750 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1751 result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
1752 } else if (ev.keyCode === 192) {
1753 result.key = C0.ESC + '`';
1754 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
1755 result.key = C0.ESC + (ev.keyCode - 48);
1756 }
1757 }
1758 break;
1759 }
1760
1761 return result;
1762 };
1763
1764 /**
1765 * Set the G level of the terminal
1766 * @param g
1767 */
1768 Terminal.prototype.setgLevel = function(g) {
1769 this.glevel = g;
1770 this.charset = this.charsets[g];
1771 };
1772
1773 /**
1774 * Set the charset for the given G level of the terminal
1775 * @param g
1776 * @param charset
1777 */
1778 Terminal.prototype.setgCharset = function(g, charset) {
1779 this.charsets[g] = charset;
1780 if (this.glevel === g) {
1781 this.charset = charset;
1782 }
1783 };
1784
1785 /**
1786 * Handle a keypress event.
1787 * Key Resources:
1788 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1789 * @param {KeyboardEvent} ev The keypress event to be handled.
1790 */
1791 Terminal.prototype.keyPress = function(ev) {
1792 var key;
1793
1794 this.cancel(ev);
1795
1796 if (ev.charCode) {
1797 key = ev.charCode;
1798 } else if (ev.which == null) {
1799 key = ev.keyCode;
1800 } else if (ev.which !== 0 && ev.charCode !== 0) {
1801 key = ev.which;
1802 } else {
1803 return false;
1804 }
1805
1806 if (!key || (
1807 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
1808 )) {
1809 return false;
1810 }
1811
1812 key = String.fromCharCode(key);
1813
1814 this.emit('keypress', key, ev);
1815 this.emit('key', key, ev);
1816 this.showCursor();
1817 this.handler(key);
1818
1819 return false;
1820 };
1821
1822 /**
1823 * Send data for handling to the terminal
1824 * @param {string} data
1825 */
1826 Terminal.prototype.send = function(data) {
1827 var self = this;
1828
1829 if (!this.queue) {
1830 setTimeout(function() {
1831 self.handler(self.queue);
1832 self.queue = '';
1833 }, 1);
1834 }
1835
1836 this.queue += data;
1837 };
1838
1839 /**
1840 * Ring the bell.
1841 * Note: We could do sweet things with webaudio here
1842 */
1843 Terminal.prototype.bell = function() {
1844 if (!this.visualBell) return;
1845 var self = this;
1846 this.element.style.borderColor = 'white';
1847 setTimeout(function() {
1848 self.element.style.borderColor = '';
1849 }, 10);
1850 if (this.popOnBell) this.focus();
1851 };
1852
1853 /**
1854 * Log the current state to the console.
1855 */
1856 Terminal.prototype.log = function() {
1857 if (!this.debug) return;
1858 if (!this.context.console || !this.context.console.log) return;
1859 var args = Array.prototype.slice.call(arguments);
1860 this.context.console.log.apply(this.context.console, args);
1861 };
1862
1863 /**
1864 * Log the current state as error to the console.
1865 */
1866 Terminal.prototype.error = function() {
1867 if (!this.debug) return;
1868 if (!this.context.console || !this.context.console.error) return;
1869 var args = Array.prototype.slice.call(arguments);
1870 this.context.console.error.apply(this.context.console, args);
1871 };
1872
1873 /**
1874 * Resizes the terminal.
1875 *
1876 * @param {number} x The number of columns to resize to.
1877 * @param {number} y The number of rows to resize to.
1878 */
1879 Terminal.prototype.resize = function(x, y) {
1880 if (isNaN(x) || isNaN(y)) {
1881 return;
1882 }
1883
1884 var line
1885 , el
1886 , i
1887 , j
1888 , ch
1889 , addToY;
1890
1891 if (x === this.cols && y === this.rows) {
1892 return;
1893 }
1894
1895 if (x < 1) x = 1;
1896 if (y < 1) y = 1;
1897
1898 // resize cols
1899 j = this.cols;
1900 if (j < x) {
1901 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
1902 i = this.lines.length;
1903 while (i--) {
1904 while (this.lines.get(i).length < x) {
1905 this.lines.get(i).push(ch);
1906 }
1907 }
1908 }
1909
1910 this.cols = x;
1911 this.setupStops(this.cols);
1912
1913 // resize rows
1914 j = this.rows;
1915 addToY = 0;
1916 if (j < y) {
1917 el = this.element;
1918 while (j++ < y) {
1919 // y is rows, not this.y
1920 if (this.lines.length < y + this.ybase) {
1921 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
1922 // There is room above the buffer and there are no empty elements below the line,
1923 // scroll up
1924 this.ybase--;
1925 addToY++
1926 if (this.ydisp > 0) {
1927 // Viewport is at the top of the buffer, must increase downwards
1928 this.ydisp--;
1929 }
1930 } else {
1931 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1932 // are blank lines after the cursor
1933 this.lines.push(this.blankLine());
1934 }
1935 }
1936 if (this.children.length < y) {
1937 this.insertRow();
1938 }
1939 }
1940 } else { // (j > y)
1941 while (j-- > y) {
1942 if (this.lines.length > y + this.ybase) {
1943 if (this.lines.length > this.ybase + this.y + 1) {
1944 // The line is a blank line below the cursor, remove it
1945 this.lines.pop();
1946 } else {
1947 // The line is the cursor, scroll down
1948 this.ybase++;
1949 this.ydisp++;
1950 }
1951 }
1952 if (this.children.length > y) {
1953 el = this.children.shift();
1954 if (!el) continue;
1955 el.parentNode.removeChild(el);
1956 }
1957 }
1958 }
1959 this.rows = y;
1960
1961 // Make sure that the cursor stays on screen
1962 if (this.y >= y) {
1963 this.y = y - 1;
1964 }
1965 if (addToY) {
1966 this.y += addToY;
1967 }
1968
1969 if (this.x >= x) {
1970 this.x = x - 1;
1971 }
1972
1973 this.scrollTop = 0;
1974 this.scrollBottom = y - 1;
1975
1976 this.charMeasure.measure();
1977
1978 this.refresh(0, this.rows - 1);
1979
1980 this.normal = null;
1981
1982 this.geometry = [this.cols, this.rows];
1983 this.emit('resize', {terminal: this, cols: x, rows: y});
1984 };
1985
1986 /**
1987 * Updates the range of rows to refresh
1988 * @param {number} y The number of rows to refresh next.
1989 */
1990 Terminal.prototype.updateRange = function(y) {
1991 if (y < this.refreshStart) this.refreshStart = y;
1992 if (y > this.refreshEnd) this.refreshEnd = y;
1993 // if (y > this.refreshEnd) {
1994 // this.refreshEnd = y;
1995 // if (y > this.rows - 1) {
1996 // this.refreshEnd = this.rows - 1;
1997 // }
1998 // }
1999 };
2000
2001 /**
2002 * Set the range of refreshing to the maximum value
2003 */
2004 Terminal.prototype.maxRange = function() {
2005 this.refreshStart = 0;
2006 this.refreshEnd = this.rows - 1;
2007 };
2008
2009
2010
2011 /**
2012 * Setup the tab stops.
2013 * @param {number} i
2014 */
2015 Terminal.prototype.setupStops = function(i) {
2016 if (i != null) {
2017 if (!this.tabs[i]) {
2018 i = this.prevStop(i);
2019 }
2020 } else {
2021 this.tabs = {};
2022 i = 0;
2023 }
2024
2025 for (; i < this.cols; i += this.getOption('tabStopWidth')) {
2026 this.tabs[i] = true;
2027 }
2028 };
2029
2030
2031 /**
2032 * Move the cursor to the previous tab stop from the given position (default is current).
2033 * @param {number} x The position to move the cursor to the previous tab stop.
2034 */
2035 Terminal.prototype.prevStop = function(x) {
2036 if (x == null) x = this.x;
2037 while (!this.tabs[--x] && x > 0);
2038 return x >= this.cols
2039 ? this.cols - 1
2040 : x < 0 ? 0 : x;
2041 };
2042
2043
2044 /**
2045 * Move the cursor one tab stop forward from the given position (default is current).
2046 * @param {number} x The position to move the cursor one tab stop forward.
2047 */
2048 Terminal.prototype.nextStop = function(x) {
2049 if (x == null) x = this.x;
2050 while (!this.tabs[++x] && x < this.cols);
2051 return x >= this.cols
2052 ? this.cols - 1
2053 : x < 0 ? 0 : x;
2054 };
2055
2056
2057 /**
2058 * Erase in the identified line everything from "x" to the end of the line (right).
2059 * @param {number} x The column from which to start erasing to the end of the line.
2060 * @param {number} y The line in which to operate.
2061 */
2062 Terminal.prototype.eraseRight = function(x, y) {
2063 var line = this.lines.get(this.ybase + y);
2064 if (!line) {
2065 return;
2066 }
2067 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2068 for (; x < this.cols; x++) {
2069 line[x] = ch;
2070 }
2071 this.updateRange(y);
2072 };
2073
2074
2075
2076 /**
2077 * Erase in the identified line everything from "x" to the start of the line (left).
2078 * @param {number} x The column from which to start erasing to the start of the line.
2079 * @param {number} y The line in which to operate.
2080 */
2081 Terminal.prototype.eraseLeft = function(x, y) {
2082 var line = this.lines.get(this.ybase + y);
2083 if (!line) {
2084 return;
2085 }
2086 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2087 x++;
2088 while (x--) {
2089 line[x] = ch;
2090 }
2091 this.updateRange(y);
2092 };
2093
2094 /**
2095 * Clears the entire buffer, making the prompt line the new first line.
2096 */
2097 Terminal.prototype.clear = function() {
2098 if (this.ybase === 0 && this.y === 0) {
2099 // Don't clear if it's already clear
2100 return;
2101 }
2102 this.lines.set(0, this.lines.get(this.ybase + this.y));
2103 this.lines.length = 1;
2104 this.ydisp = 0;
2105 this.ybase = 0;
2106 this.y = 0;
2107 for (var i = 1; i < this.rows; i++) {
2108 this.lines.push(this.blankLine());
2109 }
2110 this.refresh(0, this.rows - 1);
2111 this.emit('scroll', this.ydisp);
2112 };
2113
2114 /**
2115 * Erase all content in the given line
2116 * @param {number} y The line to erase all of its contents.
2117 */
2118 Terminal.prototype.eraseLine = function(y) {
2119 this.eraseRight(0, y);
2120 };
2121
2122
2123 /**
2124 * Return the data array of a blank line
2125 * @param {number} cur First bunch of data for each "blank" character.
2126 */
2127 Terminal.prototype.blankLine = function(cur) {
2128 var attr = cur
2129 ? this.eraseAttr()
2130 : this.defAttr;
2131
2132 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
2133 , line = []
2134 , i = 0;
2135
2136 for (; i < this.cols; i++) {
2137 line[i] = ch;
2138 }
2139
2140 return line;
2141 };
2142
2143
2144 /**
2145 * If cur return the back color xterm feature attribute. Else return defAttr.
2146 * @param {object} cur
2147 */
2148 Terminal.prototype.ch = function(cur) {
2149 return cur
2150 ? [this.eraseAttr(), ' ', 1]
2151 : [this.defAttr, ' ', 1];
2152 };
2153
2154
2155 /**
2156 * Evaluate if the current erminal is the given argument.
2157 * @param {object} term The terminal to evaluate
2158 */
2159 Terminal.prototype.is = function(term) {
2160 var name = this.termName;
2161 return (name + '').indexOf(term) === 0;
2162 };
2163
2164
2165 /**
2166 * Emit the 'data' event and populate the given data.
2167 * @param {string} data The data to populate in the event.
2168 */
2169 Terminal.prototype.handler = function(data) {
2170 // Prevents all events to pty process if stdin is disabled
2171 if (this.options.disableStdin) {
2172 return;
2173 }
2174
2175 // Input is being sent to the terminal, the terminal should focus the prompt.
2176 if (this.ybase !== this.ydisp) {
2177 this.scrollToBottom();
2178 }
2179 this.emit('data', data);
2180 };
2181
2182
2183 /**
2184 * Emit the 'title' event and populate the given title.
2185 * @param {string} title The title to populate in the event.
2186 */
2187 Terminal.prototype.handleTitle = function(title) {
2188 /**
2189 * This event is emitted when the title of the terminal is changed
2190 * from inside the terminal. The parameter is the new title.
2191 *
2192 * @event title
2193 */
2194 this.emit('title', title);
2195 };
2196
2197
2198 /**
2199 * ESC
2200 */
2201
2202 /**
2203 * ESC D Index (IND is 0x84).
2204 */
2205 Terminal.prototype.index = function() {
2206 this.y++;
2207 if (this.y > this.scrollBottom) {
2208 this.y--;
2209 this.scroll();
2210 }
2211 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2212 if (this.x >= this.cols) {
2213 this.x--;
2214 }
2215 };
2216
2217
2218 /**
2219 * ESC M Reverse Index (RI is 0x8d).
2220 *
2221 * Move the cursor up one row, inserting a new blank line if necessary.
2222 */
2223 Terminal.prototype.reverseIndex = function() {
2224 var j;
2225 if (this.y === this.scrollTop) {
2226 // possibly move the code below to term.reverseScroll();
2227 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2228 // blankLine(true) is xterm/linux behavior
2229 this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
2230 this.lines.set(this.y + this.ybase, this.blankLine(true));
2231 this.updateRange(this.scrollTop);
2232 this.updateRange(this.scrollBottom);
2233 } else {
2234 this.y--;
2235 }
2236 };
2237
2238
2239 /**
2240 * ESC c Full Reset (RIS).
2241 */
2242 Terminal.prototype.reset = function() {
2243 this.options.rows = this.rows;
2244 this.options.cols = this.cols;
2245 var customKeydownHandler = this.customKeydownHandler;
2246 var cursorBlinkInterval = this.cursorBlinkInterval;
2247 Terminal.call(this, this.options);
2248 this.customKeydownHandler = customKeydownHandler;
2249 this.cursorBlinkInterval = cursorBlinkInterval;
2250 this.refresh(0, this.rows - 1);
2251 this.viewport.syncScrollArea();
2252 };
2253
2254
2255 /**
2256 * ESC H Tab Set (HTS is 0x88).
2257 */
2258 Terminal.prototype.tabSet = function() {
2259 this.tabs[this.x] = true;
2260 };
2261
2262 /**
2263 * Helpers
2264 */
2265
2266 function on(el, type, handler, capture) {
2267 if (!Array.isArray(el)) {
2268 el = [el];
2269 }
2270 el.forEach(function (element) {
2271 element.addEventListener(type, handler, capture || false);
2272 });
2273 }
2274
2275 function off(el, type, handler, capture) {
2276 el.removeEventListener(type, handler, capture || false);
2277 }
2278
2279 function cancel(ev, force) {
2280 if (!this.cancelEvents && !force) {
2281 return;
2282 }
2283 ev.preventDefault();
2284 ev.stopPropagation();
2285 return false;
2286 }
2287
2288 function inherits(child, parent) {
2289 function f() {
2290 this.constructor = child;
2291 }
2292 f.prototype = parent.prototype;
2293 child.prototype = new f;
2294 }
2295
2296 function indexOf(obj, el) {
2297 var i = obj.length;
2298 while (i--) {
2299 if (obj[i] === el) return i;
2300 }
2301 return -1;
2302 }
2303
2304 function isThirdLevelShift(term, ev) {
2305 var thirdLevelKey =
2306 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
2307 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
2308
2309 if (ev.type == 'keypress') {
2310 return thirdLevelKey;
2311 }
2312
2313 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2314 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
2315 }
2316
2317 // Expose to InputHandler (temporary)
2318 Terminal.prototype.matchColor = matchColor;
2319
2320 function matchColor(r1, g1, b1) {
2321 var hash = (r1 << 16) | (g1 << 8) | b1;
2322
2323 if (matchColor._cache[hash] != null) {
2324 return matchColor._cache[hash];
2325 }
2326
2327 var ldiff = Infinity
2328 , li = -1
2329 , i = 0
2330 , c
2331 , r2
2332 , g2
2333 , b2
2334 , diff;
2335
2336 for (; i < Terminal.vcolors.length; i++) {
2337 c = Terminal.vcolors[i];
2338 r2 = c[0];
2339 g2 = c[1];
2340 b2 = c[2];
2341
2342 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
2343
2344 if (diff === 0) {
2345 li = i;
2346 break;
2347 }
2348
2349 if (diff < ldiff) {
2350 ldiff = diff;
2351 li = i;
2352 }
2353 }
2354
2355 return matchColor._cache[hash] = li;
2356 }
2357
2358 matchColor._cache = {};
2359
2360 // http://stackoverflow.com/questions/1633828
2361 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
2362 return Math.pow(30 * (r1 - r2), 2)
2363 + Math.pow(59 * (g1 - g2), 2)
2364 + Math.pow(11 * (b1 - b2), 2);
2365 };
2366
2367 function each(obj, iter, con) {
2368 if (obj.forEach) return obj.forEach(iter, con);
2369 for (var i = 0; i < obj.length; i++) {
2370 iter.call(con, obj[i], i, obj);
2371 }
2372 }
2373
2374 function wasMondifierKeyOnlyEvent(ev) {
2375 return ev.keyCode === 16 || // Shift
2376 ev.keyCode === 17 || // Ctrl
2377 ev.keyCode === 18; // Alt
2378 }
2379
2380 function keys(obj) {
2381 if (Object.keys) return Object.keys(obj);
2382 var key, keys = [];
2383 for (key in obj) {
2384 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2385 keys.push(key);
2386 }
2387 }
2388 return keys;
2389 }
2390
2391 /**
2392 * Expose
2393 */
2394
2395 Terminal.EventEmitter = EventEmitter;
2396 Terminal.inherits = inherits;
2397
2398 /**
2399 * Adds an event listener to the terminal.
2400 *
2401 * @param {string} event The name of the event. TODO: Document all event types
2402 * @param {function} callback The function to call when the event is triggered.
2403 */
2404 Terminal.on = on;
2405 Terminal.off = off;
2406 Terminal.cancel = cancel;
2407
2408 module.exports = Terminal;