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