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