]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Merge remote-tracking branch 'ups/master' into 612_multiple_links_in_row
[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.attachHypertextLinkHandler = 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.attachHypertextLinkHandler(handler);
1327 // Refresh to force links to refresh
1328 this.refresh(0, this.rows - 1);
1329 }
1330
1331 /**
1332 * Registers a link matcher, allowing custom link patterns to be matched and
1333 * handled.
1334 * @param {RegExp} regex The regular expression to search for, specifically
1335 * this searches the textContent of the rows. You will want to use \s to match
1336 * a space ' ' character for example.
1337 * @param {LinkHandler} handler The callback when the link is called.
1338 * @param {LinkMatcherOptions} [options] Options for the link matcher.
1339 * @return {number} The ID of the new matcher, this can be used to deregister.
1340 */
1341 Terminal.prototype.registerLinkMatcher = function(regex, handler, options) {
1342 if (this.linkifier) {
1343 var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
1344 this.refresh(0, this.rows - 1);
1345 return matcherId;
1346 }
1347 }
1348
1349 /**
1350 * Deregisters a link matcher if it has been registered.
1351 * @param {number} matcherId The link matcher's ID (returned after register)
1352 */
1353 Terminal.prototype.deregisterLinkMatcher = function(matcherId) {
1354 if (this.linkifier) {
1355 if (this.linkifier.deregisterLinkMatcher(matcherId)) {
1356 this.refresh(0, this.rows - 1);
1357 }
1358 }
1359 }
1360
1361 /**
1362 * Handle a keydown event
1363 * Key Resources:
1364 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1365 * @param {KeyboardEvent} ev The keydown event to be handled.
1366 */
1367 Terminal.prototype.keyDown = function(ev) {
1368 if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
1369 return false;
1370 }
1371
1372 this.restartCursorBlinking();
1373
1374 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
1375 if (this.ybase !== this.ydisp) {
1376 this.scrollToBottom();
1377 }
1378 return false;
1379 }
1380
1381 var self = this;
1382 var result = this.evaluateKeyEscapeSequence(ev);
1383
1384 if (result.key === C0.DC3) { // XOFF
1385 this.writeStopped = true;
1386 } else if (result.key === C0.DC1) { // XON
1387 this.writeStopped = false;
1388 }
1389
1390 if (result.scrollDisp) {
1391 this.scrollDisp(result.scrollDisp);
1392 return this.cancel(ev, true);
1393 }
1394
1395 if (isThirdLevelShift(this, ev)) {
1396 return true;
1397 }
1398
1399 if (result.cancel) {
1400 // The event is canceled at the end already, is this necessary?
1401 this.cancel(ev, true);
1402 }
1403
1404 if (!result.key) {
1405 return true;
1406 }
1407
1408 this.emit('keydown', ev);
1409 this.emit('key', result.key, ev);
1410 this.showCursor();
1411 this.handler(result.key);
1412
1413 return this.cancel(ev, true);
1414 };
1415
1416 /**
1417 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
1418 * returned value is the new key code to pass to the PTY.
1419 *
1420 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1421 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
1422 */
1423 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
1424 var result = {
1425 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
1426 // canceled at the end of keyDown
1427 cancel: false,
1428 // The new key even to emit
1429 key: undefined,
1430 // The number of characters to scroll, if this is defined it will cancel the event
1431 scrollDisp: undefined
1432 };
1433 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
1434 switch (ev.keyCode) {
1435 case 8:
1436 // backspace
1437 if (ev.shiftKey) {
1438 result.key = C0.BS; // ^H
1439 break;
1440 }
1441 result.key = C0.DEL; // ^?
1442 break;
1443 case 9:
1444 // tab
1445 if (ev.shiftKey) {
1446 result.key = C0.ESC + '[Z';
1447 break;
1448 }
1449 result.key = C0.HT;
1450 result.cancel = true;
1451 break;
1452 case 13:
1453 // return/enter
1454 result.key = C0.CR;
1455 result.cancel = true;
1456 break;
1457 case 27:
1458 // escape
1459 result.key = C0.ESC;
1460 result.cancel = true;
1461 break;
1462 case 37:
1463 // left-arrow
1464 if (modifiers) {
1465 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
1466 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1467 // http://unix.stackexchange.com/a/108106
1468 // macOS uses different escape sequences than linux
1469 if (result.key == C0.ESC + '[1;3D') {
1470 result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
1471 }
1472 } else if (this.applicationCursor) {
1473 result.key = C0.ESC + 'OD';
1474 } else {
1475 result.key = C0.ESC + '[D';
1476 }
1477 break;
1478 case 39:
1479 // right-arrow
1480 if (modifiers) {
1481 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
1482 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1483 // http://unix.stackexchange.com/a/108106
1484 // macOS uses different escape sequences than linux
1485 if (result.key == C0.ESC + '[1;3C') {
1486 result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
1487 }
1488 } else if (this.applicationCursor) {
1489 result.key = C0.ESC + 'OC';
1490 } else {
1491 result.key = C0.ESC + '[C';
1492 }
1493 break;
1494 case 38:
1495 // up-arrow
1496 if (modifiers) {
1497 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
1498 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1499 // http://unix.stackexchange.com/a/108106
1500 if (result.key == C0.ESC + '[1;3A') {
1501 result.key = C0.ESC + '[1;5A';
1502 }
1503 } else if (this.applicationCursor) {
1504 result.key = C0.ESC + 'OA';
1505 } else {
1506 result.key = C0.ESC + '[A';
1507 }
1508 break;
1509 case 40:
1510 // down-arrow
1511 if (modifiers) {
1512 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
1513 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1514 // http://unix.stackexchange.com/a/108106
1515 if (result.key == C0.ESC + '[1;3B') {
1516 result.key = C0.ESC + '[1;5B';
1517 }
1518 } else if (this.applicationCursor) {
1519 result.key = C0.ESC + 'OB';
1520 } else {
1521 result.key = C0.ESC + '[B';
1522 }
1523 break;
1524 case 45:
1525 // insert
1526 if (!ev.shiftKey && !ev.ctrlKey) {
1527 // <Ctrl> or <Shift> + <Insert> are used to
1528 // copy-paste on some systems.
1529 result.key = C0.ESC + '[2~';
1530 }
1531 break;
1532 case 46:
1533 // delete
1534 if (modifiers) {
1535 result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
1536 } else {
1537 result.key = C0.ESC + '[3~';
1538 }
1539 break;
1540 case 36:
1541 // home
1542 if (modifiers)
1543 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
1544 else if (this.applicationCursor)
1545 result.key = C0.ESC + 'OH';
1546 else
1547 result.key = C0.ESC + '[H';
1548 break;
1549 case 35:
1550 // end
1551 if (modifiers)
1552 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
1553 else if (this.applicationCursor)
1554 result.key = C0.ESC + 'OF';
1555 else
1556 result.key = C0.ESC + '[F';
1557 break;
1558 case 33:
1559 // page up
1560 if (ev.shiftKey) {
1561 result.scrollDisp = -(this.rows - 1);
1562 } else {
1563 result.key = C0.ESC + '[5~';
1564 }
1565 break;
1566 case 34:
1567 // page down
1568 if (ev.shiftKey) {
1569 result.scrollDisp = this.rows - 1;
1570 } else {
1571 result.key = C0.ESC + '[6~';
1572 }
1573 break;
1574 case 112:
1575 // F1-F12
1576 if (modifiers) {
1577 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
1578 } else {
1579 result.key = C0.ESC + 'OP';
1580 }
1581 break;
1582 case 113:
1583 if (modifiers) {
1584 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
1585 } else {
1586 result.key = C0.ESC + 'OQ';
1587 }
1588 break;
1589 case 114:
1590 if (modifiers) {
1591 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
1592 } else {
1593 result.key = C0.ESC + 'OR';
1594 }
1595 break;
1596 case 115:
1597 if (modifiers) {
1598 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
1599 } else {
1600 result.key = C0.ESC + 'OS';
1601 }
1602 break;
1603 case 116:
1604 if (modifiers) {
1605 result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
1606 } else {
1607 result.key = C0.ESC + '[15~';
1608 }
1609 break;
1610 case 117:
1611 if (modifiers) {
1612 result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
1613 } else {
1614 result.key = C0.ESC + '[17~';
1615 }
1616 break;
1617 case 118:
1618 if (modifiers) {
1619 result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
1620 } else {
1621 result.key = C0.ESC + '[18~';
1622 }
1623 break;
1624 case 119:
1625 if (modifiers) {
1626 result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
1627 } else {
1628 result.key = C0.ESC + '[19~';
1629 }
1630 break;
1631 case 120:
1632 if (modifiers) {
1633 result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
1634 } else {
1635 result.key = C0.ESC + '[20~';
1636 }
1637 break;
1638 case 121:
1639 if (modifiers) {
1640 result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
1641 } else {
1642 result.key = C0.ESC + '[21~';
1643 }
1644 break;
1645 case 122:
1646 if (modifiers) {
1647 result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
1648 } else {
1649 result.key = C0.ESC + '[23~';
1650 }
1651 break;
1652 case 123:
1653 if (modifiers) {
1654 result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
1655 } else {
1656 result.key = C0.ESC + '[24~';
1657 }
1658 break;
1659 default:
1660 // a-z and space
1661 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
1662 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1663 result.key = String.fromCharCode(ev.keyCode - 64);
1664 } else if (ev.keyCode === 32) {
1665 // NUL
1666 result.key = String.fromCharCode(0);
1667 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
1668 // escape, file sep, group sep, record sep, unit sep
1669 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
1670 } else if (ev.keyCode === 56) {
1671 // delete
1672 result.key = String.fromCharCode(127);
1673 } else if (ev.keyCode === 219) {
1674 // ^[ - Control Sequence Introducer (CSI)
1675 result.key = String.fromCharCode(27);
1676 } else if (ev.keyCode === 220) {
1677 // ^\ - String Terminator (ST)
1678 result.key = String.fromCharCode(28);
1679 } else if (ev.keyCode === 221) {
1680 // ^] - Operating System Command (OSC)
1681 result.key = String.fromCharCode(29);
1682 }
1683 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
1684 // On Mac this is a third level shift. Use <Esc> instead.
1685 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1686 result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
1687 } else if (ev.keyCode === 192) {
1688 result.key = C0.ESC + '`';
1689 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
1690 result.key = C0.ESC + (ev.keyCode - 48);
1691 }
1692 }
1693 break;
1694 }
1695
1696 return result;
1697 };
1698
1699 /**
1700 * Set the G level of the terminal
1701 * @param g
1702 */
1703 Terminal.prototype.setgLevel = function(g) {
1704 this.glevel = g;
1705 this.charset = this.charsets[g];
1706 };
1707
1708 /**
1709 * Set the charset for the given G level of the terminal
1710 * @param g
1711 * @param charset
1712 */
1713 Terminal.prototype.setgCharset = function(g, charset) {
1714 this.charsets[g] = charset;
1715 if (this.glevel === g) {
1716 this.charset = charset;
1717 }
1718 };
1719
1720 /**
1721 * Handle a keypress event.
1722 * Key Resources:
1723 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1724 * @param {KeyboardEvent} ev The keypress event to be handled.
1725 */
1726 Terminal.prototype.keyPress = function(ev) {
1727 var key;
1728
1729 this.cancel(ev);
1730
1731 if (ev.charCode) {
1732 key = ev.charCode;
1733 } else if (ev.which == null) {
1734 key = ev.keyCode;
1735 } else if (ev.which !== 0 && ev.charCode !== 0) {
1736 key = ev.which;
1737 } else {
1738 return false;
1739 }
1740
1741 if (!key || (
1742 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
1743 )) {
1744 return false;
1745 }
1746
1747 key = String.fromCharCode(key);
1748
1749 this.emit('keypress', key, ev);
1750 this.emit('key', key, ev);
1751 this.showCursor();
1752 this.handler(key);
1753
1754 return false;
1755 };
1756
1757 /**
1758 * Send data for handling to the terminal
1759 * @param {string} data
1760 */
1761 Terminal.prototype.send = function(data) {
1762 var self = this;
1763
1764 if (!this.queue) {
1765 setTimeout(function() {
1766 self.handler(self.queue);
1767 self.queue = '';
1768 }, 1);
1769 }
1770
1771 this.queue += data;
1772 };
1773
1774 /**
1775 * Ring the bell.
1776 * Note: We could do sweet things with webaudio here
1777 */
1778 Terminal.prototype.bell = function() {
1779 if (!this.visualBell) return;
1780 var self = this;
1781 this.element.style.borderColor = 'white';
1782 setTimeout(function() {
1783 self.element.style.borderColor = '';
1784 }, 10);
1785 if (this.popOnBell) this.focus();
1786 };
1787
1788 /**
1789 * Log the current state to the console.
1790 */
1791 Terminal.prototype.log = function() {
1792 if (!this.debug) return;
1793 if (!this.context.console || !this.context.console.log) return;
1794 var args = Array.prototype.slice.call(arguments);
1795 this.context.console.log.apply(this.context.console, args);
1796 };
1797
1798 /**
1799 * Log the current state as error to the console.
1800 */
1801 Terminal.prototype.error = function() {
1802 if (!this.debug) return;
1803 if (!this.context.console || !this.context.console.error) return;
1804 var args = Array.prototype.slice.call(arguments);
1805 this.context.console.error.apply(this.context.console, args);
1806 };
1807
1808 /**
1809 * Resizes the terminal.
1810 *
1811 * @param {number} x The number of columns to resize to.
1812 * @param {number} y The number of rows to resize to.
1813 */
1814 Terminal.prototype.resize = function(x, y) {
1815 if (isNaN(x) || isNaN(y)) {
1816 return;
1817 }
1818
1819 var line
1820 , el
1821 , i
1822 , j
1823 , ch
1824 , addToY;
1825
1826 if (x === this.cols && y === this.rows) {
1827 return;
1828 }
1829
1830 if (x < 1) x = 1;
1831 if (y < 1) y = 1;
1832
1833 // resize cols
1834 j = this.cols;
1835 if (j < x) {
1836 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
1837 i = this.lines.length;
1838 while (i--) {
1839 while (this.lines.get(i).length < x) {
1840 this.lines.get(i).push(ch);
1841 }
1842 }
1843 }
1844
1845 this.cols = x;
1846 this.setupStops(this.cols);
1847
1848 // resize rows
1849 j = this.rows;
1850 addToY = 0;
1851 if (j < y) {
1852 el = this.element;
1853 while (j++ < y) {
1854 // y is rows, not this.y
1855 if (this.lines.length < y + this.ybase) {
1856 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
1857 // There is room above the buffer and there are no empty elements below the line,
1858 // scroll up
1859 this.ybase--;
1860 addToY++
1861 if (this.ydisp > 0) {
1862 // Viewport is at the top of the buffer, must increase downwards
1863 this.ydisp--;
1864 }
1865 } else {
1866 // Add a blank line if there is no buffer left at the top to scroll to, or if there
1867 // are blank lines after the cursor
1868 this.lines.push(this.blankLine());
1869 }
1870 }
1871 if (this.children.length < y) {
1872 this.insertRow();
1873 }
1874 }
1875 } else { // (j > y)
1876 while (j-- > y) {
1877 if (this.lines.length > y + this.ybase) {
1878 if (this.lines.length > this.ybase + this.y + 1) {
1879 // The line is a blank line below the cursor, remove it
1880 this.lines.pop();
1881 } else {
1882 // The line is the cursor, scroll down
1883 this.ybase++;
1884 this.ydisp++;
1885 }
1886 }
1887 if (this.children.length > y) {
1888 el = this.children.shift();
1889 if (!el) continue;
1890 el.parentNode.removeChild(el);
1891 }
1892 }
1893 }
1894 this.rows = y;
1895
1896 // Make sure that the cursor stays on screen
1897 if (this.y >= y) {
1898 this.y = y - 1;
1899 }
1900 if (addToY) {
1901 this.y += addToY;
1902 }
1903
1904 if (this.x >= x) {
1905 this.x = x - 1;
1906 }
1907
1908 this.scrollTop = 0;
1909 this.scrollBottom = y - 1;
1910
1911 this.charMeasure.measure();
1912
1913 this.refresh(0, this.rows - 1);
1914
1915 this.normal = null;
1916
1917 this.geometry = [this.cols, this.rows];
1918 this.emit('resize', {terminal: this, cols: x, rows: y});
1919 };
1920
1921 /**
1922 * Updates the range of rows to refresh
1923 * @param {number} y The number of rows to refresh next.
1924 */
1925 Terminal.prototype.updateRange = function(y) {
1926 if (y < this.refreshStart) this.refreshStart = y;
1927 if (y > this.refreshEnd) this.refreshEnd = y;
1928 // if (y > this.refreshEnd) {
1929 // this.refreshEnd = y;
1930 // if (y > this.rows - 1) {
1931 // this.refreshEnd = this.rows - 1;
1932 // }
1933 // }
1934 };
1935
1936 /**
1937 * Set the range of refreshing to the maximum value
1938 */
1939 Terminal.prototype.maxRange = function() {
1940 this.refreshStart = 0;
1941 this.refreshEnd = this.rows - 1;
1942 };
1943
1944
1945
1946 /**
1947 * Setup the tab stops.
1948 * @param {number} i
1949 */
1950 Terminal.prototype.setupStops = function(i) {
1951 if (i != null) {
1952 if (!this.tabs[i]) {
1953 i = this.prevStop(i);
1954 }
1955 } else {
1956 this.tabs = {};
1957 i = 0;
1958 }
1959
1960 for (; i < this.cols; i += this.getOption('tabStopWidth')) {
1961 this.tabs[i] = true;
1962 }
1963 };
1964
1965
1966 /**
1967 * Move the cursor to the previous tab stop from the given position (default is current).
1968 * @param {number} x The position to move the cursor to the previous tab stop.
1969 */
1970 Terminal.prototype.prevStop = function(x) {
1971 if (x == null) x = this.x;
1972 while (!this.tabs[--x] && x > 0);
1973 return x >= this.cols
1974 ? this.cols - 1
1975 : x < 0 ? 0 : x;
1976 };
1977
1978
1979 /**
1980 * Move the cursor one tab stop forward from the given position (default is current).
1981 * @param {number} x The position to move the cursor one tab stop forward.
1982 */
1983 Terminal.prototype.nextStop = function(x) {
1984 if (x == null) x = this.x;
1985 while (!this.tabs[++x] && x < this.cols);
1986 return x >= this.cols
1987 ? this.cols - 1
1988 : x < 0 ? 0 : x;
1989 };
1990
1991
1992 /**
1993 * Erase in the identified line everything from "x" to the end of the line (right).
1994 * @param {number} x The column from which to start erasing to the end of the line.
1995 * @param {number} y The line in which to operate.
1996 */
1997 Terminal.prototype.eraseRight = function(x, y) {
1998 var line = this.lines.get(this.ybase + y);
1999 if (!line) {
2000 return;
2001 }
2002 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2003 for (; x < this.cols; x++) {
2004 line[x] = ch;
2005 }
2006 this.updateRange(y);
2007 };
2008
2009
2010
2011 /**
2012 * Erase in the identified line everything from "x" to the start of the line (left).
2013 * @param {number} x The column from which to start erasing to the start of the line.
2014 * @param {number} y The line in which to operate.
2015 */
2016 Terminal.prototype.eraseLeft = function(x, y) {
2017 var line = this.lines.get(this.ybase + y);
2018 if (!line) {
2019 return;
2020 }
2021 var ch = [this.eraseAttr(), ' ', 1]; // xterm
2022 x++;
2023 while (x--) {
2024 line[x] = ch;
2025 }
2026 this.updateRange(y);
2027 };
2028
2029 /**
2030 * Clears the entire buffer, making the prompt line the new first line.
2031 */
2032 Terminal.prototype.clear = function() {
2033 if (this.ybase === 0 && this.y === 0) {
2034 // Don't clear if it's already clear
2035 return;
2036 }
2037 this.lines.set(0, this.lines.get(this.ybase + this.y));
2038 this.lines.length = 1;
2039 this.ydisp = 0;
2040 this.ybase = 0;
2041 this.y = 0;
2042 for (var i = 1; i < this.rows; i++) {
2043 this.lines.push(this.blankLine());
2044 }
2045 this.refresh(0, this.rows - 1);
2046 this.emit('scroll', this.ydisp);
2047 };
2048
2049 /**
2050 * Erase all content in the given line
2051 * @param {number} y The line to erase all of its contents.
2052 */
2053 Terminal.prototype.eraseLine = function(y) {
2054 this.eraseRight(0, y);
2055 };
2056
2057
2058 /**
2059 * Return the data array of a blank line
2060 * @param {number} cur First bunch of data for each "blank" character.
2061 */
2062 Terminal.prototype.blankLine = function(cur) {
2063 var attr = cur
2064 ? this.eraseAttr()
2065 : this.defAttr;
2066
2067 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
2068 , line = []
2069 , i = 0;
2070
2071 for (; i < this.cols; i++) {
2072 line[i] = ch;
2073 }
2074
2075 return line;
2076 };
2077
2078
2079 /**
2080 * If cur return the back color xterm feature attribute. Else return defAttr.
2081 * @param {object} cur
2082 */
2083 Terminal.prototype.ch = function(cur) {
2084 return cur
2085 ? [this.eraseAttr(), ' ', 1]
2086 : [this.defAttr, ' ', 1];
2087 };
2088
2089
2090 /**
2091 * Evaluate if the current erminal is the given argument.
2092 * @param {object} term The terminal to evaluate
2093 */
2094 Terminal.prototype.is = function(term) {
2095 var name = this.termName;
2096 return (name + '').indexOf(term) === 0;
2097 };
2098
2099
2100 /**
2101 * Emit the 'data' event and populate the given data.
2102 * @param {string} data The data to populate in the event.
2103 */
2104 Terminal.prototype.handler = function(data) {
2105 // Prevents all events to pty process if stdin is disabled
2106 if (this.options.disableStdin) {
2107 return;
2108 }
2109
2110 // Input is being sent to the terminal, the terminal should focus the prompt.
2111 if (this.ybase !== this.ydisp) {
2112 this.scrollToBottom();
2113 }
2114 this.emit('data', data);
2115 };
2116
2117
2118 /**
2119 * Emit the 'title' event and populate the given title.
2120 * @param {string} title The title to populate in the event.
2121 */
2122 Terminal.prototype.handleTitle = function(title) {
2123 /**
2124 * This event is emitted when the title of the terminal is changed
2125 * from inside the terminal. The parameter is the new title.
2126 *
2127 * @event title
2128 */
2129 this.emit('title', title);
2130 };
2131
2132
2133 /**
2134 * ESC
2135 */
2136
2137 /**
2138 * ESC D Index (IND is 0x84).
2139 */
2140 Terminal.prototype.index = function() {
2141 this.y++;
2142 if (this.y > this.scrollBottom) {
2143 this.y--;
2144 this.scroll();
2145 }
2146 // If the end of the line is hit, prevent this action from wrapping around to the next line.
2147 if (this.x >= this.cols) {
2148 this.x--;
2149 }
2150 };
2151
2152
2153 /**
2154 * ESC M Reverse Index (RI is 0x8d).
2155 *
2156 * Move the cursor up one row, inserting a new blank line if necessary.
2157 */
2158 Terminal.prototype.reverseIndex = function() {
2159 var j;
2160 if (this.y === this.scrollTop) {
2161 // possibly move the code below to term.reverseScroll();
2162 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
2163 // blankLine(true) is xterm/linux behavior
2164 this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
2165 this.lines.set(this.y + this.ybase, this.blankLine(true));
2166 this.updateRange(this.scrollTop);
2167 this.updateRange(this.scrollBottom);
2168 } else {
2169 this.y--;
2170 }
2171 };
2172
2173
2174 /**
2175 * ESC c Full Reset (RIS).
2176 */
2177 Terminal.prototype.reset = function() {
2178 this.options.rows = this.rows;
2179 this.options.cols = this.cols;
2180 var customKeydownHandler = this.customKeydownHandler;
2181 Terminal.call(this, this.options);
2182 this.customKeydownHandler = customKeydownHandler;
2183 this.refresh(0, this.rows - 1);
2184 this.viewport.syncScrollArea();
2185 };
2186
2187
2188 /**
2189 * ESC H Tab Set (HTS is 0x88).
2190 */
2191 Terminal.prototype.tabSet = function() {
2192 this.tabs[this.x] = true;
2193 };
2194
2195 /**
2196 * Helpers
2197 */
2198
2199 function on(el, type, handler, capture) {
2200 if (!Array.isArray(el)) {
2201 el = [el];
2202 }
2203 el.forEach(function (element) {
2204 element.addEventListener(type, handler, capture || false);
2205 });
2206 }
2207
2208 function off(el, type, handler, capture) {
2209 el.removeEventListener(type, handler, capture || false);
2210 }
2211
2212 function cancel(ev, force) {
2213 if (!this.cancelEvents && !force) {
2214 return;
2215 }
2216 ev.preventDefault();
2217 ev.stopPropagation();
2218 return false;
2219 }
2220
2221 function inherits(child, parent) {
2222 function f() {
2223 this.constructor = child;
2224 }
2225 f.prototype = parent.prototype;
2226 child.prototype = new f;
2227 }
2228
2229 function indexOf(obj, el) {
2230 var i = obj.length;
2231 while (i--) {
2232 if (obj[i] === el) return i;
2233 }
2234 return -1;
2235 }
2236
2237 function isThirdLevelShift(term, ev) {
2238 var thirdLevelKey =
2239 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
2240 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
2241
2242 if (ev.type == 'keypress') {
2243 return thirdLevelKey;
2244 }
2245
2246 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
2247 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
2248 }
2249
2250 // Expose to InputHandler (temporary)
2251 Terminal.prototype.matchColor = matchColor;
2252
2253 function matchColor(r1, g1, b1) {
2254 var hash = (r1 << 16) | (g1 << 8) | b1;
2255
2256 if (matchColor._cache[hash] != null) {
2257 return matchColor._cache[hash];
2258 }
2259
2260 var ldiff = Infinity
2261 , li = -1
2262 , i = 0
2263 , c
2264 , r2
2265 , g2
2266 , b2
2267 , diff;
2268
2269 for (; i < Terminal.vcolors.length; i++) {
2270 c = Terminal.vcolors[i];
2271 r2 = c[0];
2272 g2 = c[1];
2273 b2 = c[2];
2274
2275 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
2276
2277 if (diff === 0) {
2278 li = i;
2279 break;
2280 }
2281
2282 if (diff < ldiff) {
2283 ldiff = diff;
2284 li = i;
2285 }
2286 }
2287
2288 return matchColor._cache[hash] = li;
2289 }
2290
2291 matchColor._cache = {};
2292
2293 // http://stackoverflow.com/questions/1633828
2294 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
2295 return Math.pow(30 * (r1 - r2), 2)
2296 + Math.pow(59 * (g1 - g2), 2)
2297 + Math.pow(11 * (b1 - b2), 2);
2298 };
2299
2300 function each(obj, iter, con) {
2301 if (obj.forEach) return obj.forEach(iter, con);
2302 for (var i = 0; i < obj.length; i++) {
2303 iter.call(con, obj[i], i, obj);
2304 }
2305 }
2306
2307 function wasMondifierKeyOnlyEvent(ev) {
2308 return ev.keyCode === 16 || // Shift
2309 ev.keyCode === 17 || // Ctrl
2310 ev.keyCode === 18; // Alt
2311 }
2312
2313 function keys(obj) {
2314 if (Object.keys) return Object.keys(obj);
2315 var key, keys = [];
2316 for (key in obj) {
2317 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2318 keys.push(key);
2319 }
2320 }
2321 return keys;
2322 }
2323
2324 /**
2325 * Expose
2326 */
2327
2328 Terminal.EventEmitter = EventEmitter;
2329 Terminal.inherits = inherits;
2330
2331 /**
2332 * Adds an event listener to the terminal.
2333 *
2334 * @param {string} event The name of the event. TODO: Document all event types
2335 * @param {function} callback The function to call when the event is triggered.
2336 */
2337 Terminal.on = on;
2338 Terminal.off = off;
2339 Terminal.cancel = cancel;
2340
2341 module.exports = Terminal;