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