]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Add more CSI codes
[mirror_xterm.js.git] / src / xterm.js
1 /**
2 * xterm.js: xterm, in the browser
3 * Originally forked from (with the author's permission):
4 * Fabrice Bellard's javascript vt100 for jslinux:
5 * http://bellard.org/jslinux/
6 * Copyright (c) 2011 Fabrice Bellard
7 * The original design remains. The terminal itself
8 * has been extended to include xterm CSI codes, among
9 * other features.
10 * @license MIT
11 */
12
13 import { CompositionHelper } from './CompositionHelper.js';
14 import { EventEmitter } from './EventEmitter.js';
15 import { Viewport } from './Viewport.js';
16 import { rightClickHandler, pasteHandler, copyHandler } from './handlers/Clipboard.js';
17 import { CircularList } from './utils/CircularList.js';
18 import { C0 } from './EscapeSequences';
19 import { InputHandler } from './InputHandler';
20 import { Parser } from './Parser';
21 import { CharMeasure } from './utils/CharMeasure.js';
22 import * as Browser from './utils/Browser';
23 import * as Keyboard from './utils/Keyboard';
24 import { CHARSETS } from './Charsets';
25
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 */
36
37 // Let it work inside Node.js for automated testing purposes.
38 var document = (typeof window != 'undefined') ? window.document : null;
39
40 /**
41 * States
42 */
43 var normal = 0, escaped = 1, csi = 2, osc = 3, charset = 4, dcs = 5, ignore = 6;
44
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 */
50 var 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 */
56 var WRITE_BATCH_SIZE = 300;
57
58 /**
59 * The maximum number of refresh frames to skip when the write buffer is non-
60 * empty. Note that these frames may be intermingled with frames that are
61 * skipped via requestAnimationFrame's mechanism.
62 */
63 var MAX_REFRESH_FRAME_SKIP = 5;
64
65 /**
66 * Terminal
67 */
68
69 /**
70 * Creates a new `Terminal` object.
71 *
72 * @param {object} options An object containing a set of options, the available options are:
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)
76 *
77 * @public
78 * @class Xterm Xterm
79 * @alias module:xterm/src/xterm
80 */
81 function Terminal(options) {
82 var self = this;
83
84 if (!(this instanceof Terminal)) {
85 return new Terminal(arguments[0], arguments[1], arguments[2]);
86 }
87
88 self.browser = Browser;
89 self.cancel = Terminal.cancel;
90
91 EventEmitter.call(this);
92
93 if (typeof options === 'number') {
94 options = {
95 cols: arguments[0],
96 rows: arguments[1],
97 handler: arguments[2]
98 };
99 }
100
101 options = options || {};
102
103
104 Object.keys(Terminal.defaults).forEach(function(key) {
105 if (options[key] == null) {
106 options[key] = Terminal.options[key];
107
108 if (Terminal[key] !== Terminal.defaults[key]) {
109 options[key] = Terminal[key];
110 }
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];
138 this.geometry = [this.cols, this.rows];
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
165 /** A queue of the rows to be refreshed */
166 this.refreshRowsQueue = [];
167
168 this.cursorState = 0;
169 this.cursorHidden = false;
170 this.convertEol;
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
223 this.inputHandler = new InputHandler(this);
224 this.parser = new Parser(this.inputHandler, this);
225
226 // user input states
227 this.writeBuffer = [];
228 this.writeInProgress = false;
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;
241
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 */
249 this.lines = new CircularList(this.scrollback);
250 var i = this.rows;
251 while (i--) {
252 this.lines.push(this.blankLine());
253 }
254
255 this.tabs;
256 this.setupStops();
257
258 // Store if user went browsing history in scrollback
259 this.userScrolling = false;
260 }
261
262 inherits(Terminal, EventEmitter);
263
264 /**
265 * back_color_erase feature for xterm.
266 */
267 Terminal.prototype.eraseAttr = function() {
268 // if (this.is('screen')) return this.defAttr;
269 return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
270 };
271
272 /**
273 * Colors
274 */
275
276 // Colors 0-15
277 Terminal.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.
300 Terminal.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
330 Terminal._colors = Terminal.colors.slice();
331
332 Terminal.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 })();
349
350 /**
351 * Options
352 */
353
354 Terminal.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,
366 cancelEvents: false,
367 disableStdin: false
368 // programFeatures: false,
369 // focusKeys: false,
370 };
371
372 Terminal.options = {};
373
374 Terminal.focus = null;
375
376 each(keys(Terminal.defaults), function(key) {
377 Terminal[key] = Terminal.defaults[key];
378 Terminal.options[key] = Terminal.defaults[key];
379 });
380
381 /**
382 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
383 */
384 Terminal.prototype.focus = function() {
385 return this.textarea.focus();
386 };
387
388 /**
389 * Retrieves an option's value from the terminal.
390 * @param {string} key The option key.
391 */
392 Terminal.prototype.getOption = function(key, value) {
393 if (!(key in Terminal.defaults)) {
394 throw new Error('No option with key "' + key + '"');
395 }
396
397 if (typeof this.options[key] !== 'undefined') {
398 return this.options[key];
399 }
400
401 return this[key];
402 };
403
404 /**
405 * Sets an option on the terminal.
406 * @param {string} key The option key.
407 * @param {string} value The option value.
408 */
409 Terminal.prototype.setOption = function(key, value) {
410 if (!(key in Terminal.defaults)) {
411 throw new Error('No option with key "' + key + '"');
412 }
413 this[key] = value;
414 this.options[key] = value;
415 };
416
417 /**
418 * Binds the desired focus behavior on a given terminal object.
419 *
420 * @static
421 */
422 Terminal.bindFocus = function (term) {
423 on(term.textarea, 'focus', function (ev) {
424 if (term.sendFocus) {
425 term.send(C0.ESC + '[I');
426 }
427 term.element.classList.add('focus');
428 term.showCursor();
429 Terminal.focus = term;
430 term.emit('focus', {terminal: term});
431 });
432 };
433
434 /**
435 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
436 */
437 Terminal.prototype.blur = function() {
438 return this.textarea.blur();
439 };
440
441 /**
442 * Binds the desired blur behavior on a given terminal object.
443 *
444 * @static
445 */
446 Terminal.bindBlur = function (term) {
447 on(term.textarea, 'blur', function (ev) {
448 term.queueRefresh(term.y, term.y);
449 if (term.sendFocus) {
450 term.send(C0.ESC + '[O');
451 }
452 term.element.classList.remove('focus');
453 Terminal.focus = null;
454 term.emit('blur', {terminal: term});
455 });
456 };
457
458 /**
459 * Initialize default behavior
460 */
461 Terminal.prototype.initGlobal = function() {
462 var term = this;
463
464 Terminal.bindKeys(this);
465 Terminal.bindFocus(this);
466 Terminal.bindBlur(this);
467
468 // Bind clipboard functionality
469 on(this.element, 'copy', function (ev) {
470 copyHandler.call(this, ev, term);
471 });
472 on(this.textarea, 'paste', function (ev) {
473 pasteHandler.call(this, ev, term);
474 });
475 on(this.element, 'paste', function (ev) {
476 pasteHandler.call(this, ev, term);
477 });
478
479 function rightClickHandlerWrapper (ev) {
480 rightClickHandler.call(this, ev, term);
481 }
482
483 if (term.browser.isFirefox) {
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 }
492 };
493
494 /**
495 * Apply key handling to the terminal
496 */
497 Terminal.bindKeys = function(term) {
498 on(term.element, 'keydown', function(ev) {
499 if (document.activeElement != this) {
500 return;
501 }
502 term.keyDown(ev);
503 }, true);
504
505 on(term.element, 'keypress', function(ev) {
506 if (document.activeElement != this) {
507 return;
508 }
509 term.keyPress(ev);
510 }, true);
511
512 on(term.element, 'keyup', term.focus.bind(term));
513
514 on(term.textarea, 'keydown', function(ev) {
515 term.keyDown(ev);
516 }, true);
517
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);
523
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 };
529
530
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 */
536 Terminal.prototype.insertRow = function (row) {
537 if (typeof row != 'object') {
538 row = document.createElement('div');
539 }
540
541 this.rowContainer.appendChild(row);
542 this.children.push(row);
543
544 return row;
545 };
546
547 /**
548 * Opens the terminal within an element.
549 *
550 * @param {HTMLElement} parent The element to create the terminal within.
551 */
552 Terminal.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
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
614 this.charSizeStyleElement = document.createElement('style');
615 this.helperContainer.appendChild(this.charSizeStyleElement);
616
617 for (; i < this.rows; i++) {
618 this.insertRow();
619 }
620 this.parent.appendChild(this.element);
621
622 this.charMeasure = new CharMeasure(this.rowContainer);
623 this.charMeasure.on('charsizechanged', function () {
624 self.updateCharSizeCSS();
625 });
626 this.charMeasure.measure();
627
628 this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasure);
629
630 // Setup loop that draws to screen
631 this.queueRefresh(0, this.rows - 1);
632 this.refreshLoop();
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
641 on(this.element, 'click', function() {
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 });
649
650 // Listen for mouse events and translate
651 // them into terminal mouse protocols.
652 this.bindMouse();
653
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 }
659
660 /**
661 * This event is emitted when terminal has completed opening.
662 *
663 * @event open
664 */
665 this.emit('open');
666 };
667
668
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 */
674 Terminal.loadAddon = function(addon, callback) {
675 if (typeof exports === 'object' && typeof module === 'object') {
676 // CommonJS
677 return require('./addons/' + addon + '/' + addon);
678 } else if (typeof define == 'function') {
679 // RequireJS
680 return require(['./addons/' + addon + '/' + addon], callback);
681 } else {
682 console.error('Cannot load a module without a CommonJS or RequireJS environment.');
683 return false;
684 }
685 };
686
687 /**
688 * Updates the helper CSS class with any changes necessary after the terminal's
689 * character width has been changed.
690 */
691 Terminal.prototype.updateCharSizeCSS = function() {
692 this.charSizeStyleElement.textContent = '.xterm-wide-char{width:' + (this.charMeasure.width * 2) + 'px;}';
693 }
694
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 */
705 Terminal.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;
795 var data = C0.ESC + '[24';
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 }
805
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;
815 self.send(C0.ESC + '['
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 }
828
829 if (self.urxvtMouse) {
830 pos.x -= 32;
831 pos.y -= 32;
832 pos.x++;
833 pos.y++;
834 self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
835 return;
836 }
837
838 if (self.sgrMouse) {
839 pos.x -= 32;
840 pos.y -= 32;
841 self.send(C0.ESC + '[<'
842 + (((button & 3) === 3 ? button & ~3 : button) - 32)
843 + ';'
844 + pos.x
845 + ';'
846 + pos.y
847 + ((button & 3) === 3 ? 'm' : 'M'));
848 return;
849 }
850
851 var data = [];
852
853 encode(data, button);
854 encode(data, pos.x);
855 encode(data, pos.y);
856
857 self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, data));
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
882 if (self.browser.isMSIE) {
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 }
900
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 }
915
916 // increment to SP
917 button = (32 + (mod << 2)) + button;
918
919 return button;
920 }
921
922 // mouse coordinates measured in cols/rows
923 function getCoords(ev) {
924 var x, y, w, h, el;
925
926 // ignore browsers without pageX for now
927 if (ev.pageX == null) return;
928
929 x = ev.pageX;
930 y = ev.pageY;
931 el = self.element;
932
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 }
942
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'
965 };
966 }
967
968 on(el, 'mousedown', function(ev) {
969 if (!self.mouseEvents) return;
970
971 // send the button
972 sendButton(ev);
973
974 // ensure focus
975 self.focus();
976
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 }
984
985 // bind events
986 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
987
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);
995 });
996 }
997
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;
1018 self.viewport.onWheel(ev);
1019 return self.cancel(ev);
1020 });
1021 };
1022
1023 /**
1024 * Destroys the terminal.
1025 */
1026 Terminal.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 };
1037
1038
1039 /**
1040 * Flags used to render terminal text properly
1041 */
1042 Terminal.flags = {
1043 BOLD: 1,
1044 UNDERLINE: 2,
1045 BLINK: 4,
1046 INVERSE: 8,
1047 INVISIBLE: 16
1048 }
1049
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 */
1056 Terminal.prototype.queueRefresh = function(start, end) {
1057 this.refreshRowsQueue.push({ start: start, end: end });
1058 }
1059
1060 /**
1061 * Performs the refresh loop callback, calling refresh only if a refresh is
1062 * necessary before queueing up the next one.
1063 */
1064 Terminal.prototype.refreshLoop = function() {
1065 // Don't refresh if there were no row changes
1066 if (this.refreshRowsQueue.length > 0) {
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 }
1092 }
1093 }
1094 this.refreshRowsQueue = [];
1095 this.refresh(start, end);
1096 }
1097 }
1098 window.requestAnimationFrame(this.refreshLoop.bind(this));
1099 }
1100
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)
1121 */
1122 Terminal.prototype.refresh = function(start, end) {
1123 var self = this;
1124
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 }
1134
1135 width = this.cols;
1136 y = start;
1137
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 }
1142
1143 for (; y <= end; y++) {
1144 row = y + this.ydisp;
1145
1146 line = this.lines.get(row);
1147 out = '';
1148
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 }
1156
1157 attr = this.defAttr;
1158 i = 0;
1159
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;
1166
1167 if (i === x) data = -1;
1168
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 = [];
1182
1183 bg = data & 0x1ff;
1184 fg = (data >> 9) & 0x1ff;
1185 flags = data >> 18;
1186
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 }
1194
1195 if (flags & Terminal.flags.UNDERLINE) {
1196 classNames.push('xterm-underline');
1197 }
1198
1199 if (flags & Terminal.flags.BLINK) {
1200 classNames.push('xterm-blink');
1201 }
1202
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 }
1211
1212 if (flags & Terminal.flags.INVISIBLE) {
1213 classNames.push('xterm-hidden');
1214 }
1215
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 }
1231
1232 if (bg < 256) {
1233 classNames.push('xterm-bg-color-' + bg);
1234 }
1235
1236 if (fg < 256) {
1237 classNames.push('xterm-color-' + fg);
1238 }
1239
1240 out += '<span';
1241 if (classNames.length) {
1242 out += ' class="' + classNames.join(' ') + '"';
1243 }
1244 out += '>';
1245 }
1246 }
1247 }
1248
1249 if (ch_width === 2) {
1250 out += '<span class="xterm-wide-char">';
1251 }
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;';
1265 } else {
1266 out += ch;
1267 }
1268 break;
1269 }
1270 if (ch_width === 2) {
1271 out += '</span>';
1272 }
1273
1274 attr = data;
1275 }
1276
1277 if (attr !== this.defAttr) {
1278 out += '</span>';
1279 }
1280
1281 this.children[y].innerHTML = out;
1282 }
1283
1284 if (parent) {
1285 this.element.appendChild(this.rowContainer);
1286 }
1287
1288 this.emit('refresh', {element: this.element, start: start, end: end});
1289 };
1290
1291 /**
1292 * Display the cursor element
1293 */
1294 Terminal.prototype.showCursor = function() {
1295 if (!this.cursorState) {
1296 this.cursorState = 1;
1297 this.queueRefresh(this.y, this.y);
1298 }
1299 };
1300
1301 /**
1302 * Scroll the terminal down 1 row, creating a blank line.
1303 */
1304 Terminal.prototype.scroll = function() {
1305 var row;
1306
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
1316 this.ybase++;
1317
1318 // TODO: Why is this done twice?
1319 if (!this.userScrolling) {
1320 this.ydisp = this.ybase;
1321 }
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
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 }
1336
1337 if (this.scrollTop !== 0) {
1338 if (this.ybase !== 0) {
1339 this.ybase--;
1340 if (!this.userScrolling) {
1341 this.ydisp = this.ybase;
1342 }
1343 }
1344 this.lines.splice(this.ybase + this.scrollTop, 1);
1345 }
1346
1347 // this.maxRange();
1348 this.updateRange(this.scrollTop);
1349 this.updateRange(this.scrollBottom);
1350
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 */
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 */
1367 Terminal.prototype.scrollDisp = function(disp, suppressScrollEvent) {
1368 if (disp < 0) {
1369 this.userScrolling = true;
1370 } else if (disp + this.ydisp >= this.ybase) {
1371 this.userScrolling = false;
1372 }
1373
1374 this.ydisp += disp;
1375
1376 if (this.ydisp > this.ybase) {
1377 this.ydisp = this.ybase;
1378 } else if (this.ydisp < 0) {
1379 this.ydisp = 0;
1380 }
1381
1382 if (!suppressScrollEvent) {
1383 this.emit('scroll', this.ydisp);
1384 }
1385
1386 this.queueRefresh(0, this.rows - 1);
1387 };
1388
1389 /**
1390 * Scroll the display of the terminal by a number of pages.
1391 * @param {number} pageCount The number of pages to scroll (negative scrolls up).
1392 */
1393 Terminal.prototype.scrollPages = function(pageCount) {
1394 this.scrollDisp(pageCount * (this.rows - 1));
1395 }
1396
1397 /**
1398 * Scrolls the display of the terminal to the top.
1399 */
1400 Terminal.prototype.scrollToTop = function() {
1401 this.scrollDisp(-this.ydisp);
1402 }
1403
1404 /**
1405 * Scrolls the display of the terminal to the bottom.
1406 */
1407 Terminal.prototype.scrollToBottom = function() {
1408 this.scrollDisp(this.ybase - this.ydisp);
1409 }
1410
1411 /**
1412 * Writes text to the terminal.
1413 * @param {string} text The text to write to the terminal.
1414 */
1415 Terminal.prototype.write = function(data) {
1416 this.writeBuffer.push(data);
1417
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.
1421 if (!this.xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
1422 // XOFF - stop pty pipe
1423 // XON will be triggered by emulator before processing data chunk
1424 this.send(C0.DC3);
1425 this.xoffSentToCatchUp = true;
1426 }
1427
1428 if (!this.writeInProgress && this.writeBuffer.length > 0) {
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
1432 var self = this;
1433 setTimeout(function () {
1434 self.innerWrite();
1435 });
1436 }
1437 }
1438
1439 Terminal.prototype.innerWrite = function() {
1440 var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
1441 while (writeBatch.length > 0) {
1442 var data = writeBatch.shift();
1443 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
1444
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.
1447 if (this.xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
1448 this.send(C0.DC1);
1449 this.xoffSentToCatchUp = false;
1450 }
1451
1452 this.refreshStart = this.y;
1453 this.refreshEnd = this.y;
1454
1455 this.parser.parse(data);
1456
1457 this.updateRange(this.y);
1458 this.queueRefresh(this.refreshStart, this.refreshEnd);
1459 }
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 }
1469 };
1470
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 */
1475 Terminal.prototype.writeln = function(data) {
1476 this.write(data + '\r\n');
1477 };
1478
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 */
1487 Terminal.prototype.attachCustomKeydownHandler = function(customKeydownHandler) {
1488 this.customKeydownHandler = customKeydownHandler;
1489 }
1490
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 */
1497 Terminal.prototype.keyDown = function(ev) {
1498 if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
1499 return false;
1500 }
1501
1502 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
1503 if (this.ybase !== this.ydisp) {
1504 this.scrollToBottom();
1505 }
1506 return false;
1507 }
1508
1509 var self = this;
1510 var result = this.evaluateKeyEscapeSequence(ev);
1511
1512 if (result.key === C0.DC3) { // XOFF
1513 this.writeStopped = true;
1514 } else if (result.key === C0.DC1) { // XON
1515 this.writeStopped = false;
1516 }
1517
1518 if (result.scrollDisp) {
1519 this.scrollDisp(result.scrollDisp);
1520 return this.cancel(ev, true);
1521 }
1522
1523 if (isThirdLevelShift(this, ev)) {
1524 return true;
1525 }
1526
1527 if (result.cancel) {
1528 // The event is canceled at the end already, is this necessary?
1529 this.cancel(ev, true);
1530 }
1531
1532 if (!result.key) {
1533 return true;
1534 }
1535
1536 this.emit('keydown', ev);
1537 this.emit('key', result.key, ev);
1538 this.showCursor();
1539 this.handler(result.key);
1540
1541 return this.cancel(ev, true);
1542 };
1543
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 */
1551 Terminal.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) {
1563 case 8:
1564 // backspace
1565 if (ev.shiftKey) {
1566 result.key = C0.BS; // ^H
1567 break;
1568 }
1569 result.key = C0.DEL; // ^?
1570 break;
1571 case 9:
1572 // tab
1573 if (ev.shiftKey) {
1574 result.key = C0.ESC + '[Z';
1575 break;
1576 }
1577 result.key = C0.HT;
1578 result.cancel = true;
1579 break;
1580 case 13:
1581 // return/enter
1582 result.key = C0.CR;
1583 result.cancel = true;
1584 break;
1585 case 27:
1586 // escape
1587 result.key = C0.ESC;
1588 result.cancel = true;
1589 break;
1590 case 37:
1591 // left-arrow
1592 if (modifiers) {
1593 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
1594 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
1595 // http://unix.stackexchange.com/a/108106
1596 // macOS uses different escape sequences than linux
1597 if (result.key == C0.ESC + '[1;3D') {
1598 result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
1599 }
1600 } else if (this.applicationCursor) {
1601 result.key = C0.ESC + 'OD';
1602 } else {
1603 result.key = C0.ESC + '[D';
1604 }
1605 break;
1606 case 39:
1607 // right-arrow
1608 if (modifiers) {
1609 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
1610 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
1611 // http://unix.stackexchange.com/a/108106
1612 // macOS uses different escape sequences than linux
1613 if (result.key == C0.ESC + '[1;3C') {
1614 result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
1615 }
1616 } else if (this.applicationCursor) {
1617 result.key = C0.ESC + 'OC';
1618 } else {
1619 result.key = C0.ESC + '[C';
1620 }
1621 break;
1622 case 38:
1623 // up-arrow
1624 if (modifiers) {
1625 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
1626 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
1627 // http://unix.stackexchange.com/a/108106
1628 if (result.key == C0.ESC + '[1;3A') {
1629 result.key = C0.ESC + '[1;5A';
1630 }
1631 } else if (this.applicationCursor) {
1632 result.key = C0.ESC + 'OA';
1633 } else {
1634 result.key = C0.ESC + '[A';
1635 }
1636 break;
1637 case 40:
1638 // down-arrow
1639 if (modifiers) {
1640 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
1641 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
1642 // http://unix.stackexchange.com/a/108106
1643 if (result.key == C0.ESC + '[1;3B') {
1644 result.key = C0.ESC + '[1;5B';
1645 }
1646 } else if (this.applicationCursor) {
1647 result.key = C0.ESC + 'OB';
1648 } else {
1649 result.key = C0.ESC + '[B';
1650 }
1651 break;
1652 case 45:
1653 // insert
1654 if (!ev.shiftKey && !ev.ctrlKey) {
1655 // <Ctrl> or <Shift> + <Insert> are used to
1656 // copy-paste on some systems.
1657 result.key = C0.ESC + '[2~';
1658 }
1659 break;
1660 case 46:
1661 // delete
1662 if (modifiers) {
1663 result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
1664 } else {
1665 result.key = C0.ESC + '[3~';
1666 }
1667 break;
1668 case 36:
1669 // home
1670 if (modifiers)
1671 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
1672 else if (this.applicationCursor)
1673 result.key = C0.ESC + 'OH';
1674 else
1675 result.key = C0.ESC + '[H';
1676 break;
1677 case 35:
1678 // end
1679 if (modifiers)
1680 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
1681 else if (this.applicationCursor)
1682 result.key = C0.ESC + 'OF';
1683 else
1684 result.key = C0.ESC + '[F';
1685 break;
1686 case 33:
1687 // page up
1688 if (ev.shiftKey) {
1689 result.scrollDisp = -(this.rows - 1);
1690 } else {
1691 result.key = C0.ESC + '[5~';
1692 }
1693 break;
1694 case 34:
1695 // page down
1696 if (ev.shiftKey) {
1697 result.scrollDisp = this.rows - 1;
1698 } else {
1699 result.key = C0.ESC + '[6~';
1700 }
1701 break;
1702 case 112:
1703 // F1-F12
1704 if (modifiers) {
1705 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
1706 } else {
1707 result.key = C0.ESC + 'OP';
1708 }
1709 break;
1710 case 113:
1711 if (modifiers) {
1712 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
1713 } else {
1714 result.key = C0.ESC + 'OQ';
1715 }
1716 break;
1717 case 114:
1718 if (modifiers) {
1719 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
1720 } else {
1721 result.key = C0.ESC + 'OR';
1722 }
1723 break;
1724 case 115:
1725 if (modifiers) {
1726 result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
1727 } else {
1728 result.key = C0.ESC + 'OS';
1729 }
1730 break;
1731 case 116:
1732 if (modifiers) {
1733 result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
1734 } else {
1735 result.key = C0.ESC + '[15~';
1736 }
1737 break;
1738 case 117:
1739 if (modifiers) {
1740 result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
1741 } else {
1742 result.key = C0.ESC + '[17~';
1743 }
1744 break;
1745 case 118:
1746 if (modifiers) {
1747 result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
1748 } else {
1749 result.key = C0.ESC + '[18~';
1750 }
1751 break;
1752 case 119:
1753 if (modifiers) {
1754 result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
1755 } else {
1756 result.key = C0.ESC + '[19~';
1757 }
1758 break;
1759 case 120:
1760 if (modifiers) {
1761 result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
1762 } else {
1763 result.key = C0.ESC + '[20~';
1764 }
1765 break;
1766 case 121:
1767 if (modifiers) {
1768 result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
1769 } else {
1770 result.key = C0.ESC + '[21~';
1771 }
1772 break;
1773 case 122:
1774 if (modifiers) {
1775 result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
1776 } else {
1777 result.key = C0.ESC + '[23~';
1778 }
1779 break;
1780 case 123:
1781 if (modifiers) {
1782 result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
1783 } else {
1784 result.key = C0.ESC + '[24~';
1785 }
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) {
1802 // ^[ - Control Sequence Introducer (CSI)
1803 result.key = String.fromCharCode(27);
1804 } else if (ev.keyCode === 220) {
1805 // ^\ - String Terminator (ST)
1806 result.key = String.fromCharCode(28);
1807 } else if (ev.keyCode === 221) {
1808 // ^] - Operating System Command (OSC)
1809 result.key = String.fromCharCode(29);
1810 }
1811 } else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
1812 // On Mac this is a third level shift. Use <Esc> instead.
1813 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
1814 result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
1815 } else if (ev.keyCode === 192) {
1816 result.key = C0.ESC + '`';
1817 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
1818 result.key = C0.ESC + (ev.keyCode - 48);
1819 }
1820 }
1821 break;
1822 }
1823
1824 return result;
1825 };
1826
1827 /**
1828 * Set the G level of the terminal
1829 * @param g
1830 */
1831 Terminal.prototype.setgLevel = function(g) {
1832 this.glevel = g;
1833 this.charset = this.charsets[g];
1834 };
1835
1836 /**
1837 * Set the charset for the given G level of the terminal
1838 * @param g
1839 * @param charset
1840 */
1841 Terminal.prototype.setgCharset = function(g, charset) {
1842 this.charsets[g] = charset;
1843 if (this.glevel === g) {
1844 this.charset = charset;
1845 }
1846 };
1847
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 */
1854 Terminal.prototype.keyPress = function(ev) {
1855 var key;
1856
1857 this.cancel(ev);
1858
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 }
1868
1869 if (!key || (
1870 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
1871 )) {
1872 return false;
1873 }
1874
1875 key = String.fromCharCode(key);
1876
1877 this.emit('keypress', key, ev);
1878 this.emit('key', key, ev);
1879 this.showCursor();
1880 this.handler(key);
1881
1882 return false;
1883 };
1884
1885 /**
1886 * Send data for handling to the terminal
1887 * @param {string} data
1888 */
1889 Terminal.prototype.send = function(data) {
1890 var self = this;
1891
1892 if (!this.queue) {
1893 setTimeout(function() {
1894 self.handler(self.queue);
1895 self.queue = '';
1896 }, 1);
1897 }
1898
1899 this.queue += data;
1900 };
1901
1902 /**
1903 * Ring the bell.
1904 * Note: We could do sweet things with webaudio here
1905 */
1906 Terminal.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 };
1915
1916 /**
1917 * Log the current state to the console.
1918 */
1919 Terminal.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 };
1925
1926 /**
1927 * Log the current state as error to the console.
1928 */
1929 Terminal.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 };
1935
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 */
1942 Terminal.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--) {
1963 while (this.lines.get(i).length < x) {
1964 this.lines.get(i).push(ch);
1965 }
1966 }
1967 } else { // (j > x)
1968 i = this.lines.length;
1969 while (i--) {
1970 while (this.lines.get(i).length > x) {
1971 this.lines.get(i).pop();
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;
2025
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 }
2033
2034 if (this.x >= x) {
2035 this.x = x - 1;
2036 }
2037
2038 this.scrollTop = 0;
2039 this.scrollBottom = y - 1;
2040
2041 this.charMeasure.measure();
2042
2043 this.queueRefresh(0, this.rows - 1);
2044
2045 this.normal = null;
2046
2047 this.geometry = [this.cols, this.rows];
2048 this.emit('resize', {terminal: this, cols: x, rows: y});
2049 };
2050
2051 /**
2052 * Updates the range of rows to refresh
2053 * @param {number} y The number of rows to refresh next.
2054 */
2055 Terminal.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 };
2065
2066 /**
2067 * Set the range of refreshing to the maximum value
2068 */
2069 Terminal.prototype.maxRange = function() {
2070 this.refreshStart = 0;
2071 this.refreshEnd = this.rows - 1;
2072 };
2073
2074
2075
2076 /**
2077 * Setup the tab stops.
2078 * @param {number} i
2079 */
2080 Terminal.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 }
2089
2090 for (; i < this.cols; i += 8) {
2091 this.tabs[i] = true;
2092 }
2093 };
2094
2095
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 */
2100 Terminal.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 };
2107
2108
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 */
2113 Terminal.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 };
2120
2121
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 */
2127 Terminal.prototype.eraseRight = function(x, y) {
2128 var line = this.lines.get(this.ybase + y)
2129 , ch = [this.eraseAttr(), ' ', 1]; // xterm
2130
2131
2132 for (; x < this.cols; x++) {
2133 line[x] = ch;
2134 }
2135
2136 this.updateRange(y);
2137 };
2138
2139
2140
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 */
2146 Terminal.prototype.eraseLeft = function(x, y) {
2147 var line = this.lines.get(this.ybase + y)
2148 , ch = [this.eraseAttr(), ' ', 1]; // xterm
2149
2150 x++;
2151 while (x--) line[x] = ch;
2152
2153 this.updateRange(y);
2154 };
2155
2156 /**
2157 * Clears the entire buffer, making the prompt line the new first line.
2158 */
2159 Terminal.prototype.clear = function() {
2160 if (this.ybase === 0 && this.y === 0) {
2161 // Don't clear if it's already clear
2162 return;
2163 }
2164 this.lines.set(0, this.lines.get(this.ybase + this.y));
2165 this.lines.length = 1;
2166 this.ydisp = 0;
2167 this.ybase = 0;
2168 this.y = 0;
2169 for (var i = 1; i < this.rows; i++) {
2170 this.lines.push(this.blankLine());
2171 }
2172 this.queueRefresh(0, this.rows - 1);
2173 this.emit('scroll', this.ydisp);
2174 };
2175
2176 /**
2177 * Erase all content in the given line
2178 * @param {number} y The line to erase all of its contents.
2179 */
2180 Terminal.prototype.eraseLine = function(y) {
2181 this.eraseRight(0, y);
2182 };
2183
2184
2185 /**
2186 * Return the data array of a blank line
2187 * @param {number} cur First bunch of data for each "blank" character.
2188 */
2189 Terminal.prototype.blankLine = function(cur) {
2190 var attr = cur
2191 ? this.eraseAttr()
2192 : this.defAttr;
2193
2194 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
2195 , line = []
2196 , i = 0;
2197
2198 for (; i < this.cols; i++) {
2199 line[i] = ch;
2200 }
2201
2202 return line;
2203 };
2204
2205
2206 /**
2207 * If cur return the back color xterm feature attribute. Else return defAttr.
2208 * @param {object} cur
2209 */
2210 Terminal.prototype.ch = function(cur) {
2211 return cur
2212 ? [this.eraseAttr(), ' ', 1]
2213 : [this.defAttr, ' ', 1];
2214 };
2215
2216
2217 /**
2218 * Evaluate if the current erminal is the given argument.
2219 * @param {object} term The terminal to evaluate
2220 */
2221 Terminal.prototype.is = function(term) {
2222 var name = this.termName;
2223 return (name + '').indexOf(term) === 0;
2224 };
2225
2226
2227 /**
2228 * Emit the 'data' event and populate the given data.
2229 * @param {string} data The data to populate in the event.
2230 */
2231 Terminal.prototype.handler = function(data) {
2232 // Prevents all events to pty process if stdin is disabled
2233 if (this.options.disableStdin) {
2234 return;
2235 }
2236
2237 // Input is being sent to the terminal, the terminal should focus the prompt.
2238 if (this.ybase !== this.ydisp) {
2239 this.scrollToBottom();
2240 }
2241 this.emit('data', data);
2242 };
2243
2244
2245 /**
2246 * Emit the 'title' event and populate the given title.
2247 * @param {string} title The title to populate in the event.
2248 */
2249 Terminal.prototype.handleTitle = function(title) {
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 */
2256 this.emit('title', title);
2257 };
2258
2259
2260 /**
2261 * ESC
2262 */
2263
2264 /**
2265 * ESC D Index (IND is 0x84).
2266 */
2267 Terminal.prototype.index = function() {
2268 this.y++;
2269 if (this.y > this.scrollBottom) {
2270 this.y--;
2271 this.scroll();
2272 }
2273 };
2274
2275
2276 /**
2277 * ESC M Reverse Index (RI is 0x8d).
2278 *
2279 * Move the cursor up one row, inserting a new blank line if necessary.
2280 */
2281 Terminal.prototype.reverseIndex = function() {
2282 var j;
2283 if (this.y === this.scrollTop) {
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
2287 this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
2288 this.lines.set(this.y + this.ybase, this.blankLine(true));
2289 this.updateRange(this.scrollTop);
2290 this.updateRange(this.scrollBottom);
2291 } else {
2292 this.y--;
2293 }
2294 };
2295
2296
2297 /**
2298 * ESC c Full Reset (RIS).
2299 */
2300 Terminal.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;
2306 this.queueRefresh(0, this.rows - 1);
2307 this.viewport.syncScrollArea();
2308 };
2309
2310
2311 /**
2312 * ESC H Tab Set (HTS is 0x88).
2313 */
2314 Terminal.prototype.tabSet = function() {
2315 this.tabs[this.x] = true;
2316 };
2317
2318
2319 /**
2320 * CSI
2321 */
2322
2323
2324 /**
2325 * Additions
2326 */
2327
2328
2329 /**
2330 * CSI Pm l Reset Mode (RM).
2331 * Ps = 2 -> Keyboard Action Mode (AM).
2332 * Ps = 4 -> Replace Mode (IRM).
2333 * Ps = 1 2 -> Send/receive (SRM).
2334 * Ps = 2 0 -> Normal Linefeed (LNM).
2335 * CSI ? Pm l
2336 * DEC Private Mode Reset (DECRST).
2337 * Ps = 1 -> Normal Cursor Keys (DECCKM).
2338 * Ps = 2 -> Designate VT52 mode (DECANM).
2339 * Ps = 3 -> 80 Column Mode (DECCOLM).
2340 * Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
2341 * Ps = 5 -> Normal Video (DECSCNM).
2342 * Ps = 6 -> Normal Cursor Mode (DECOM).
2343 * Ps = 7 -> No Wraparound Mode (DECAWM).
2344 * Ps = 8 -> No Auto-repeat Keys (DECARM).
2345 * Ps = 9 -> Don't send Mouse X & Y on button press.
2346 * Ps = 1 0 -> Hide toolbar (rxvt).
2347 * Ps = 1 2 -> Stop Blinking Cursor (att610).
2348 * Ps = 1 8 -> Don't print form feed (DECPFF).
2349 * Ps = 1 9 -> Limit print to scrolling region (DECPEX).
2350 * Ps = 2 5 -> Hide Cursor (DECTCEM).
2351 * Ps = 3 0 -> Don't show scrollbar (rxvt).
2352 * Ps = 3 5 -> Disable font-shifting functions (rxvt).
2353 * Ps = 4 0 -> Disallow 80 -> 132 Mode.
2354 * Ps = 4 1 -> No more(1) fix (see curses resource).
2355 * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
2356 * NRCM).
2357 * Ps = 4 4 -> Turn Off Margin Bell.
2358 * Ps = 4 5 -> No Reverse-wraparound Mode.
2359 * Ps = 4 6 -> Stop Logging. (This is normally disabled by a
2360 * compile-time option).
2361 * Ps = 4 7 -> Use Normal Screen Buffer.
2362 * Ps = 6 6 -> Numeric keypad (DECNKM).
2363 * Ps = 6 7 -> Backarrow key sends delete (DECBKM).
2364 * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
2365 * release. See the section Mouse Tracking.
2366 * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
2367 * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
2368 * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
2369 * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
2370 * Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
2371 * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
2372 * (rxvt).
2373 * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
2374 * Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
2375 * the eightBitInput resource).
2376 * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
2377 * Lock keys. (This disables the numLock resource).
2378 * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
2379 * (This disables the metaSendsEscape resource).
2380 * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
2381 * Delete key.
2382 * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
2383 * (This disables the altSendsEscape resource).
2384 * Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
2385 * (This disables the keepSelection resource).
2386 * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
2387 * the selectToClipboard resource).
2388 * Ps = 1 0 4 2 -> Disable Urgency window manager hint when
2389 * Control-G is received. (This disables the bellIsUrgent
2390 * resource).
2391 * Ps = 1 0 4 3 -> Disable raising of the window when Control-
2392 * G is received. (This disables the popOnBell resource).
2393 * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
2394 * first if in the Alternate Screen. (This may be disabled by
2395 * the titeInhibit resource).
2396 * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
2397 * disabled by the titeInhibit resource).
2398 * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
2399 * as in DECRC. (This may be disabled by the titeInhibit
2400 * resource). This combines the effects of the 1 0 4 7 and 1 0
2401 * 4 8 modes. Use this with terminfo-based applications rather
2402 * than the 4 7 mode.
2403 * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
2404 * Ps = 1 0 5 1 -> Reset Sun function-key mode.
2405 * Ps = 1 0 5 2 -> Reset HP function-key mode.
2406 * Ps = 1 0 5 3 -> Reset SCO function-key mode.
2407 * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
2408 * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
2409 * Ps = 2 0 0 4 -> Reset bracketed paste mode.
2410 */
2411 Terminal.prototype.resetMode = function(params) {
2412 if (typeof params === 'object') {
2413 var l = params.length
2414 , i = 0;
2415
2416 for (; i < l; i++) {
2417 this.resetMode(params[i]);
2418 }
2419
2420 return;
2421 }
2422
2423 if (!this.prefix) {
2424 switch (params) {
2425 case 4:
2426 this.insertMode = false;
2427 break;
2428 case 20:
2429 //this.convertEol = false;
2430 break;
2431 }
2432 } else if (this.prefix === '?') {
2433 switch (params) {
2434 case 1:
2435 this.applicationCursor = false;
2436 break;
2437 case 3:
2438 if (this.cols === 132 && this.savedCols) {
2439 this.resize(this.savedCols, this.rows);
2440 }
2441 delete this.savedCols;
2442 break;
2443 case 6:
2444 this.originMode = false;
2445 break;
2446 case 7:
2447 this.wraparoundMode = false;
2448 break;
2449 case 12:
2450 // this.cursorBlink = false;
2451 break;
2452 case 66:
2453 this.log('Switching back to normal keypad.');
2454 this.applicationKeypad = false;
2455 this.viewport.syncScrollArea();
2456 break;
2457 case 9: // X10 Mouse
2458 case 1000: // vt200 mouse
2459 case 1002: // button event mouse
2460 case 1003: // any event mouse
2461 this.x10Mouse = false;
2462 this.vt200Mouse = false;
2463 this.normalMouse = false;
2464 this.mouseEvents = false;
2465 this.element.style.cursor = '';
2466 break;
2467 case 1004: // send focusin/focusout events
2468 this.sendFocus = false;
2469 break;
2470 case 1005: // utf8 ext mode mouse
2471 this.utfMouse = false;
2472 break;
2473 case 1006: // sgr ext mode mouse
2474 this.sgrMouse = false;
2475 break;
2476 case 1015: // urxvt ext mode mouse
2477 this.urxvtMouse = false;
2478 break;
2479 case 25: // hide cursor
2480 this.cursorHidden = true;
2481 break;
2482 case 1049: // alt screen buffer cursor
2483 ; // FALL-THROUGH
2484 case 47: // normal screen buffer
2485 case 1047: // normal screen buffer - clearing it first
2486 if (this.normal) {
2487 this.lines = this.normal.lines;
2488 this.ybase = this.normal.ybase;
2489 this.ydisp = this.normal.ydisp;
2490 this.x = this.normal.x;
2491 this.y = this.normal.y;
2492 this.scrollTop = this.normal.scrollTop;
2493 this.scrollBottom = this.normal.scrollBottom;
2494 this.tabs = this.normal.tabs;
2495 this.normal = null;
2496 // if (params === 1049) {
2497 // this.x = this.savedX;
2498 // this.y = this.savedY;
2499 // }
2500 this.queueRefresh(0, this.rows - 1);
2501 this.viewport.syncScrollArea();
2502 this.showCursor();
2503 }
2504 break;
2505 }
2506 }
2507 };
2508
2509
2510 /**
2511 * CSI Ps ; Ps r
2512 * Set Scrolling Region [top;bottom] (default = full size of win-
2513 * dow) (DECSTBM).
2514 * CSI ? Pm r
2515 */
2516 Terminal.prototype.setScrollRegion = function(params) {
2517 if (this.prefix) return;
2518 this.scrollTop = (params[0] || 1) - 1;
2519 this.scrollBottom = (params[1] || this.rows) - 1;
2520 this.x = 0;
2521 this.y = 0;
2522 };
2523
2524
2525 /**
2526 * CSI s
2527 * Save cursor (ANSI.SYS).
2528 */
2529 Terminal.prototype.saveCursor = function(params) {
2530 this.savedX = this.x;
2531 this.savedY = this.y;
2532 };
2533
2534
2535 /**
2536 * CSI u
2537 * Restore cursor (ANSI.SYS).
2538 */
2539 Terminal.prototype.restoreCursor = function(params) {
2540 this.x = this.savedX || 0;
2541 this.y = this.savedY || 0;
2542 };
2543
2544
2545 /**
2546 * Lesser Used
2547 */
2548
2549 /**
2550 * CSI Ps I
2551 * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
2552 */
2553 Terminal.prototype.cursorForwardTab = function(params) {
2554 var param = params[0] || 1;
2555 while (param--) {
2556 this.x = this.nextStop();
2557 }
2558 };
2559
2560
2561 /**
2562 * CSI Ps S Scroll up Ps lines (default = 1) (SU).
2563 */
2564 Terminal.prototype.scrollUp = function(params) {
2565 var param = params[0] || 1;
2566 while (param--) {
2567 this.lines.splice(this.ybase + this.scrollTop, 1);
2568 this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine());
2569 }
2570 // this.maxRange();
2571 this.updateRange(this.scrollTop);
2572 this.updateRange(this.scrollBottom);
2573 };
2574
2575
2576 /**
2577 * CSI Ps T Scroll down Ps lines (default = 1) (SD).
2578 */
2579 Terminal.prototype.scrollDown = function(params) {
2580 var param = params[0] || 1;
2581 while (param--) {
2582 this.lines.splice(this.ybase + this.scrollBottom, 1);
2583 this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine());
2584 }
2585 // this.maxRange();
2586 this.updateRange(this.scrollTop);
2587 this.updateRange(this.scrollBottom);
2588 };
2589
2590
2591 /**
2592 * CSI Ps ; Ps ; Ps ; Ps ; Ps T
2593 * Initiate highlight mouse tracking. Parameters are
2594 * [func;startx;starty;firstrow;lastrow]. See the section Mouse
2595 * Tracking.
2596 */
2597 Terminal.prototype.initMouseTracking = function(params) {
2598 // Relevant: DECSET 1001
2599 };
2600
2601
2602 /**
2603 * CSI > Ps; Ps T
2604 * Reset one or more features of the title modes to the default
2605 * value. Normally, "reset" disables the feature. It is possi-
2606 * ble to disable the ability to reset features by compiling a
2607 * different default for the title modes into xterm.
2608 * Ps = 0 -> Do not set window/icon labels using hexadecimal.
2609 * Ps = 1 -> Do not query window/icon labels using hexadeci-
2610 * mal.
2611 * Ps = 2 -> Do not set window/icon labels using UTF-8.
2612 * Ps = 3 -> Do not query window/icon labels using UTF-8.
2613 * (See discussion of "Title Modes").
2614 */
2615 Terminal.prototype.resetTitleModes = function(params) {
2616 ;
2617 };
2618
2619
2620 /**
2621 * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
2622 */
2623 Terminal.prototype.cursorBackwardTab = function(params) {
2624 var param = params[0] || 1;
2625 while (param--) {
2626 this.x = this.prevStop();
2627 }
2628 };
2629
2630
2631 /**
2632 * CSI Ps b Repeat the preceding graphic character Ps times (REP).
2633 */
2634 Terminal.prototype.repeatPrecedingCharacter = function(params) {
2635 var param = params[0] || 1
2636 , line = this.lines.get(this.ybase + this.y)
2637 , ch = line[this.x - 1] || [this.defAttr, ' ', 1];
2638
2639 while (param--) line[this.x++] = ch;
2640 };
2641
2642
2643 /**
2644 * CSI Ps g Tab Clear (TBC).
2645 * Ps = 0 -> Clear Current Column (default).
2646 * Ps = 3 -> Clear All.
2647 * Potentially:
2648 * Ps = 2 -> Clear Stops on Line.
2649 * http://vt100.net/annarbor/aaa-ug/section6.html
2650 */
2651 Terminal.prototype.tabClear = function(params) {
2652 var param = params[0];
2653 if (param <= 0) {
2654 delete this.tabs[this.x];
2655 } else if (param === 3) {
2656 this.tabs = {};
2657 }
2658 };
2659
2660
2661 /**
2662 * CSI Pm i Media Copy (MC).
2663 * Ps = 0 -> Print screen (default).
2664 * Ps = 4 -> Turn off printer controller mode.
2665 * Ps = 5 -> Turn on printer controller mode.
2666 * CSI ? Pm i
2667 * Media Copy (MC, DEC-specific).
2668 * Ps = 1 -> Print line containing cursor.
2669 * Ps = 4 -> Turn off autoprint mode.
2670 * Ps = 5 -> Turn on autoprint mode.
2671 * Ps = 1 0 -> Print composed display, ignores DECPEX.
2672 * Ps = 1 1 -> Print all pages.
2673 */
2674 Terminal.prototype.mediaCopy = function(params) {
2675 ;
2676 };
2677
2678
2679 /**
2680 * CSI > Ps; Ps m
2681 * Set or reset resource-values used by xterm to decide whether
2682 * to construct escape sequences holding information about the
2683 * modifiers pressed with a given key. The first parameter iden-
2684 * tifies the resource to set/reset. The second parameter is the
2685 * value to assign to the resource. If the second parameter is
2686 * omitted, the resource is reset to its initial value.
2687 * Ps = 1 -> modifyCursorKeys.
2688 * Ps = 2 -> modifyFunctionKeys.
2689 * Ps = 4 -> modifyOtherKeys.
2690 * If no parameters are given, all resources are reset to their
2691 * initial values.
2692 */
2693 Terminal.prototype.setResources = function(params) {
2694 ;
2695 };
2696
2697
2698 /**
2699 * CSI > Ps n
2700 * Disable modifiers which may be enabled via the CSI > Ps; Ps m
2701 * sequence. This corresponds to a resource value of "-1", which
2702 * cannot be set with the other sequence. The parameter identi-
2703 * fies the resource to be disabled:
2704 * Ps = 1 -> modifyCursorKeys.
2705 * Ps = 2 -> modifyFunctionKeys.
2706 * Ps = 4 -> modifyOtherKeys.
2707 * If the parameter is omitted, modifyFunctionKeys is disabled.
2708 * When modifyFunctionKeys is disabled, xterm uses the modifier
2709 * keys to make an extended sequence of functions rather than
2710 * adding a parameter to each function key to denote the modi-
2711 * fiers.
2712 */
2713 Terminal.prototype.disableModifiers = function(params) {
2714 ;
2715 };
2716
2717
2718 /**
2719 * CSI > Ps p
2720 * Set resource value pointerMode. This is used by xterm to
2721 * decide whether to hide the pointer cursor as the user types.
2722 * Valid values for the parameter:
2723 * Ps = 0 -> never hide the pointer.
2724 * Ps = 1 -> hide if the mouse tracking mode is not enabled.
2725 * Ps = 2 -> always hide the pointer. If no parameter is
2726 * given, xterm uses the default, which is 1 .
2727 */
2728 Terminal.prototype.setPointerMode = function(params) {
2729 ;
2730 };
2731
2732
2733 /**
2734 * CSI ! p Soft terminal reset (DECSTR).
2735 * http://vt100.net/docs/vt220-rm/table4-10.html
2736 */
2737 Terminal.prototype.softReset = function(params) {
2738 this.cursorHidden = false;
2739 this.insertMode = false;
2740 this.originMode = false;
2741 this.wraparoundMode = false; // autowrap
2742 this.applicationKeypad = false; // ?
2743 this.viewport.syncScrollArea();
2744 this.applicationCursor = false;
2745 this.scrollTop = 0;
2746 this.scrollBottom = this.rows - 1;
2747 this.curAttr = this.defAttr;
2748 this.x = this.y = 0; // ?
2749 this.charset = null;
2750 this.glevel = 0; // ??
2751 this.charsets = [null]; // ??
2752 };
2753
2754
2755 /**
2756 * CSI Ps$ p
2757 * Request ANSI mode (DECRQM). For VT300 and up, reply is
2758 * CSI Ps; Pm$ y
2759 * where Ps is the mode number as in RM, and Pm is the mode
2760 * value:
2761 * 0 - not recognized
2762 * 1 - set
2763 * 2 - reset
2764 * 3 - permanently set
2765 * 4 - permanently reset
2766 */
2767 Terminal.prototype.requestAnsiMode = function(params) {
2768 ;
2769 };
2770
2771
2772 /**
2773 * CSI ? Ps$ p
2774 * Request DEC private mode (DECRQM). For VT300 and up, reply is
2775 * CSI ? Ps; Pm$ p
2776 * where Ps is the mode number as in DECSET, Pm is the mode value
2777 * as in the ANSI DECRQM.
2778 */
2779 Terminal.prototype.requestPrivateMode = function(params) {
2780 ;
2781 };
2782
2783
2784 /**
2785 * CSI Ps ; Ps " p
2786 * Set conformance level (DECSCL). Valid values for the first
2787 * parameter:
2788 * Ps = 6 1 -> VT100.
2789 * Ps = 6 2 -> VT200.
2790 * Ps = 6 3 -> VT300.
2791 * Valid values for the second parameter:
2792 * Ps = 0 -> 8-bit controls.
2793 * Ps = 1 -> 7-bit controls (always set for VT100).
2794 * Ps = 2 -> 8-bit controls.
2795 */
2796 Terminal.prototype.setConformanceLevel = function(params) {
2797 ;
2798 };
2799
2800
2801 /**
2802 * CSI Ps q Load LEDs (DECLL).
2803 * Ps = 0 -> Clear all LEDS (default).
2804 * Ps = 1 -> Light Num Lock.
2805 * Ps = 2 -> Light Caps Lock.
2806 * Ps = 3 -> Light Scroll Lock.
2807 * Ps = 2 1 -> Extinguish Num Lock.
2808 * Ps = 2 2 -> Extinguish Caps Lock.
2809 * Ps = 2 3 -> Extinguish Scroll Lock.
2810 */
2811 Terminal.prototype.loadLEDs = function(params) {
2812 ;
2813 };
2814
2815
2816 /**
2817 * CSI Ps SP q
2818 * Set cursor style (DECSCUSR, VT520).
2819 * Ps = 0 -> blinking block.
2820 * Ps = 1 -> blinking block (default).
2821 * Ps = 2 -> steady block.
2822 * Ps = 3 -> blinking underline.
2823 * Ps = 4 -> steady underline.
2824 */
2825 Terminal.prototype.setCursorStyle = function(params) {
2826 ;
2827 };
2828
2829
2830 /**
2831 * CSI Ps " q
2832 * Select character protection attribute (DECSCA). Valid values
2833 * for the parameter:
2834 * Ps = 0 -> DECSED and DECSEL can erase (default).
2835 * Ps = 1 -> DECSED and DECSEL cannot erase.
2836 * Ps = 2 -> DECSED and DECSEL can erase.
2837 */
2838 Terminal.prototype.setCharProtectionAttr = function(params) {
2839 ;
2840 };
2841
2842
2843 /**
2844 * CSI ? Pm r
2845 * Restore DEC Private Mode Values. The value of Ps previously
2846 * saved is restored. Ps values are the same as for DECSET.
2847 */
2848 Terminal.prototype.restorePrivateValues = function(params) {
2849 ;
2850 };
2851
2852
2853 /**
2854 * CSI Pt; Pl; Pb; Pr; Ps$ r
2855 * Change Attributes in Rectangular Area (DECCARA), VT400 and up.
2856 * Pt; Pl; Pb; Pr denotes the rectangle.
2857 * Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7.
2858 * NOTE: xterm doesn't enable this code by default.
2859 */
2860 Terminal.prototype.setAttrInRectangle = function(params) {
2861 var t = params[0]
2862 , l = params[1]
2863 , b = params[2]
2864 , r = params[3]
2865 , attr = params[4];
2866
2867 var line
2868 , i;
2869
2870 for (; t < b + 1; t++) {
2871 line = this.lines.get(this.ybase + t);
2872 for (i = l; i < r; i++) {
2873 line[i] = [attr, line[i][1]];
2874 }
2875 }
2876
2877 // this.maxRange();
2878 this.updateRange(params[0]);
2879 this.updateRange(params[2]);
2880 };
2881
2882
2883 /**
2884 * CSI Pc; Pt; Pl; Pb; Pr$ x
2885 * Fill Rectangular Area (DECFRA), VT420 and up.
2886 * Pc is the character to use.
2887 * Pt; Pl; Pb; Pr denotes the rectangle.
2888 * NOTE: xterm doesn't enable this code by default.
2889 */
2890 Terminal.prototype.fillRectangle = function(params) {
2891 var ch = params[0]
2892 , t = params[1]
2893 , l = params[2]
2894 , b = params[3]
2895 , r = params[4];
2896
2897 var line
2898 , i;
2899
2900 for (; t < b + 1; t++) {
2901 line = this.lines.get(this.ybase + t);
2902 for (i = l; i < r; i++) {
2903 line[i] = [line[i][0], String.fromCharCode(ch)];
2904 }
2905 }
2906
2907 // this.maxRange();
2908 this.updateRange(params[1]);
2909 this.updateRange(params[3]);
2910 };
2911
2912
2913 /**
2914 * CSI Ps ; Pu ' z
2915 * Enable Locator Reporting (DECELR).
2916 * Valid values for the first parameter:
2917 * Ps = 0 -> Locator disabled (default).
2918 * Ps = 1 -> Locator enabled.
2919 * Ps = 2 -> Locator enabled for one report, then disabled.
2920 * The second parameter specifies the coordinate unit for locator
2921 * reports.
2922 * Valid values for the second parameter:
2923 * Pu = 0 <- or omitted -> default to character cells.
2924 * Pu = 1 <- device physical pixels.
2925 * Pu = 2 <- character cells.
2926 */
2927 Terminal.prototype.enableLocatorReporting = function(params) {
2928 var val = params[0] > 0;
2929 //this.mouseEvents = val;
2930 //this.decLocator = val;
2931 };
2932
2933
2934 /**
2935 * CSI Pt; Pl; Pb; Pr$ z
2936 * Erase Rectangular Area (DECERA), VT400 and up.
2937 * Pt; Pl; Pb; Pr denotes the rectangle.
2938 * NOTE: xterm doesn't enable this code by default.
2939 */
2940 Terminal.prototype.eraseRectangle = function(params) {
2941 var t = params[0]
2942 , l = params[1]
2943 , b = params[2]
2944 , r = params[3];
2945
2946 var line
2947 , i
2948 , ch;
2949
2950 ch = [this.eraseAttr(), ' ', 1]; // xterm?
2951
2952 for (; t < b + 1; t++) {
2953 line = this.lines.get(this.ybase + t);
2954 for (i = l; i < r; i++) {
2955 line[i] = ch;
2956 }
2957 }
2958
2959 // this.maxRange();
2960 this.updateRange(params[0]);
2961 this.updateRange(params[2]);
2962 };
2963
2964
2965 /**
2966 * CSI P m SP }
2967 * Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
2968 * NOTE: xterm doesn't enable this code by default.
2969 */
2970 Terminal.prototype.insertColumns = function() {
2971 var param = params[0]
2972 , l = this.ybase + this.rows
2973 , ch = [this.eraseAttr(), ' ', 1] // xterm?
2974 , i;
2975
2976 while (param--) {
2977 for (i = this.ybase; i < l; i++) {
2978 this.lines.get(i).splice(this.x + 1, 0, ch);
2979 this.lines.get(i).pop();
2980 }
2981 }
2982
2983 this.maxRange();
2984 };
2985
2986
2987 /**
2988 * CSI P m SP ~
2989 * Delete P s Column(s) (default = 1) (DECDC), VT420 and up
2990 * NOTE: xterm doesn't enable this code by default.
2991 */
2992 Terminal.prototype.deleteColumns = function() {
2993 var param = params[0]
2994 , l = this.ybase + this.rows
2995 , ch = [this.eraseAttr(), ' ', 1] // xterm?
2996 , i;
2997
2998 while (param--) {
2999 for (i = this.ybase; i < l; i++) {
3000 this.lines.get(i).splice(this.x, 1);
3001 this.lines.get(i).push(ch);
3002 }
3003 }
3004
3005 this.maxRange();
3006 };
3007
3008 /**
3009 * Helpers
3010 */
3011
3012 function on(el, type, handler, capture) {
3013 if (!Array.isArray(el)) {
3014 el = [el];
3015 }
3016 el.forEach(function (element) {
3017 element.addEventListener(type, handler, capture || false);
3018 });
3019 }
3020
3021 function off(el, type, handler, capture) {
3022 el.removeEventListener(type, handler, capture || false);
3023 }
3024
3025 function cancel(ev, force) {
3026 if (!this.cancelEvents && !force) {
3027 return;
3028 }
3029 ev.preventDefault();
3030 ev.stopPropagation();
3031 return false;
3032 }
3033
3034 function inherits(child, parent) {
3035 function f() {
3036 this.constructor = child;
3037 }
3038 f.prototype = parent.prototype;
3039 child.prototype = new f;
3040 }
3041
3042 // if bold is broken, we can't
3043 // use it in the terminal.
3044 function isBoldBroken(document) {
3045 var body = document.getElementsByTagName('body')[0];
3046 var el = document.createElement('span');
3047 el.innerHTML = 'hello world';
3048 body.appendChild(el);
3049 var w1 = el.scrollWidth;
3050 el.style.fontWeight = 'bold';
3051 var w2 = el.scrollWidth;
3052 body.removeChild(el);
3053 return w1 !== w2;
3054 }
3055
3056 function indexOf(obj, el) {
3057 var i = obj.length;
3058 while (i--) {
3059 if (obj[i] === el) return i;
3060 }
3061 return -1;
3062 }
3063
3064 function isThirdLevelShift(term, ev) {
3065 var thirdLevelKey =
3066 (term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
3067 (term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
3068
3069 if (ev.type == 'keypress') {
3070 return thirdLevelKey;
3071 }
3072
3073 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
3074 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
3075 }
3076
3077 // Expose to InputHandler (temporary)
3078 Terminal.prototype.matchColor = matchColor;
3079
3080 function matchColor(r1, g1, b1) {
3081 var hash = (r1 << 16) | (g1 << 8) | b1;
3082
3083 if (matchColor._cache[hash] != null) {
3084 return matchColor._cache[hash];
3085 }
3086
3087 var ldiff = Infinity
3088 , li = -1
3089 , i = 0
3090 , c
3091 , r2
3092 , g2
3093 , b2
3094 , diff;
3095
3096 for (; i < Terminal.vcolors.length; i++) {
3097 c = Terminal.vcolors[i];
3098 r2 = c[0];
3099 g2 = c[1];
3100 b2 = c[2];
3101
3102 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
3103
3104 if (diff === 0) {
3105 li = i;
3106 break;
3107 }
3108
3109 if (diff < ldiff) {
3110 ldiff = diff;
3111 li = i;
3112 }
3113 }
3114
3115 return matchColor._cache[hash] = li;
3116 }
3117
3118 matchColor._cache = {};
3119
3120 // http://stackoverflow.com/questions/1633828
3121 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
3122 return Math.pow(30 * (r1 - r2), 2)
3123 + Math.pow(59 * (g1 - g2), 2)
3124 + Math.pow(11 * (b1 - b2), 2);
3125 };
3126
3127 function each(obj, iter, con) {
3128 if (obj.forEach) return obj.forEach(iter, con);
3129 for (var i = 0; i < obj.length; i++) {
3130 iter.call(con, obj[i], i, obj);
3131 }
3132 }
3133
3134 function keys(obj) {
3135 if (Object.keys) return Object.keys(obj);
3136 var key, keys = [];
3137 for (key in obj) {
3138 if (Object.prototype.hasOwnProperty.call(obj, key)) {
3139 keys.push(key);
3140 }
3141 }
3142 return keys;
3143 }
3144
3145 /**
3146 * Expose
3147 */
3148
3149 Terminal.EventEmitter = EventEmitter;
3150 Terminal.inherits = inherits;
3151
3152 /**
3153 * Adds an event listener to the terminal.
3154 *
3155 * @param {string} event The name of the event. TODO: Document all event types
3156 * @param {function} callback The function to call when the event is triggered.
3157 */
3158 Terminal.on = on;
3159 Terminal.off = off;
3160 Terminal.cancel = cancel;
3161
3162 module.exports = Terminal;