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