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