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