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