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