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