xterm
authorVSORC <josuer08@gmail.com>
Wed, 13 Nov 2019 21:31:35 +0000 (17:31 -0400)
committerVSORC <josuer08@gmail.com>
Wed, 13 Nov 2019 21:31:35 +0000 (17:31 -0400)
103 files changed:
node_modules/.bin/mime [changed from symlink to file mode: 0755]
node_modules/.bin/static [changed from symlink to file mode: 0755]
node_modules/.bin/wscat [changed from symlink to file mode: 0755]
node_modules/xterm/LICENSE [new file with mode: 0644]
node_modules/xterm/README.md [new file with mode: 0644]
node_modules/xterm/css/xterm.css [new file with mode: 0644]
node_modules/xterm/lib/xterm.js [new file with mode: 0644]
node_modules/xterm/lib/xterm.js.map [new file with mode: 0644]
node_modules/xterm/package.json [new file with mode: 0644]
node_modules/xterm/src/AccessibilityManager.ts [new file with mode: 0644]
node_modules/xterm/src/InputHandler.ts [new file with mode: 0644]
node_modules/xterm/src/Terminal.ts [new file with mode: 0644]
node_modules/xterm/src/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/WindowsMode.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Clipboard.ts [new file with mode: 0644]
node_modules/xterm/src/browser/ColorManager.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Lifecycle.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Linkifier.ts [new file with mode: 0644]
node_modules/xterm/src/browser/LocalizableStrings.ts [new file with mode: 0644]
node_modules/xterm/src/browser/MouseZoneManager.ts [new file with mode: 0644]
node_modules/xterm/src/browser/RenderDebouncer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/ScreenDprMonitor.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Viewport.ts [new file with mode: 0644]
node_modules/xterm/src/browser/input/CompositionHelper.ts [new file with mode: 0644]
node_modules/xterm/src/browser/input/Mouse.ts [new file with mode: 0644]
node_modules/xterm/src/browser/input/MoveToCell.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/GridCache.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/RendererUtils.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/TextRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/Constants.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts [new file with mode: 0644]
node_modules/xterm/src/browser/selection/SelectionModel.ts [new file with mode: 0644]
node_modules/xterm/src/browser/selection/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/CharSizeService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/MouseService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/RenderService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/SelectionService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/Services.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/SoundService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/tsconfig.json [new file with mode: 0644]
node_modules/xterm/src/common/CharWidth.ts [new file with mode: 0644]
node_modules/xterm/src/common/CircularList.ts [new file with mode: 0644]
node_modules/xterm/src/common/Clone.ts [new file with mode: 0644]
node_modules/xterm/src/common/EventEmitter.ts [new file with mode: 0644]
node_modules/xterm/src/common/Lifecycle.ts [new file with mode: 0644]
node_modules/xterm/src/common/Platform.ts [new file with mode: 0644]
node_modules/xterm/src/common/TypedArrayUtils.ts [new file with mode: 0644]
node_modules/xterm/src/common/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/AttributeData.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Buffer.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/BufferLine.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/BufferReflow.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/BufferSet.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/CellData.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Constants.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Marker.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/common/data/Charsets.ts [new file with mode: 0644]
node_modules/xterm/src/common/data/EscapeSequences.ts [new file with mode: 0644]
node_modules/xterm/src/common/input/Keyboard.ts [new file with mode: 0644]
node_modules/xterm/src/common/input/TextDecoder.ts [new file with mode: 0644]
node_modules/xterm/src/common/input/WriteBuffer.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/Constants.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/DcsParser.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/EscapeSequenceParser.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/OscParser.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/Params.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/BufferService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/CoreMouseService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/CoreService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/DirtyRowService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/InstantiationService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/LogService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/OptionsService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/ServiceRegistry.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/Services.ts [new file with mode: 0644]
node_modules/xterm/src/common/tsconfig.json [new file with mode: 0644]
node_modules/xterm/src/public/AddonManager.ts [new file with mode: 0644]
node_modules/xterm/src/public/Terminal.ts [new file with mode: 0644]
node_modules/xterm/src/renderer/CursorRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/renderer/Renderer.ts [new file with mode: 0644]
node_modules/xterm/src/renderer/dom/DomRenderer.ts [new file with mode: 0644]
node_modules/xterm/src/tsconfig-base.json [new file with mode: 0644]
node_modules/xterm/src/tsconfig-library-base.json [new file with mode: 0644]
node_modules/xterm/src/tsconfig.json [new file with mode: 0644]
node_modules/xterm/tsconfig.all.json [new file with mode: 0644]
node_modules/xterm/typings/xterm.d.ts [new file with mode: 0644]
npm-debug.log [deleted file]
src/index.js
src/views/starter.ejs

deleted file mode 120000 (symlink)
index fbb7ee0eed8d1dd0fe3b5a9d6ff41d1c4f044675..0000000000000000000000000000000000000000
+++ /dev/null
@@ -1 +0,0 @@
-../mime/cli.js
\ No newline at end of file
new file mode 100755 (executable)
index 0000000000000000000000000000000000000000..20b1ffeb2f97648e0faa7e022c98ed9e6a8e9a0d
--- /dev/null
@@ -0,0 +1,8 @@
+#!/usr/bin/env node
+
+var mime = require('./mime.js');
+var file = process.argv[2];
+var type = mime.lookup(file);
+
+process.stdout.write(type + '\n');
+
deleted file mode 120000 (symlink)
index 66f6f8a942a83628f745c840cff4078b84d52825..0000000000000000000000000000000000000000
+++ /dev/null
@@ -1 +0,0 @@
-../node-static/bin/cli.js
\ No newline at end of file
new file mode 100755 (executable)
index 0000000000000000000000000000000000000000..ecdab3fa0c347db0ab4b1466da6e560be6ed350b
--- /dev/null
@@ -0,0 +1,131 @@
+#!/usr/bin/env node
+
+var fs = require('fs'),
+    tty = require('tty'),
+    statik = require('./../lib/node-static');
+
+    var argv = require('optimist')
+        .usage([
+            'USAGE: $0 [-p <port>] [<directory>]',
+            'simple, rfc 2616 compliant file streaming module for node']
+            .join('\n\n'))
+        .option('port', {
+            alias: 'p',
+            'default': 8080,
+            description: 'TCP port at which the files will be served'
+        })
+        .option('host-address', {
+            alias: 'a',
+            'default': '127.0.0.1',
+            description: 'the local network interface at which to listen'
+        })
+        .option('cache', {
+            alias: 'c',
+            description: '"Cache-Control" header setting, defaults to 3600'
+        })
+        .option('version', {
+            alias: 'v',
+            description: 'node-static version'
+        })
+        .option('headers', {
+            alias: 'H',
+            description: 'additional headers (in JSON format)'
+        })
+        .option('header-file', {
+            alias: 'f',
+            description: 'JSON file of additional headers'
+        })
+        .option('gzip', {
+            alias: 'z',
+            description: 'enable compression (tries to serve file of same name plus \'.gz\')'
+        })
+        .option('spa', {
+            description: 'serve the content as a single page app by redirecting all non-file requests to the index html file'
+        })
+        .option('indexFile', {
+            alias: 'i',
+            'default': 'index.html',
+            description: 'specify a custom index file when serving up directories'
+        })
+        .option('help', {
+            alias: 'h',
+            description: 'display this help message'
+        })
+        .argv;
+
+    var dir = argv._[0] || '.';
+
+    var colors = require('colors');
+
+    var log = function(request, response, statusCode) {
+        var d = new Date();
+        var seconds = d.getSeconds() < 10? '0'+d.getSeconds() : d.getSeconds(),
+            datestr = d.getHours() + ':' + d.getMinutes() + ':' + seconds,
+            line = datestr + ' [' + response.statusCode + ']: ' + request.url,
+            colorized = line;
+        if (tty.isatty(process.stdout.fd))
+            colorized = (response.statusCode >= 500) ? line.red.bold :
+                        (response.statusCode >= 400) ? line.red :
+                        line;
+        console.log(colorized);
+    };
+
+    var file, options;
+
+if (argv.help) {
+    require('optimist').showHelp(console.log);
+    process.exit(0);
+}
+
+if (argv.version) {
+    console.log('node-static', statik.version.join('.'));
+    process.exit(0);
+}
+
+if (argv.cache) {
+    (options = options || {}).cache = argv.cache;
+}
+
+if (argv.headers) {
+    (options = options || {}).headers = JSON.parse(argv.headers);
+}
+
+if (argv['header-file']) {
+    (options = options || {}).headers =
+        JSON.parse(fs.readFileSync(argv['header-file']));
+}
+
+if (argv.gzip) {
+    (options = options || {}).gzip = true;
+}
+
+if (argv.indexFile) {
+    (options = options || {}).indexFile = argv['indexFile'];
+}
+
+file = new(statik.Server)(dir, options);
+
+require('http').createServer(function (request, response) {
+    request.addListener('end', function () {
+        var callback = function(e, rsp) {
+          if (e && e.status === 404) {
+              response.writeHead(e.status, e.headers);
+              response.end("Not Found");
+              log(request, response);
+          } else {
+              log(request, response);
+          }
+        };
+
+        if (argv['spa'] && request.url.indexOf(".") == -1) {
+            file.serveFile(argv['indexFile'], 200, {}, request, response);
+        } else {
+            file.serve(request, response, callback);
+        }
+    }).resume();
+}).listen(+argv.port, argv['host-address']);
+
+console.log('serving "' + dir + '" at http://' + argv['host-address'] + ':' + argv.port);
+if (argv.spa) {
+  console.log('serving as a single page app (all non-file requests redirect to ' + argv['indexFile'] +')');
+}
deleted file mode 120000 (symlink)
index 5392fc9d1daad3de7eb35e17be7940fa91ef4aa3..0000000000000000000000000000000000000000
+++ /dev/null
@@ -1 +0,0 @@
-../wscat/bin/wscat
\ No newline at end of file
new file mode 100755 (executable)
index 0000000000000000000000000000000000000000..48f0889f3af31dce5fcf7e824e0e8ac3dc7163bf
--- /dev/null
@@ -0,0 +1,367 @@
+#!/usr/bin/env node
+
+/*!
+ * ws: a node.js websocket client
+ * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
+ * MIT Licensed
+ */
+
+const EventEmitter = require('events');
+const fs = require('fs');
+const program = require('commander');
+const read = require('read');
+const readline = require('readline');
+const tty = require('tty');
+const WebSocket = require('ws');
+
+/**
+ * InputReader - processes console input.
+ *
+ * @extends EventEmitter
+ */
+class Console extends EventEmitter {
+  constructor() {
+    super();
+
+    this.stdin = process.stdin;
+    this.stdout = process.stdout;
+
+    this.readlineInterface = readline.createInterface(this.stdin, this.stdout);
+
+    this.readlineInterface
+      .on('line', data => {
+        this.emit('line', data);
+      })
+      .on('close', () => {
+        this.emit('close');
+      });
+
+    this._resetInput = () => {
+      this.clear();
+    };
+  }
+
+  static get Colors() {
+    return {
+      Red: '\u001b[31m',
+      Green: '\u001b[32m',
+      Yellow: '\u001b[33m',
+      Blue: '\u001b[34m',
+      Default: '\u001b[39m'
+    };
+  }
+
+  static get Types() {
+    return {
+      Incoming: '< ',
+      Control: '',
+      Error: 'error: '
+    };
+  }
+
+  prompt() {
+    this.readlineInterface.prompt();
+  }
+
+  print(type, msg, color) {
+    if (tty.isatty(1)) {
+      this.clear();
+
+      if (program.execute) color = type = '';
+      else if (!program.color) color = '';
+
+      this.stdout.write(color + type + msg + Console.Colors.Default + '\n');
+      this.prompt();
+    } else if (type === Console.Types.Incoming) {
+      this.stdout.write(msg + '\n');
+    } else {
+      // is a control message and we're not in a tty... drop it.
+    }
+  }
+
+  clear() {
+    if (tty.isatty(1)) {
+      this.stdout.write('\u001b[2K\u001b[3D');
+    }
+  }
+
+  pause() {
+    this.stdin.on('keypress', this._resetInput);
+  }
+
+  resume() {
+    this.stdin.removeListener('keypress', this._resetInput);
+  }
+}
+
+function collect(val, memo) {
+  memo.push(val);
+  return memo;
+}
+
+function noop() {}
+
+/**
+ * The actual application
+ */
+const version = require('../package.json').version;
+
+program
+  .version(version)
+  .usage('[options] (--listen <port> | --connect <url>)')
+  .option('-l, --listen <port>', 'listen on port')
+  .option('-c, --connect <url>', 'connect to a websocket server')
+  .option('-p, --protocol <version>', 'optional protocol version')
+  .option('-o, --origin <origin>', 'optional origin')
+  .option('-x, --execute <command>', 'execute command after connecting')
+  .option('-w, --wait <seconds>', 'wait given seconds after executing command')
+  .option('--host <host>', 'optional host')
+  .option('-s, --subprotocol <protocol>', 'optional subprotocol', collect, [])
+  .option('-n, --no-check', 'Do not check for unauthorized certificates')
+  .option(
+    '-H, --header <header:value>',
+    'Set an HTTP header. Repeat to set multiple. (--connect only)',
+    collect,
+    []
+  )
+  .option(
+    '--auth <username:password>',
+    'Add basic HTTP authentication header. (--connect only)'
+  )
+  .option('--ca <ca>', 'Specify a Certificate Authority (--connect only)')
+  .option('--cert <cert>', 'Specify a Client SSL Certificate (--connect only)')
+  .option(
+    '--key <key>',
+    "Specify a Client SSL Certificate's key (--connect only)"
+  )
+  .option(
+    '--passphrase [passphrase]',
+    "Specify a Client SSL Certificate Key's passphrase (--connect only). " +
+      "If you don't provide a value, it will be prompted for."
+  )
+  .option('--no-color', 'Run without color')
+  .option(
+    '--slash',
+    'Enable slash commands for control frames ' +
+      '(/ping, /pong, /close [code [, reason]])'
+  )
+  .parse(process.argv);
+
+if (program.listen && program.connect) {
+  console.error('\u001b[33merror: use either --listen or --connect\u001b[39m');
+  process.exit(-1);
+}
+
+if (program.listen) {
+  const wsConsole = new Console();
+  wsConsole.pause();
+
+  let ws = null;
+  const wss = new WebSocket.Server({ port: program.listen }, () => {
+    wsConsole.print(
+      Console.Types.Control,
+      `listening on port ${program.listen} (press CTRL+C to quit)`,
+      Console.Colors.Green
+    );
+    wsConsole.clear();
+  });
+
+  wsConsole.on('close', () => {
+    if (ws) ws.close();
+    process.exit(0);
+  });
+
+  wsConsole.on('line', data => {
+    if (ws) {
+      ws.send(data);
+      wsConsole.prompt();
+    }
+  });
+
+  wss.on('connection', newClient => {
+    if (ws) return newClient.terminate();
+
+    ws = newClient;
+    wsConsole.resume();
+    wsConsole.prompt();
+    wsConsole.print(
+      Console.Types.Control,
+      'client connected',
+      Console.Colors.Green
+    );
+
+    ws.on('close', code => {
+      wsConsole.print(
+        Console.Types.Control,
+        `disconnected (code: ${code})`,
+        Console.Colors.Green
+      );
+      wsConsole.clear();
+      wsConsole.pause();
+      ws = null;
+    });
+
+    ws.on('error', err => {
+      wsConsole.print(Console.Types.Error, err.message, Console.Colors.Yellow);
+    });
+
+    ws.on('message', data => {
+      wsConsole.print(Console.Types.Incoming, data, Console.Colors.Blue);
+    });
+  });
+
+  wss.on('error', err => {
+    wsConsole.print(Console.Types.Error, err.message, Console.Colors.Yellow);
+    process.exit(-1);
+  });
+} else if (program.connect) {
+  const options = {};
+  const cont = () => {
+    const wsConsole = new Console();
+
+    const headers = program.header.reduce((acc, cur) => {
+      const i = cur.indexOf(':');
+      const key = cur.slice(0, i);
+      const value = cur.slice(i + 1);
+      acc[key] = value;
+      return acc;
+    }, {});
+
+    if (program.auth) {
+      headers.Authorization =
+        'Basic ' + Buffer.from(program.auth).toString('base64');
+    }
+    if (program.host) headers.Host = program.host;
+    if (program.protocol) options.protocolVersion = +program.protocol;
+    if (program.origin) options.origin = program.origin;
+    if (!program.check) options.rejectUnauthorized = program.check;
+    if (program.ca) options.ca = fs.readFileSync(program.ca);
+    if (program.cert) options.cert = fs.readFileSync(program.cert);
+    if (program.key) options.key = fs.readFileSync(program.key);
+
+    let connectUrl = program.connect;
+    if (!connectUrl.match(/\w+:\/\/.*$/i)) {
+      connectUrl = `ws://${connectUrl}`;
+    }
+
+    options.headers = headers;
+    const ws = new WebSocket(connectUrl, program.subprotocol, options);
+
+    ws.on('open', () => {
+      if (program.execute) {
+        ws.send(program.execute);
+        setTimeout(() => {
+          ws.close();
+        }, program.wait ? program.wait * 1000 : 2000);
+      } else {
+        wsConsole.print(
+          Console.Types.Control,
+          'connected (press CTRL+C to quit)',
+          Console.Colors.Green
+        );
+
+        wsConsole.on('line', data => {
+          if (program.slash && data[0] === '/') {
+            const toks = data.split(/\s+/);
+            switch (toks[0].substr(1)) {
+              case 'ping':
+                ws.ping(noop);
+                break;
+              case 'pong':
+                ws.pong(noop);
+                break;
+              case 'close': {
+                let closeStatusCode = 1000;
+                let closeReason = '';
+                if (toks.length >= 2) {
+                  closeStatusCode = parseInt(toks[1]);
+                }
+                if (toks.length >= 3) {
+                  closeReason = toks.slice(2).join(' ');
+                }
+                if (closeReason.length > 0) {
+                  ws.close(closeStatusCode, closeReason);
+                } else {
+                  ws.close(closeStatusCode);
+                }
+                break;
+              }
+              default:
+                wsConsole.print(
+                  Console.Types.Error,
+                  'Unrecognized slash command.',
+                  Console.Colors.Yellow
+                );
+            }
+          } else {
+            ws.send(data);
+          }
+          wsConsole.prompt();
+        });
+      }
+    });
+
+    ws.on('close', code => {
+      if (!program.execute) {
+        wsConsole.print(
+          Console.Types.Control,
+          `disconnected (code: ${code})`,
+          Console.Colors.Green
+        );
+      }
+      wsConsole.clear();
+      process.exit();
+    });
+
+    ws.on('error', err => {
+      wsConsole.print(Console.Types.Error, err.message, Console.Colors.Yellow);
+      process.exit(-1);
+    });
+
+    ws.on('message', data => {
+      wsConsole.print(Console.Types.Incoming, data, Console.Colors.Blue);
+    });
+
+    ws.on('ping', () => {
+      wsConsole.print(
+        Console.Types.Incoming,
+        'Received ping',
+        Console.Colors.Blue
+      );
+    });
+
+    ws.on('pong', () => {
+      wsConsole.print(
+        Console.Types.Incoming,
+        'Received pong',
+        Console.Colors.Blue
+      );
+    });
+
+    wsConsole.on('close', () => {
+      ws.close();
+      process.exit();
+    });
+  };
+
+  if (program.passphrase === true) {
+    read(
+      {
+        prompt: 'Passphrase: ',
+        silent: true,
+        replace: '*'
+      },
+      (err, passphrase) => {
+        options.passphrase = passphrase;
+        cont();
+      }
+    );
+  } else if (typeof program.passphrase === 'string') {
+    options.passphrase = program.passphrase;
+    cont();
+  } else {
+    cont();
+  }
+} else {
+  program.help();
+}
diff --git a/node_modules/xterm/LICENSE b/node_modules/xterm/LICENSE
new file mode 100644 (file)
index 0000000..4472336
--- /dev/null
@@ -0,0 +1,21 @@
+Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
+Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/node_modules/xterm/README.md b/node_modules/xterm/README.md
new file mode 100644 (file)
index 0000000..5cf2848
--- /dev/null
@@ -0,0 +1,190 @@
+# [![xterm.js logo](logo-full.png)](https://xtermjs.org)
+
+[![Build Status](https://dev.azure.com/xtermjs/xterm.js/_apis/build/status/xtermjs.xterm.js)](https://dev.azure.com/xtermjs/xterm.js/_build/latest?definitionId=3)
+
+Xterm.js is a front-end component written in TypeScript that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code, Hyper and Theia.
+
+## Features
+
+- **Terminal apps just work**: Xterm.js works with most terminal apps such as `bash`, `vim` and `tmux`, this includes support for curses-based apps and mouse event support.
+- **Performant**: Xterm.js is *really* fast, it even includes a GPU-accelerated renderer.
+- **Rich unicode support**: Supports CJK, emojis and IMEs.
+- **Self-contained**: Requires zero dependencies to work.
+- **Accessible**: Screen reader support can be turned on using the `screenReaderMode` option.
+- **And much more**: Links, theming, addons, well documented API, etc.
+
+## What xterm.js is not
+
+- Xterm.js is not a terminal application that you can download and use on your computer.
+- Xterm.js is not `bash`. Xterm.js can be connected to processes like `bash` and let you interact with them (provide input, receive output).
+
+## Getting Started
+
+First you need to install the module, we ship exclusively through [npm](https://www.npmjs.com/) so you need that installed and then add xterm.js as a dependency by running:
+
+```
+npm install xterm
+```
+
+To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your html page. Then create a `<div id="terminal"></div>` onto which xterm can attach itself. Finally instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
+
+```html
+<!doctype html>
+  <html>
+    <head>
+      <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
+      <script src="node_modules/xterm/lib/xterm.js"></script>
+    </head>
+    <body>
+      <div id="terminal"></div>
+      <script>
+        var term = new Terminal();
+        term.open(document.getElementById('terminal'));
+        term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
+      </script>
+    </body>
+  </html>
+```
+
+### Importing
+
+The recommended way to load xterm.js is via the ES6 module syntax:
+
+```javascript
+import { Terminal } from 'xterm';
+```
+
+### Addons
+
+⚠️ *This section describes the new addon format introduced in v3.14.0, see [here](https://github.com/xtermjs/xterm.js/blob/3.14.2/README.md#addons) for the instructions on the old format*
+
+Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon you first need to install it in your project:
+
+```bash
+npm i -S xterm-addon-web-links
+```
+
+Then import the addon, instantiate it and call `Terminal.loadAddon`:
+
+```ts
+import { Terminal } from 'xterm';
+import { WebLinksAddon } from 'xterm-addon-web-links';
+
+const terminal = new Terminal();
+// Load WebLinksAddon on terminal, this is all that's needed to get web links
+// working in the terminal.
+terminal.loadAddon(new WebLinksAddon());
+```
+
+The xterm.js team maintains the following addons but they can be built by anyone:
+
+- [`xterm-addon-attach`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-attach): Attaches to a server running a process via a websocket
+- [`xterm-addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-fit): Fits the terminal to the containing element
+- [`xterm-addon-search`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-search): Adds search functionality
+- [`xterm-addon-web-links`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-web-links): Adds web link detection and interaction
+
+## Browser Support
+
+Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox* and *Safari*.
+
+We also partially support *Intenet Explorer 11*, meaning xterm.js should work for the most part, but we reserve the right to not provide workarounds specifically for it unless it's absolutely necessary to get the basic input/output flow working.
+
+Xterm.js works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers, these are the versions we strive to keep working.
+
+## API
+
+The full API for xterm.js is contained within the [TypeScript declaration file](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts), use the branch/tag picker in GitHub (`w`) to navigate to the correct version of the API.
+
+Note that some APIs are marked *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions so be sure to read release notes if you plan on using experimental APIs.
+
+## Real-world uses
+Xterm.js is used in several world-class applications to provide great terminal experiences.
+
+- [**SourceLair**](https://www.sourcelair.com/): In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js.
+- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile and powerful open source code editor that provides an integrated terminal based on xterm.js.
+- [**ttyd**](https://github.com/tsl0922/ttyd): A command-line tool for sharing terminal over the web, with fully-featured terminal emulation based on xterm.js.
+- [**Katacoda**](https://www.katacoda.com/): Katacoda is an Interactive Learning Platform for software developers, covering the latest Cloud Native technologies.
+- [**Eclipse Che**](http://www.eclipse.org/che): Developer workspace server, cloud IDE, and Eclipse next-generation IDE.
+- [**Codenvy**](http://www.codenvy.com): Cloud workspaces for development teams.
+- [**CoderPad**](https://coderpad.io): Online interviewing platform for programmers. Run code in many programming languages, with results displayed by xterm.js.
+- [**WebSSH2**](https://github.com/billchurch/WebSSH2): A web based SSH2 client using xterm.js, socket.io, and ssh2.
+- [**Spyder Terminal**](https://github.com/spyder-ide/spyder-terminal): A full fledged system terminal embedded on Spyder IDE.
+- [**Cloud Commander**](https://cloudcmd.io "Cloud Commander"): Orthodox web file manager with console and editor.
+- [**Codevolve**](https://www.codevolve.com "Codevolve"): Online platform for interactive coding and web development courses. Live container-backed terminal uses xterm.js.
+- [**RStudio**](https://www.rstudio.com/products/RStudio "RStudio"): RStudio is an integrated development environment (IDE) for R.
+- [**Terminal for Atom**](https://github.com/jsmecham/atom-terminal-tab): A simple terminal for the Atom text editor.
+- [**Eclipse Orion**](https://orionhub.org): A modern, open source software development environment that runs in the cloud. Code, deploy and run in the cloud.
+- [**Gravitational Teleport**](https://github.com/gravitational/teleport): Gravitational Teleport is a modern SSH server for remotely accessing clusters of Linux servers via SSH or HTTPS.
+- [**Hexlet**](https://en.hexlet.io): Practical programming courses (JavaScript, PHP, Unix, databases, functional programming). A steady path from the first line of code to the first job.
+- [**Selenoid UI**](https://github.com/aerokube/selenoid-ui): Simple UI for the scallable golang implementation of Selenium Hub named Selenoid. We use XTerm for streaming logs over websockets from docker containers.
+- [**Portainer**](https://portainer.io): Simple management UI for Docker.
+- [**SSHy**](https://github.com/stuicey/SSHy): HTML5 Based SSHv2 Web Client with E2E encryption utilising xterm.js, SJCL & websockets.
+- [**JupyterLab**](https://github.com/jupyterlab/jupyterlab): An extensible computational environment for Jupyter, supporting interactive data science and scientific computing across all programming languages.
+- [**Theia**](https://github.com/theia-ide/theia): Theia is a cloud & desktop IDE framework implemented in TypeScript.
+- [**Opshell**](https://github.com/ricktbaker/opshell) Ops Helper tool to make life easier working with AWS instances across multiple organizations.
+- [**Proxmox VE**](https://www.proxmox.com/en/proxmox-ve): Proxmox VE is a complete open-source platform for enterprise virtualization. It uses xterm.js for container terminals and the host shell.
+- [**Script Runner**](https://github.com/ioquatix/script-runner): Run scripts (or a shell) in Atom.
+- [**Whack Whack Terminal**](https://github.com/Microsoft/WhackWhackTerminal): Terminal emulator for Visual Studio 2017.
+- [**VTerm**](https://github.com/vterm/vterm): Extensible terminal emulator based on Electron and React.
+- [**electerm**](http://electerm.html5beta.com): electerm is a terminal/ssh/sftp client(mac, win, linux) based on electron/node-pty/xterm.
+- [**Kubebox**](https://github.com/astefanutti/kubebox): Terminal console for Kubernetes clusters.
+- [**Azure Cloud Shell**](https://shell.azure.com): Azure Cloud Shell is a Microsoft-managed admin machine built on Azure, for Azure.
+- [**atom-xterm**](https://atom.io/packages/atom-xterm): Atom plugin for providing terminals inside your Atom workspace.
+- [**rtty**](https://github.com/zhaojh329/rtty): Access your terminals from anywhere via the web.
+- [**Pisth**](https://github.com/ColdGrub1384/Pisth): An SFTP and SSH client for iOS.
+- [**abstruse**](https://github.com/bleenco/abstruse): Abstruse CI is a continuous integration platform based on Node.JS and Docker.
+- [**Azure Data Studio**](https://github.com/Microsoft/azuredatastudio): A data management tool that enables working with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.
+- [**FreeMAN**](https://github.com/matthew-matvei/freeman): A free, cross-platform file manager for power users.
+- [**Fluent Terminal**](https://github.com/felixse/FluentTerminal): A terminal emulator based on UWP and web technologies.
+- [**Hyper**](https://hyper.is): A terminal built on web technologies.
+- [**Diag**](https://diag.ai): A better way to troubleshoot problems faster. Capture, share and reapply troubleshooting knowledge so you can focus on solving problems that matter.
+- [**GoTTY**](https://github.com/yudai/gotty): A simple command line tool that shares your terminal as a web application based on xterm.js.
+- [**genact**](https://github.com/svenstaro/genact): A nonsense activity generator.
+- [**cPanel & WHM**](https://cpanel.com): The hosting platform of choice.
+- [**Nutanix**](https://github.com/nutanix): Nutanix Enterprise Cloud uses xterm in the webssh functionality within Nutanix Calm, and is also looking to move our old noserial (termjs) functionality to xterm.js.
+- [**SSH Web Client**](https://github.com/roke22/PHP-SSH2-Web-Client): SSH Web Client with PHP.
+- [**Shellvault**](https://www.shellvault.io): The cloud-based SSH terminal you can access from anywhere.
+- [**Juno**](http://junolab.org/): A flexible Julia IDE, based on Atom.
+- [**webssh**](https://github.com/huashengdun/webssh): Web based ssh client.
+- [**info-beamer hosted**](https://info-beamer.com): Uses xterm.js to manage digital signage devices from the web dashboard.
+- [**Jumpserver**](https://github.com/jumpserver/luna): Jumpserver Luna project, Jumpserver is a bastion server project, Luna use xterm.js for web terminal emulation.
+- [**LxdMosaic**](https://github.com/turtle0x1/LxdMosaic): Uses xterm.js to give terminal access to containers through LXD
+- [**CodeInterview.io**](https://codeinterview.io): A coding interview platform in 25+ languages and many web frameworks. Uses xterm.js to provide shell access.
+- [**Bastillion**](https://www.bastillion.io): Bastillion is an open-source web-based SSH console that centrally manages administrative access to systems.
+- [**PHP App Server**](https://github.com/cubiclesoft/php-app-server/): Create lightweight, installable almost-native applications for desktop OSes.  ExecTerminal (nicely wraps the xterm.js Terminal), TerminalManager, and RunProcessSDK are self-contained, reusable ES5+ compliant Javascript components.
+- [**NgTerminal**](https://github.com/qwefgh90/ng-terminal): NgTerminal is a web terminal that leverages xterm.js on Angular 7+. You can easily add it into your application by adding `<ng-terminal></ng-terminal>` into your component.
+- [**tty-share**](https://tty-share.com): Extremely simple terminal sharing over the Internet.
+- [**Ten Hands**](https://github.com/saisandeepvaddi/ten-hands): One place to run your command-line tasks.
+- [**WebAssembly.sh**](https://webassembly.sh): A WebAssembly WASI browser terminal
+
+[And much more...](https://github.com/xtermjs/xterm.js/network/dependents)
+
+Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it in our list. Note: Please add any new contributions to the end of the list only.
+
+## Releases
+
+Xterm.js follows a monthly release cycle roughly.
+
+All current and past releases are available on this repo's [Releases page](https://github.com/sourcelair/xterm.js/releases), you can view the [high-level roadmap on the wiki](https://github.com/xtermjs/xterm.js/wiki/Roadmap) and see what we're working on now by looking through [Milestones](https://github.com/sourcelair/xterm.js/milestones).
+
+### Beta builds
+
+Our CI releases beta builds to npm for every change that goes into master, install the latest beta build with:
+
+```
+npm install -S xterm@beta
+```
+
+These should generally be stable but some bugs may slip in, we recommend using the beta build primarily to test out new features and for verifying bug fixes.
+
+## Contributing
+
+You can read the [guide on the wiki](https://github.com/xtermjs/xterm.js/wiki/Contributing) to learn how to contribute and setup xterm.js for development.
+
+## License Agreement
+
+If you contribute code to this project, you are implicitly allowing your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work.
+
+Copyright (c) 2017-2019, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)<br>
+Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)<br>
+Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
diff --git a/node_modules/xterm/css/xterm.css b/node_modules/xterm/css/xterm.css
new file mode 100644 (file)
index 0000000..b3d8d4f
--- /dev/null
@@ -0,0 +1,171 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * https://github.com/chjj/term.js
+ * @license MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * Originally forked from (with the author's permission):
+ *   Fabrice Bellard's javascript vt100 for jslinux:
+ *   http://bellard.org/jslinux/
+ *   Copyright (c) 2011 Fabrice Bellard
+ *   The original design remains. The terminal itself
+ *   has been extended to include xterm CSI codes, among
+ *   other features.
+ */
+
+/**
+ *  Default styles for xterm.js
+ */
+
+.xterm {
+    font-feature-settings: "liga" 0;
+    position: relative;
+    user-select: none;
+    -ms-user-select: none;
+    -webkit-user-select: none;
+}
+
+.xterm.focus,
+.xterm:focus {
+    outline: none;
+}
+
+.xterm .xterm-helpers {
+    position: absolute;
+    top: 0;
+    /**
+     * The z-index of the helpers must be higher than the canvases in order for
+     * IMEs to appear on top.
+     */
+    z-index: 5;
+}
+
+.xterm .xterm-helper-textarea {
+    /*
+     * HACK: to fix IE's blinking cursor
+     * Move textarea out of the screen to the far left, so that the cursor is not visible.
+     */
+    position: absolute;
+    opacity: 0;
+    left: -9999em;
+    top: 0;
+    width: 0;
+    height: 0;
+    z-index: -5;
+    /** Prevent wrapping so the IME appears against the textarea at the correct position */
+    white-space: nowrap;
+    overflow: hidden;
+    resize: none;
+}
+
+.xterm .composition-view {
+    /* TODO: Composition position got messed up somewhere */
+    background: #000;
+    color: #FFF;
+    display: none;
+    position: absolute;
+    white-space: nowrap;
+    z-index: 1;
+}
+
+.xterm .composition-view.active {
+    display: block;
+}
+
+.xterm .xterm-viewport {
+    /* On OS X this is required in order for the scroll bar to appear fully opaque */
+    background-color: #000;
+    overflow-y: scroll;
+    cursor: default;
+    position: absolute;
+    right: 0;
+    left: 0;
+    top: 0;
+    bottom: 0;
+}
+
+.xterm .xterm-screen {
+    position: relative;
+}
+
+.xterm .xterm-screen canvas {
+    position: absolute;
+    left: 0;
+    top: 0;
+}
+
+.xterm .xterm-scroll-area {
+    visibility: hidden;
+}
+
+.xterm-char-measure-element {
+    display: inline-block;
+    visibility: hidden;
+    position: absolute;
+    top: 0;
+    left: -9999em;
+    line-height: normal;
+}
+
+.xterm {
+    cursor: text;
+}
+
+.xterm.enable-mouse-events {
+    /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
+    cursor: default;
+}
+
+.xterm.xterm-cursor-pointer {
+    cursor: pointer;
+}
+
+.xterm.column-select.focus {
+    /* Column selection mode */
+    cursor: crosshair;
+}
+
+.xterm .xterm-accessibility,
+.xterm .xterm-message {
+    position: absolute;
+    left: 0;
+    top: 0;
+    bottom: 0;
+    right: 0;
+    z-index: 10;
+    color: transparent;
+}
+
+.xterm .live-region {
+    position: absolute;
+    left: -9999px;
+    width: 1px;
+    height: 1px;
+    overflow: hidden;
+}
+
+.xterm-dim {
+    opacity: 0.5;
+}
+
+.xterm-underline {
+    text-decoration: underline;
+}
diff --git a/node_modules/xterm/lib/xterm.js b/node_modules/xterm/lib/xterm.js
new file mode 100644 (file)
index 0000000..7ee6ebc
--- /dev/null
@@ -0,0 +1,2 @@
+!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(window,function(){return function(e){var t={};function i(r){if(t[r])return t[r].exports;var n=t[r]={i:r,l:!1,exports:{}};return e[r].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=e,i.c=t,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)i.d(r,n,function(t){return e[t]}.bind(null,n));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=32)}([function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(13);t.IBufferService=r.createDecorator("BufferService"),t.ICoreMouseService=r.createDecorator("CoreMouseService"),t.ICoreService=r.createDecorator("CoreService"),t.IDirtyRowService=r.createDecorator("DirtyRowService"),t.IInstantiationService=r.createDecorator("InstantiationService"),t.ILogService=r.createDecorator("LogService"),t.IOptionsService=r.createDecorator("OptionsService")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._listeners=[]}return Object.defineProperty(e.prototype,"event",{get:function(){var e=this;return this._event||(this._event=function(t){return e._listeners.push(t),{dispose:function(){for(var i=0;i<e._listeners.length;i++)if(e._listeners[i]===t)return void e._listeners.splice(i,1)}}}),this._event},enumerable:!0,configurable:!0}),e.prototype.fire=function(e){for(var t=[],i=0;i<this._listeners.length;i++)t.push(this._listeners[i]);for(i=0;i<t.length;i++)t[i].call(void 0,e)},e}();t.EventEmitter=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._disposables=[],this._isDisposed=!1}return e.prototype.dispose=function(){this._isDisposed=!0,this._disposables.forEach(function(e){return e.dispose()}),this._disposables.length=0},e.prototype.register=function(e){this._disposables.push(e)},e.prototype.unregister=function(e){var t=this._disposables.indexOf(e);-1!==t&&this._disposables.splice(t,1)},e}();t.Disposable=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_COLOR=256,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR="",t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=" ",t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(8),o=i(3),a=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.content=0,t.fg=0,t.bg=0,t.combinedData="",t}return n(t,e),t.fromCharData=function(e){var i=new t;return i.setFromCharData(e),i},t.prototype.isCombined=function(){return 2097152&this.content},t.prototype.getWidth=function(){return this.content>>22},t.prototype.getChars=function(){return 2097152&this.content?this.combinedData:2097151&this.content?s.stringFromCodePoint(2097151&this.content):""},t.prototype.getCode=function(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content},t.prototype.setFromCharData=function(e){this.fg=e[o.CHAR_DATA_ATTR_INDEX],this.bg=0;var t=!1;if(e[o.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(2===e[o.CHAR_DATA_CHAR_INDEX].length){var i=e[o.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){var r=e[o.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(i-55296)+r-56320+65536|e[o.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[o.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[o.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[o.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[o.CHAR_DATA_WIDTH_INDEX]<<22)},t.prototype.getAsCharData=function(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]},t}(i(6).AttributeData);t.CellData=a},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(13);t.ICharSizeService=r.createDecorator("CharSizeService"),t.IMouseService=r.createDecorator("MouseService"),t.IRenderService=r.createDecorator("RenderService"),t.ISelectionService=r.createDecorator("SelectionService"),t.ISoundService=r.createDecorator("SoundService")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.fg=0,this.bg=0}return e.toColorRGB=function(e){return[e>>>16&255,e>>>8&255,255&e]},e.fromColorRGB=function(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]},e.prototype.clone=function(){var t=new e;return t.fg=this.fg,t.bg=this.bg,t},e.prototype.isInverse=function(){return 67108864&this.fg},e.prototype.isBold=function(){return 134217728&this.fg},e.prototype.isUnderline=function(){return 268435456&this.fg},e.prototype.isBlink=function(){return 536870912&this.fg},e.prototype.isInvisible=function(){return 1073741824&this.fg},e.prototype.isItalic=function(){return 67108864&this.bg},e.prototype.isDim=function(){return 134217728&this.bg},e.prototype.getFgColorMode=function(){return 50331648&this.fg},e.prototype.getBgColorMode=function(){return 50331648&this.bg},e.prototype.isFgRGB=function(){return 50331648==(50331648&this.fg)},e.prototype.isBgRGB=function(){return 50331648==(50331648&this.bg)},e.prototype.isFgPalette=function(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)},e.prototype.isBgPalette=function(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)},e.prototype.isFgDefault=function(){return 0==(50331648&this.fg)},e.prototype.isBgDefault=function(){return 0==(50331648&this.bg)},e.prototype.getFgColor=function(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}},e.prototype.getBgColor=function(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}},e}();t.AttributeData=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDisposableDomListener=function(e,t,i,r){return e.addEventListener(t,i,r),{dispose:function(){i&&e.removeEventListener(t,i,r)}}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=e.length);for(var r="",n=t;n<i;++n){var s=e[n];s>65535?(s-=65536,r+=String.fromCharCode(55296+(s>>10))+String.fromCharCode(s%1024+56320)):r+=String.fromCharCode(s)}return r};var r=function(){function e(){this._interim=0}return e.prototype.clear=function(){this._interim=0},e.prototype.decode=function(e,t){var i=e.length;if(!i)return 0;var r=0,n=0;this._interim&&(56320<=(a=e.charCodeAt(n++))&&a<=57343?t[r++]=1024*(this._interim-55296)+a-56320+65536:(t[r++]=this._interim,t[r++]=a),this._interim=0);for(var s=n;s<i;++s){var o=e.charCodeAt(s);if(55296<=o&&o<=56319){if(++s>=i)return this._interim=o,r;var a;56320<=(a=e.charCodeAt(s))&&a<=57343?t[r++]=1024*(o-55296)+a-56320+65536:(t[r++]=o,t[r++]=a)}else t[r++]=o}return r},e}();t.StringToUtf32=r;var n=function(){function e(){this.interim=new Uint8Array(3)}return e.prototype.clear=function(){this.interim.fill(0)},e.prototype.decode=function(e,t){var i=e.length;if(!i)return 0;var r,n,s,o,a=0,c=0,l=0;if(this.interim[0]){var h=!1,u=this.interim[0];u&=192==(224&u)?31:224==(240&u)?15:7;for(var f=0,_=void 0;(_=63&this.interim[++f])&&f<4;)u<<=6,u|=_;for(var d=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,p=d-f;l<p;){if(l>=i)return 0;if(128!=(192&(_=e[l++]))){l--,h=!0;break}this.interim[f++]=_,u<<=6,u|=63&_}h||(2===d?u<128?l--:t[a++]=u:3===d?u<2048||u>=55296&&u<=57343||(t[a++]=u):u<65536||u>1114111||(t[a++]=u)),this.interim.fill(0)}for(var v=i-4,g=l;g<i;){for(;!(!(g<v)||128&(r=e[g])||128&(n=e[g+1])||128&(s=e[g+2])||128&(o=e[g+3]));)t[a++]=r,t[a++]=n,t[a++]=s,t[a++]=o,g+=4;if((r=e[g++])<128)t[a++]=r;else if(192==(224&r)){if(g>=i)return this.interim[0]=r,a;if(128!=(192&(n=e[g++]))){g--;continue}if((c=(31&r)<<6|63&n)<128){g--;continue}t[a++]=c}else if(224==(240&r)){if(g>=i)return this.interim[0]=r,a;if(128!=(192&(n=e[g++]))){g--;continue}if(g>=i)return this.interim[0]=r,this.interim[1]=n,a;if(128!=(192&(s=e[g++]))){g--;continue}if((c=(15&r)<<12|(63&n)<<6|63&s)<2048||c>=55296&&c<=57343)continue;t[a++]=c}else if(240==(248&r)){if(g>=i)return this.interim[0]=r,a;if(128!=(192&(n=e[g++]))){g--;continue}if(g>=i)return this.interim[0]=r,this.interim[1]=n,a;if(128!=(192&(s=e[g++]))){g--;continue}if(g>=i)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=s,a;if(128!=(192&(o=e[g++]))){g--;continue}if((c=(7&r)<<18|(63&n)<<12|(63&s)<<6|63&o)<65536||c>1114111)continue;t[a++]=c}}return a},e}();t.Utf8ToUtf32=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.INVERTED_DEFAULT_COLOR=257,t.DIM_OPACITY=.5,t.CHAR_ATLAS_CELL_SPACING=1},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="undefined"==typeof navigator,n=r?"node":navigator.userAgent,s=r?"node":navigator.platform;function o(e,t){return e.indexOf(t)>=0}t.isFirefox=!!~n.indexOf("Firefox"),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.isMac=o(["Macintosh","MacIntel","MacPPC","Mac68K"],s),t.isIpad="iPad"===s,t.isIphone="iPhone"===s,t.isWindows=o(["Windows","Win16","Win32","WinCE"],s),t.isLinux=s.indexOf("Linux")>=0},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.NUL="\0",e.SOH="\ 1",e.STX="\ 2",e.ETX="\ 3",e.EOT="\ 4",e.ENQ="\ 5",e.ACK="\ 6",e.BEL="\a",e.BS="\b",e.HT="\t",e.LF="\n",e.VT="\v",e.FF="\f",e.CR="\r",e.SO="\ e",e.SI="\ f",e.DLE="\10",e.DC1="\11",e.DC2="\12",e.DC3="\13",e.DC4="\14",e.NAK="\15",e.SYN="\16",e.ETB="\17",e.CAN="\18",e.EM="\19",e.SUB="\1a",e.ESC="\e",e.FS="\1c",e.GS="\1d",e.RS="\1e",e.US="\1f",e.SP=" ",e.DEL="\7f"}(t.C0||(t.C0={})),function(e){e.PAD="\80",e.HOP="\81",e.BPH="\82",e.NBH="\83",e.IND="\84",e.NEL="\85",e.SSA="\86",e.ESA="\87",e.HTS="\88",e.HTJ="\89",e.VTS="\8a",e.PLD="\8b",e.PLU="\8c",e.RI="\8d",e.SS2="\8e",e.SS3="\8f",e.DCS="\90",e.PU1="\91",e.PU2="\92",e.STS="\93",e.CCH="\94",e.MW="\95",e.SPA="\96",e.EPA="\97",e.SOS="\98",e.SGCI="\99",e.SCI="\9a",e.CSI="\9b",e.ST="\9c",e.OSC="\9d",e.PM="\9e",e.APC="\9f"}(t.C1||(t.C1={}))},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(3),n=i(9),s=i(23),o=i(6),a=i(26),c=function(){function e(e,t,i,r,n,s,o,a){this._container=e,this._alpha=r,this._colors=n,this._rendererId=s,this._bufferService=o,this._optionsService=a,this._scaledCharWidth=0,this._scaledCharHeight=0,this._scaledCellWidth=0,this._scaledCellHeight=0,this._scaledCharLeft=0,this._scaledCharTop=0,this._currentGlyphIdentifier={chars:"",code:0,bg:0,fg:0,bold:!1,dim:!1,italic:!1},this._canvas=document.createElement("canvas"),this._canvas.classList.add("xterm-"+t+"-layer"),this._canvas.style.zIndex=i.toString(),this._initCanvas(),this._container.appendChild(this._canvas)}return e.prototype.dispose=function(){this._container.removeChild(this._canvas),this._charAtlas&&this._charAtlas.dispose()},e.prototype._initCanvas=function(){this._ctx=a.throwIfFalsy(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()},e.prototype.onOptionsChanged=function(){},e.prototype.onBlur=function(){},e.prototype.onFocus=function(){},e.prototype.onCursorMove=function(){},e.prototype.onGridChanged=function(e,t){},e.prototype.onSelectionChanged=function(e,t,i){void 0===i&&(i=!1)},e.prototype.setColors=function(e){this._refreshCharAtlas(e)},e.prototype._setTransparency=function(e){if(e!==this._alpha){var t=this._canvas;this._alpha=e,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,t),this._refreshCharAtlas(this._colors),this.onGridChanged(0,this._bufferService.rows-1)}},e.prototype._refreshCharAtlas=function(e){this._scaledCharWidth<=0&&this._scaledCharHeight<=0||(this._charAtlas=s.acquireCharAtlas(this._optionsService.options,this._rendererId,e,this._scaledCharWidth,this._scaledCharHeight),this._charAtlas.warmUp())},e.prototype.resize=function(e){this._scaledCellWidth=e.scaledCellWidth,this._scaledCellHeight=e.scaledCellHeight,this._scaledCharWidth=e.scaledCharWidth,this._scaledCharHeight=e.scaledCharHeight,this._scaledCharLeft=e.scaledCharLeft,this._scaledCharTop=e.scaledCharTop,this._canvas.width=e.scaledCanvasWidth,this._canvas.height=e.scaledCanvasHeight,this._canvas.style.width=e.canvasWidth+"px",this._canvas.style.height=e.canvasHeight+"px",this._alpha||this._clearAll(),this._refreshCharAtlas(this._colors)},e.prototype._fillCells=function(e,t,i,r){this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,i*this._scaledCellWidth,r*this._scaledCellHeight)},e.prototype._fillBottomLineAtCells=function(e,t,i){void 0===i&&(i=1),this._ctx.fillRect(e*this._scaledCellWidth,(t+1)*this._scaledCellHeight-window.devicePixelRatio-1,i*this._scaledCellWidth,window.devicePixelRatio)},e.prototype._fillLeftLineAtCell=function(e,t){this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,window.devicePixelRatio,this._scaledCellHeight)},e.prototype._strokeRectAtCell=function(e,t,i,r){this._ctx.lineWidth=window.devicePixelRatio,this._ctx.strokeRect(e*this._scaledCellWidth+window.devicePixelRatio/2,t*this._scaledCellHeight+window.devicePixelRatio/2,i*this._scaledCellWidth-window.devicePixelRatio,r*this._scaledCellHeight-window.devicePixelRatio)},e.prototype._clearAll=function(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))},e.prototype._clearCells=function(e,t,i,r){this._alpha?this._ctx.clearRect(e*this._scaledCellWidth,t*this._scaledCellHeight,i*this._scaledCellWidth,r*this._scaledCellHeight):(this._ctx.fillStyle=this._colors.background.css,this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,i*this._scaledCellWidth,r*this._scaledCellHeight))},e.prototype._fillCharTrueColor=function(e,t,i){this._ctx.font=this._getFont(!1,!1),this._ctx.textBaseline="middle",this._clipRow(i),this._ctx.fillText(e.getChars(),t*this._scaledCellWidth+this._scaledCharLeft,i*this._scaledCellHeight+this._scaledCharTop+this._scaledCharHeight/2)},e.prototype._drawChars=function(e,t,i){var s,o;e.isFgRGB()||e.isBgRGB()?this._drawUncachedChars(e,t,i):(e.isInverse()?(s=e.isBgDefault()?n.INVERTED_DEFAULT_COLOR:e.getBgColor(),o=e.isFgDefault()?n.INVERTED_DEFAULT_COLOR:e.getFgColor()):(o=e.isBgDefault()?r.DEFAULT_COLOR:e.getBgColor(),s=e.isFgDefault()?r.DEFAULT_COLOR:e.getFgColor()),s+=this._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&s<8&&s!==n.INVERTED_DEFAULT_COLOR?8:0,this._currentGlyphIdentifier.chars=e.getChars()||r.WHITESPACE_CELL_CHAR,this._currentGlyphIdentifier.code=e.getCode()||r.WHITESPACE_CELL_CODE,this._currentGlyphIdentifier.bg=o,this._currentGlyphIdentifier.fg=s,this._currentGlyphIdentifier.bold=!!e.isBold(),this._currentGlyphIdentifier.dim=!!e.isDim(),this._currentGlyphIdentifier.italic=!!e.isItalic(),this._charAtlas&&this._charAtlas.draw(this._ctx,this._currentGlyphIdentifier,t*this._scaledCellWidth+this._scaledCharLeft,i*this._scaledCellHeight+this._scaledCharTop)||this._drawUncachedChars(e,t,i))},e.prototype._drawUncachedChars=function(e,t,i){if(this._ctx.save(),this._ctx.font=this._getFont(!!e.isBold(),!!e.isItalic()),this._ctx.textBaseline="middle",e.isInverse())e.isBgDefault()?this._ctx.fillStyle=this._colors.background.css:e.isBgRGB()?this._ctx.fillStyle="rgb("+o.AttributeData.toColorRGB(e.getBgColor()).join(",")+")":this._ctx.fillStyle=this._colors.ansi[e.getBgColor()].css;else if(e.isFgDefault())this._ctx.fillStyle=this._colors.foreground.css;else if(e.isFgRGB())this._ctx.fillStyle="rgb("+o.AttributeData.toColorRGB(e.getFgColor()).join(",")+")";else{var r=e.getFgColor();this._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&r<8&&(r+=8),this._ctx.fillStyle=this._colors.ansi[r].css}this._clipRow(i),e.isDim()&&(this._ctx.globalAlpha=n.DIM_OPACITY),this._ctx.fillText(e.getChars(),t*this._scaledCellWidth+this._scaledCharLeft,i*this._scaledCellHeight+this._scaledCharTop+this._scaledCharHeight/2),this._ctx.restore()},e.prototype._clipRow=function(e){this._ctx.beginPath(),this._ctx.rect(0,e*this._scaledCellHeight,this._bufferService.cols*this._scaledCellWidth,this._scaledCellHeight),this._ctx.clip()},e.prototype._getFont=function(e,t){return(t?"italic":"")+" "+(e?this._optionsService.options.fontWeightBold:this._optionsService.options.fontWeight)+" "+this._optionsService.options.fontSize*window.devicePixelRatio+"px "+this._optionsService.options.fontFamily},e}();t.BaseRenderLayer=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="di$target",n="di$dependencies";function s(e,t,i){t[r]===t?t[n].push({id:e,index:i}):(t[n]=[{id:e,index:i}],t[r]=t)}t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[n]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);var i=function(e,t,r){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");s(i,e,r)};return i.toString=function(){return e},t.serviceRegistry.set(e,i),i}},function(e,t,i){"use strict";function r(e,t,i,r){if(void 0===i&&(i=0),void 0===r&&(r=e.length),i>=e.length)return e;i=(e.length+i)%e.length,r=r>=e.length?e.length:(e.length+r)%e.length;for(var n=i;n<r;++n)e[n]=t;return e}Object.defineProperty(t,"__esModule",{value:!0}),t.fill=function(e,t,i,n){return e.fill?e.fill(t,i,n):r(e,t,i,n)},t.fillFallback=r,t.concat=function(e,t){var i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(8),n=i(3),s=i(4),o=i(6),a=3;t.DEFAULT_ATTR_DATA=Object.freeze(new o.AttributeData);var c=function(){function e(e,t,i){void 0===i&&(i=!1),this.isWrapped=i,this._combined={},this._data=new Uint32Array(e*a);for(var r=t||s.CellData.fromCharData([0,n.NULL_CELL_CHAR,n.NULL_CELL_WIDTH,n.NULL_CELL_CODE]),o=0;o<e;++o)this.setCell(o,r);this.length=e}return e.prototype.get=function(e){var t=this._data[e*a+0],i=2097151&t;return[this._data[e*a+1],2097152&t?this._combined[e]:i?r.stringFromCodePoint(i):"",t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]},e.prototype.set=function(e,t){this._data[e*a+1]=t[n.CHAR_DATA_ATTR_INDEX],t[n.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[e*a+0]=2097152|e|t[n.CHAR_DATA_WIDTH_INDEX]<<22):this._data[e*a+0]=t[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[n.CHAR_DATA_WIDTH_INDEX]<<22},e.prototype.getWidth=function(e){return this._data[e*a+0]>>22},e.prototype.hasWidth=function(e){return 12582912&this._data[e*a+0]},e.prototype.getFg=function(e){return this._data[e*a+1]},e.prototype.getBg=function(e){return this._data[e*a+2]},e.prototype.hasContent=function(e){return 4194303&this._data[e*a+0]},e.prototype.getCodePoint=function(e){var t=this._data[e*a+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t},e.prototype.isCombined=function(e){return 2097152&this._data[e*a+0]},e.prototype.getString=function(e){var t=this._data[e*a+0];return 2097152&t?this._combined[e]:2097151&t?r.stringFromCodePoint(2097151&t):""},e.prototype.loadCell=function(e,t){var i=e*a;return t.content=this._data[i+0],t.fg=this._data[i+1],t.bg=this._data[i+2],2097152&t.content&&(t.combinedData=this._combined[e]),t},e.prototype.setCell=function(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),this._data[e*a+0]=t.content,this._data[e*a+1]=t.fg,this._data[e*a+2]=t.bg},e.prototype.setCellFromCodePoint=function(e,t,i,r,n){this._data[e*a+0]=t|i<<22,this._data[e*a+1]=r,this._data[e*a+2]=n},e.prototype.addCodepointToCell=function(e,t){var i=this._data[e*a+0];2097152&i?this._combined[e]+=r.stringFromCodePoint(t):(2097151&i?(this._combined[e]=r.stringFromCodePoint(2097151&i)+r.stringFromCodePoint(t),i&=-2097152,i|=2097152):i=t|1<<22,this._data[e*a+0]=i)},e.prototype.insertCells=function(e,t,i){if(e%=this.length,t<this.length-e){for(var r=new s.CellData,n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(n=0;n<t;++n)this.setCell(e+n,i)}else for(n=e;n<this.length;++n)this.setCell(n,i)},e.prototype.deleteCells=function(e,t,i){if(e%=this.length,t<this.length-e){for(var r=new s.CellData,n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(n=this.length-t;n<this.length;++n)this.setCell(n,i)}else for(n=e;n<this.length;++n)this.setCell(n,i)},e.prototype.replaceCells=function(e,t,i){for(;e<t&&e<this.length;)this.setCell(e++,i)},e.prototype.resize=function(e,t){if(e!==this.length){if(e>this.length){var i=new Uint32Array(e*a);this.length&&(e*a<this._data.length?i.set(this._data.subarray(0,e*a)):i.set(this._data)),this._data=i;for(var r=this.length;r<e;++r)this.setCell(r,t)}else if(e){(i=new Uint32Array(e*a)).set(this._data.subarray(0,e*a)),this._data=i;var n=Object.keys(this._combined);for(r=0;r<n.length;r++){var s=parseInt(n[r],10);s>=e&&delete this._combined[s]}}else this._data=new Uint32Array(0),this._combined={};this.length=e}},e.prototype.fill=function(e){this._combined={};for(var t=0;t<this.length;++t)this.setCell(t,e)},e.prototype.copyFrom=function(e){for(var t in this.length!==e.length?this._data=new Uint32Array(e._data):this._data.set(e._data),this.length=e.length,this._combined={},e._combined)this._combined[t]=e._combined[t];this.isWrapped=e.isWrapped},e.prototype.clone=function(){var t=new e(0);for(var i in t._data=new Uint32Array(this._data),t.length=this.length,this._combined)t._combined[i]=this._combined[i];return t.isWrapped=this.isWrapped,t},e.prototype.getTrimmedLength=function(){for(var e=this.length-1;e>=0;--e)if(4194303&this._data[e*a+0])return e+(this._data[e*a+0]>>22);return 0},e.prototype.copyCellsFrom=function(e,t,i,r,n){var s=e._data;if(n)for(var o=r-1;o>=0;o--)for(var c=0;c<a;c++)this._data[(i+o)*a+c]=s[(t+o)*a+c];else for(o=0;o<r;o++)for(c=0;c<a;c++)this._data[(i+o)*a+c]=s[(t+o)*a+c];var l=Object.keys(e._combined);for(c=0;c<l.length;c++){var h=parseInt(l[c],10);h>=t&&(this._combined[h-t+i]=e._combined[h])}},e.prototype.translateToString=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=0),void 0===i&&(i=this.length),e&&(i=Math.min(i,this.getTrimmedLength()));for(var s="";t<i;){var o=this._data[t*a+0],c=2097151&o;s+=2097152&o?this._combined[t]:c?r.stringFromCodePoint(c):n.WHITESPACE_CELL_CHAR,t+=o>>22||1}return s},e}();t.BufferLine=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.promptLabel="Terminal input",t.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":"◆",a:"▒",b:"\t",c:"\f",d:"\r",e:"\n",f:"°",g:"±",h:"␤",i:"\v",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},t.CHARSETS.A={"#":"£"},t.CHARSETS.B=null,t.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},t.CHARSETS.C=t.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},t.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},t.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},t.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},t.CHARSETS.E=t.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},t.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},t.CHARSETS.H=t.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(14);t.wcwidth=function(e){var t=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],i=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];var n=0|e.control,s=new Uint8Array(65536);r.fill(s,1),s[0]=e.nul,r.fill(s,e.control,1,32),r.fill(s,e.control,127,160),r.fill(s,2,4352,4448),s[9001]=2,s[9002]=2,r.fill(s,2,11904,42192),s[12351]=1,r.fill(s,2,44032,55204),r.fill(s,2,63744,64256),r.fill(s,2,65040,65050),r.fill(s,2,65072,65136),r.fill(s,2,65280,65377),r.fill(s,2,65504,65511);for(var o=0;o<t.length;++o)r.fill(s,0,t[o][0],t[o][1]+1);return function(e){return e<32?0|n:e<127?1:e<65536?s[e]:function(e,t){var i,r=0,n=t.length-1;if(e<t[0][0]||e>t[n][1])return!1;for(;n>=r;)if(e>t[i=r+n>>1][1])r=i+1;else{if(!(e<t[i][0]))return!0;n=i-1}return!1}(t=e,i)?0:t>=131072&&t<=196605||t>=196608&&t<=262141?2:1;var t}}({nul:0,control:0}),t.getStringCellWidth=function(e){for(var i=0,r=e.length,n=0;n<r;++n){var s=e.charCodeAt(n);if(55296<=s&&s<=56319){if(++n>=r)return i+t.wcwidth(s);var o=e.charCodeAt(n);56320<=o&&o<=57343?s=1024*(s-55296)+o-56320+65536:i+=t.wcwidth(o)}i+=t.wcwidth(s)}return i}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=256,n=function(){function e(e,t){if(void 0===e&&(e=32),void 0===t&&(t=32),this.maxLength=e,this.maxSubParamsLength=t,t>r)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}return e.fromArray=function(t){var i=new e;if(!t.length)return i;for(var r=t[0]instanceof Array?1:0;r<t.length;++r){var n=t[r];if(n instanceof Array)for(var s=0;s<n.length;++s)i.addSubParam(n[s]);else i.addParam(n)}return i},e.prototype.clone=function(){var t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t},e.prototype.toArray=function(){for(var e=[],t=0;t<this.length;++t){e.push(this.params[t]);var i=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,r))}return e},e.prototype.reset=function(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1},e.prototype.addParam=function(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>2147483647?2147483647:e}},e.prototype.addSubParam=function(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>2147483647?2147483647:e,this._subParamsIdx[this.length-1]++}},e.prototype.hasSubParams=function(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0},e.prototype.getSubParams=function(e){var t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null},e.prototype.getSubParamsAll=function(){for(var e={},t=0;t<this.length;++t){var i=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-i>0&&(e[t]=this._subParams.slice(i,r))}return e},e.prototype.addDigit=function(e){var t;if(!(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)){var i=this._digitIsSub?this._subParams:this.params,r=i[t-1];i[t-1]=~r?Math.min(10*r+e,2147483647):e}},e}();t.Params=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(21),n=i(8),s=function(){function e(){this._state=0,this._id=-1,this._handlers=Object.create(null),this._handlerFb=function(){}}return e.prototype.addHandler=function(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);var i=this._handlers[e];return i.push(t),{dispose:function(){var e=i.indexOf(t);-1!==e&&i.splice(e,1)}}},e.prototype.setHandler=function(e,t){this._handlers[e]=[t]},e.prototype.clearHandler=function(e){this._handlers[e]&&delete this._handlers[e]},e.prototype.setHandlerFallback=function(e){this._handlerFb=e},e.prototype.dispose=function(){this._handlers=Object.create(null),this._handlerFb=function(){}},e.prototype.reset=function(){2===this._state&&this.end(!1),this._id=-1,this._state=0},e.prototype._start=function(){var e=this._handlers[this._id];if(e)for(var t=e.length-1;t>=0;t--)e[t].start();else this._handlerFb(this._id,"START")},e.prototype._put=function(e,t,i){var r=this._handlers[this._id];if(r)for(var s=r.length-1;s>=0;s--)r[s].put(e,t,i);else this._handlerFb(this._id,"PUT",n.utf32ToString(e,t,i))},e.prototype._end=function(e){var t=this._handlers[this._id];if(t){for(var i=t.length-1;i>=0&&!1===t[i].end(e);i--);for(i--;i>=0;i--)t[i].end(!1)}else this._handlerFb(this._id,"END",e)},e.prototype.start=function(){this.reset(),this._id=-1,this._state=1},e.prototype.put=function(e,t,i){if(3!==this._state){if(1===this._state)for(;t<i;){var r=e[t++];if(59===r){this._state=2,this._start();break}if(r<48||57<r)return void(this._state=3);-1===this._id&&(this._id=0),this._id=10*this._id+r-48}2===this._state&&i-t>0&&this._put(e,t,i)}},e.prototype.end=function(e){0!==this._state&&(3!==this._state&&(1===this._state&&this._start(),this._end(e)),this._id=-1,this._state=0)},e}();t.OscParser=s;var o=function(){function e(e){this._handler=e,this._data="",this._hitLimit=!1}return e.prototype.start=function(){this._data="",this._hitLimit=!1},e.prototype.put=function(e,t,i){this._hitLimit||(this._data+=n.utf32ToString(e,t,i),this._data.length>r.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))},e.prototype.end=function(e){var t;return this._hitLimit?t=!1:e&&(t=this._handler(this._data)),this._data="",this._hitLimit=!1,t},e}();t.OscHandler=o},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=1e7},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(8),n=i(19),s=i(21),o=[],a=function(){function e(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=function(){}}return e.prototype.dispose=function(){this._handlers=Object.create(null),this._handlerFb=function(){}},e.prototype.addHandler=function(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);var i=this._handlers[e];return i.push(t),{dispose:function(){var e=i.indexOf(t);-1!==e&&i.splice(e,1)}}},e.prototype.setHandler=function(e,t){this._handlers[e]=[t]},e.prototype.clearHandler=function(e){this._handlers[e]&&delete this._handlers[e]},e.prototype.setHandlerFallback=function(e){this._handlerFb=e},e.prototype.reset=function(){this._active.length&&this.unhook(!1),this._active=o,this._ident=0},e.prototype.hook=function(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(var i=this._active.length-1;i>=0;i--)this._active[i].hook(t);else this._handlerFb(this._ident,"HOOK",t)},e.prototype.put=function(e,t,i){if(this._active.length)for(var n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i);else this._handlerFb(this._ident,"PUT",r.utf32ToString(e,t,i))},e.prototype.unhook=function(e){if(this._active.length){for(var t=this._active.length-1;t>=0&&!1===this._active[t].unhook(e);t--);for(t--;t>=0;t--)this._active[t].unhook(!1)}else this._handlerFb(this._ident,"UNHOOK",e);this._active=o,this._ident=0},e}();t.DcsParser=a;var c=function(){function e(e){this._handler=e,this._data="",this._hitLimit=!1}return e.prototype.hook=function(e){this._params=e.clone(),this._data="",this._hitLimit=!1},e.prototype.put=function(e,t,i){this._hitLimit||(this._data+=r.utf32ToString(e,t,i),this._data.length>s.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))},e.prototype.unhook=function(e){var t;return this._hitLimit?t=!1:e&&(t=this._handler(this._data,this._params?this._params:new n.Params)),this._params=void 0,this._data="",this._hitLimit=!1,t},e}();t.DcsHandler=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(24),n=i(42),s=[];t.acquireCharAtlas=function(e,t,i,o,a){for(var c=r.generateConfig(o,a,e,i),l=0;l<s.length;l++){var h=(u=s[l]).ownedBy.indexOf(t);if(h>=0){if(r.configEquals(u.config,c))return u.atlas;1===u.ownedBy.length?(u.atlas.dispose(),s.splice(l,1)):u.ownedBy.splice(h,1);break}}for(l=0;l<s.length;l++){var u=s[l];if(r.configEquals(u.config,c))return u.ownedBy.push(t),u.atlas}var f={atlas:new n.DynamicCharAtlas(document,c),config:c,ownedBy:[t]};return s.push(f),f.atlas},t.removeTerminalFromCache=function(e){for(var t=0;t<s.length;t++){var i=s[t].ownedBy.indexOf(e);if(-1!==i){1===s[t].ownedBy.length?(s[t].atlas.dispose(),s.splice(t,1)):s[t].ownedBy.splice(i,1);break}}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(3);t.generateConfig=function(e,t,i,r){var n={foreground:r.foreground,background:r.background,cursor:void 0,cursorAccent:void 0,selection:void 0,ansi:r.ansi.slice(0,16)};return{devicePixelRatio:window.devicePixelRatio,scaledCharWidth:e,scaledCharHeight:t,fontFamily:i.fontFamily,fontSize:i.fontSize,fontWeight:i.fontWeight,fontWeightBold:i.fontWeightBold,allowTransparency:i.allowTransparency,colors:n}},t.configEquals=function(e,t){for(var i=0;i<e.colors.ansi.length;i++)if(e.colors.ansi[i].rgba!==t.colors.ansi[i].rgba)return!1;return e.devicePixelRatio===t.devicePixelRatio&&e.fontFamily===t.fontFamily&&e.fontSize===t.fontSize&&e.fontWeight===t.fontWeight&&e.fontWeightBold===t.fontWeightBold&&e.allowTransparency===t.allowTransparency&&e.scaledCharWidth===t.scaledCharWidth&&e.scaledCharHeight===t.scaledCharHeight&&e.colors.foreground===t.colors.foreground&&e.colors.background===t.colors.background},t.is256Color=function(e){return e<r.DEFAULT_COLOR}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=c("#ffffff"),n=c("#000000"),s=c("#ffffff"),o=c("#000000"),a={css:"rgba(255, 255, 255, 0.3)",rgba:4294967159};function c(e){return{css:e,rgba:parseInt(e.slice(1),16)<<8|255}}function l(e){var t=e.toString(16);return t.length<2?"0"+t:t}t.DEFAULT_ANSI_COLORS=function(){for(var e=[c("#2e3436"),c("#cc0000"),c("#4e9a06"),c("#c4a000"),c("#3465a4"),c("#75507b"),c("#06989a"),c("#d3d7cf"),c("#555753"),c("#ef2929"),c("#8ae234"),c("#fce94f"),c("#729fcf"),c("#ad7fa8"),c("#34e2e2"),c("#eeeeec")],t=[0,95,135,175,215,255],i=0;i<216;i++){var r=t[i/36%6|0],n=t[i/6%6|0],s=t[i%6];e.push({css:"#"+l(r)+l(n)+l(s),rgba:(r<<24|n<<16|s<<8|255)>>>0})}for(i=0;i<24;i++){var o=8+10*i,a=l(o);e.push({css:"#"+a+a+a,rgba:(o<<24|o<<16|o<<8|255)>>>0})}return e}();var h=function(){function e(e,i){this.allowTransparency=i;var c=e.createElement("canvas");c.width=1,c.height=1;var l=c.getContext("2d");if(!l)throw new Error("Could not get rendering context");this._ctx=l,this._ctx.globalCompositeOperation="copy",this._litmusColor=this._ctx.createLinearGradient(0,0,1,1),this.colors={foreground:r,background:n,cursor:s,cursorAccent:o,selection:a,ansi:t.DEFAULT_ANSI_COLORS.slice()}}return e.prototype.setTheme=function(e){void 0===e&&(e={}),this.colors.foreground=this._parseColor(e.foreground,r),this.colors.background=this._parseColor(e.background,n),this.colors.cursor=this._parseColor(e.cursor,s,!0),this.colors.cursorAccent=this._parseColor(e.cursorAccent,o,!0),this.colors.selection=this._parseColor(e.selection,a,!0),this.colors.ansi[0]=this._parseColor(e.black,t.DEFAULT_ANSI_COLORS[0]),this.colors.ansi[1]=this._parseColor(e.red,t.DEFAULT_ANSI_COLORS[1]),this.colors.ansi[2]=this._parseColor(e.green,t.DEFAULT_ANSI_COLORS[2]),this.colors.ansi[3]=this._parseColor(e.yellow,t.DEFAULT_ANSI_COLORS[3]),this.colors.ansi[4]=this._parseColor(e.blue,t.DEFAULT_ANSI_COLORS[4]),this.colors.ansi[5]=this._parseColor(e.magenta,t.DEFAULT_ANSI_COLORS[5]),this.colors.ansi[6]=this._parseColor(e.cyan,t.DEFAULT_ANSI_COLORS[6]),this.colors.ansi[7]=this._parseColor(e.white,t.DEFAULT_ANSI_COLORS[7]),this.colors.ansi[8]=this._parseColor(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),this.colors.ansi[9]=this._parseColor(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),this.colors.ansi[10]=this._parseColor(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),this.colors.ansi[11]=this._parseColor(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),this.colors.ansi[12]=this._parseColor(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),this.colors.ansi[13]=this._parseColor(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),this.colors.ansi[14]=this._parseColor(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),this.colors.ansi[15]=this._parseColor(e.brightWhite,t.DEFAULT_ANSI_COLORS[15])},e.prototype._parseColor=function(e,t,i){if(void 0===i&&(i=this.allowTransparency),void 0===e)return t;if(this._ctx.fillStyle=this._litmusColor,this._ctx.fillStyle=e,"string"!=typeof this._ctx.fillStyle)return console.warn("Color: "+e+" is invalid using fallback "+t.css),t;this._ctx.fillRect(0,0,1,1);var r=this._ctx.getImageData(0,0,1,1).data;return i||255===r[3]?{css:e,rgba:(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0}:(console.warn("Color: "+e+" is using transparency, but allowTransparency is false. Using fallback "+t.css+"."),t)},e}();t.ColorManager=h},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.throwIfFalsy=function(e){if(!e)throw new Error("value must not be falsy");return e}},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(6),o=i(3),a=i(4),c=function(e){function t(t,i,r){var n=e.call(this)||this;return n.content=0,n.combinedData="",n.fg=t.fg,n.bg=t.bg,n.combinedData=i,n._width=r,n}return n(t,e),t.prototype.isCombined=function(){return 2097152},t.prototype.getWidth=function(){return this._width},t.prototype.getChars=function(){return this.combinedData},t.prototype.getCode=function(){return 2097151},t.prototype.setFromCharData=function(e){throw new Error("not implemented")},t.prototype.getAsCharData=function(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]},t}(s.AttributeData);t.JoinedCellData=c;var l=function(){function e(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new a.CellData}return e.prototype.registerCharacterJoiner=function(e){var t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id},e.prototype.deregisterCharacterJoiner=function(e){for(var t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1},e.prototype.getJoinedCharacters=function(e){if(0===this._characterJoiners.length)return[];var t=this._bufferService.buffer.lines.get(e);if(!t||0===t.length)return[];for(var i=[],r=t.translateToString(!0),n=0,s=0,a=0,c=t.getFg(0),l=t.getBg(0),h=0;h<t.getTrimmedLength();h++)if(t.loadCell(h,this._workCell),0!==this._workCell.getWidth()){if(this._workCell.fg!==c||this._workCell.bg!==l){if(h-n>1)for(var u=this._getJoinedRanges(r,a,s,t,n),f=0;f<u.length;f++)i.push(u[f]);n=h,a=s,c=this._workCell.fg,l=this._workCell.bg}s+=this._workCell.getChars().length||o.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-n>1)for(u=this._getJoinedRanges(r,a,s,t,n),f=0;f<u.length;f++)i.push(u[f]);return i},e.prototype._getJoinedRanges=function(t,i,r,n,s){for(var o=t.substring(i,r),a=this._characterJoiners[0].handler(o),c=1;c<this._characterJoiners.length;c++)for(var l=this._characterJoiners[c].handler(o),h=0;h<l.length;h++)e._mergeRanges(a,l[h]);return this._stringRangesToCellRanges(a,n,s),a},e.prototype._stringRangesToCellRanges=function(e,t,i){var r=0,n=!1,s=0,a=e[r];if(a){for(var c=i;c<this._bufferService.cols;c++){var l=t.getWidth(c),h=t.getString(c).length||o.WHITESPACE_CELL_CHAR.length;if(0!==l){if(!n&&a[0]<=s&&(a[0]=c,n=!0),a[1]<=s){if(a[1]=c,!(a=e[++r]))break;a[0]<=s?(a[0]=c,n=!0):n=!1}s+=h}}a&&(a[1]=this._bufferService.cols)}},e._mergeRanges=function(e,t){for(var i=!1,r=0;r<e.length;r++){var n=e[r];if(i){if(t[1]<=n[0])return e[r-1][1]=t[1],e;if(t[1]<=n[1])return e[r-1][1]=Math.max(t[1],n[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=n[0])return e.splice(r,0,t),e;if(t[1]<=n[1])return n[0]=Math.min(t[0],n[0]),e;t[0]<n[1]&&(n[0]=Math.min(t[0],n[0]),i=!0)}}return i?e[e.length-1][1]=t[1]:e.push(t),e},e}();t.CharacterJoinerRegistry=l},function(e,t,i){"use strict";function r(e,t){var i=t.getBoundingClientRect();return[e.clientX-i.left,e.clientY-i.top]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoordsRelativeToElement=r,t.getCoords=function(e,t,i,n,s,o,a,c){if(s){var l=r(e,t);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/a),l[0]=Math.min(Math.max(l[0],1),i+(c?1:0)),l[1]=Math.min(Math.max(l[1],1),n),l}},t.getRawByteCoords=function(e){if(e)return{x:e[0]+32,y:e[1]+32}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this._renderCallback=e}return e.prototype.dispose=function(){this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)},e.prototype.refresh=function(e,t,i){var r=this;this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,this._animationFrame||(this._animationFrame=window.requestAnimationFrame(function(){return r._innerRefresh()}))},e.prototype._innerRefresh=function(){void 0!==this._rowStart&&void 0!==this._rowEnd&&void 0!==this._rowCount&&(this._rowStart=Math.max(this._rowStart,0),this._rowEnd=Math.min(this._rowEnd,this._rowCount-1),this._renderCallback(this._rowStart,this._rowEnd),this._rowStart=void 0,this._rowEnd=void 0,this._animationFrame=void 0)},e}();t.RenderDebouncer=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._currentDevicePixelRatio=window.devicePixelRatio,t}return n(t,e),t.prototype.setListener=function(e){var t=this;this._listener&&this.clearListener(),this._listener=e,this._outerListener=function(){t._listener&&(t._listener(window.devicePixelRatio,t._currentDevicePixelRatio),t._updateDpr())},this._updateDpr()},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.clearListener()},t.prototype._updateDpr=function(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._currentDevicePixelRatio=window.devicePixelRatio,this._resolutionMediaMatchList=window.matchMedia("screen and (resolution: "+window.devicePixelRatio+"dppx)"),this._resolutionMediaMatchList.addListener(this._outerListener))},t.prototype.clearListener=function(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)},t}(i(2).Disposable);t.ScreenDprMonitor=s},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=function e(t,i){if(void 0===i&&(i=5),"object"!=typeof t)return t;var r=Array.isArray(t)?[]:{};for(var n in t)r[n]=i<=1?t[n]:t[n]?e(t[n],i-1):t[n];return r}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(33),n=i(16),s=i(75),o=function(){function e(e){this._core=new r.Terminal(e),this._addonManager=new s.AddonManager}return Object.defineProperty(e.prototype,"onCursorMove",{get:function(){return this._core.onCursorMove},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onLineFeed",{get:function(){return this._core.onLineFeed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onSelectionChange",{get:function(){return this._core.onSelectionChange},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onData",{get:function(){return this._core.onData},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onTitleChange",{get:function(){return this._core.onTitleChange},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onScroll",{get:function(){return this._core.onScroll},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onKey",{get:function(){return this._core.onKey},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onRender",{get:function(){return this._core.onRender},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onResize",{get:function(){return this._core.onResize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"element",{get:function(){return this._core.element},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parser",{get:function(){return this._parser||(this._parser=new h(this._core)),this._parser},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textarea",{get:function(){return this._core.textarea},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rows",{get:function(){return this._core.rows},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cols",{get:function(){return this._core.cols},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"buffer",{get:function(){return new a(this._core.buffer)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"markers",{get:function(){return this._core.markers},enumerable:!0,configurable:!0}),e.prototype.blur=function(){this._core.blur()},e.prototype.focus=function(){this._core.focus()},e.prototype.resize=function(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)},e.prototype.open=function(e){this._core.open(e)},e.prototype.attachCustomKeyEventHandler=function(e){this._core.attachCustomKeyEventHandler(e)},e.prototype.registerLinkMatcher=function(e,t,i){return this._core.registerLinkMatcher(e,t,i)},e.prototype.deregisterLinkMatcher=function(e){this._core.deregisterLinkMatcher(e)},e.prototype.registerCharacterJoiner=function(e){return this._core.registerCharacterJoiner(e)},e.prototype.deregisterCharacterJoiner=function(e){this._core.deregisterCharacterJoiner(e)},e.prototype.addMarker=function(e){return this._verifyIntegers(e),this._core.addMarker(e)},e.prototype.hasSelection=function(){return this._core.hasSelection()},e.prototype.select=function(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)},e.prototype.getSelection=function(){return this._core.getSelection()},e.prototype.getSelectionPosition=function(){return this._core.getSelectionPosition()},e.prototype.clearSelection=function(){this._core.clearSelection()},e.prototype.selectAll=function(){this._core.selectAll()},e.prototype.selectLines=function(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)},e.prototype.dispose=function(){this._addonManager.dispose(),this._core.dispose()},e.prototype.scrollLines=function(e){this._verifyIntegers(e),this._core.scrollLines(e)},e.prototype.scrollPages=function(e){this._verifyIntegers(e),this._core.scrollPages(e)},e.prototype.scrollToTop=function(){this._core.scrollToTop()},e.prototype.scrollToBottom=function(){this._core.scrollToBottom()},e.prototype.scrollToLine=function(e){this._verifyIntegers(e),this._core.scrollToLine(e)},e.prototype.clear=function(){this._core.clear()},e.prototype.write=function(e,t){this._core.write(e,t)},e.prototype.writeUtf8=function(e,t){this._core.write(e,t)},e.prototype.writeln=function(e,t){this._core.write(e),this._core.write("\r\n",t)},e.prototype.paste=function(e){this._core.paste(e)},e.prototype.getOption=function(e){return this._core.optionsService.getOption(e)},e.prototype.setOption=function(e,t){this._core.optionsService.setOption(e,t)},e.prototype.refresh=function(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)},e.prototype.reset=function(){this._core.reset()},e.prototype.loadAddon=function(e){return this._addonManager.loadAddon(this,e)},Object.defineProperty(e,"strings",{get:function(){return n},enumerable:!0,configurable:!0}),e.prototype._verifyIntegers=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];e.forEach(function(e){if(e===1/0||isNaN(e)||e%1!=0)throw new Error("This API only accepts integers")})},e}();t.Terminal=o;var a=function(){function e(e){this._buffer=e}return Object.defineProperty(e.prototype,"cursorY",{get:function(){return this._buffer.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cursorX",{get:function(){return this._buffer.x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"viewportY",{get:function(){return this._buffer.ydisp},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"baseY",{get:function(){return this._buffer.ybase},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return this._buffer.lines.length},enumerable:!0,configurable:!0}),e.prototype.getLine=function(e){var t=this._buffer.lines.get(e);if(t)return new c(t)},e}(),c=function(){function e(e){this._line=e}return Object.defineProperty(e.prototype,"isWrapped",{get:function(){return this._line.isWrapped},enumerable:!0,configurable:!0}),e.prototype.getCell=function(e){if(!(e<0||e>=this._line.length))return new l(this._line,e)},e.prototype.translateToString=function(e,t,i){return this._line.translateToString(e,t,i)},e}(),l=function(){function e(e,t){this._line=e,this._x=t}return Object.defineProperty(e.prototype,"char",{get:function(){return this._line.getString(this._x)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this._line.getWidth(this._x)},enumerable:!0,configurable:!0}),e}(),h=function(){function e(e){this._core=e}return e.prototype.addCsiHandler=function(e,t){return this._core.addCsiHandler(e,function(e){return t(e.toArray())})},e.prototype.addDcsHandler=function(e,t){return this._core.addDcsHandler(e,function(e,i){return t(e,i.toArray())})},e.prototype.addEscHandler=function(e,t){return this._core.addEscHandler(e,t)},e.prototype.addOscHandler=function(e,t){return this._core.addOscHandler(e,t)},e}()},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(34),o=i(35),a=i(36),c=i(11),l=i(37),h=i(39),u=i(48),f=i(49),_=i(10),d=i(7),p=i(16),v=i(52),g=i(53),y=i(54),m=i(55),b=i(57),C=i(1),S=i(15),w=i(58),E=i(25),L=i(59),A=i(0),x=i(60),k=i(5),D=i(61),T=i(62),R=i(2),M=i(68),O=i(69),P=i(70),H=i(71),I=i(72),B=i(73),F=i(74),j="undefined"!=typeof window?window.document:null,W=function(e){function t(t){void 0===t&&(t={});var i=e.call(this)||this;return i.browser=_,i.mouseEvents=0,i._keyDownHandled=!1,i._blankLine=null,i._onCursorMove=new C.EventEmitter,i._onData=new C.EventEmitter,i._onKey=new C.EventEmitter,i._onLineFeed=new C.EventEmitter,i._onRender=new C.EventEmitter,i._onResize=new C.EventEmitter,i._onScroll=new C.EventEmitter,i._onSelectionChange=new C.EventEmitter,i._onTitleChange=new C.EventEmitter,i._onFocus=new C.EventEmitter,i._onBlur=new C.EventEmitter,i.onA11yCharEmitter=new C.EventEmitter,i.onA11yTabEmitter=new C.EventEmitter,i._instantiationService=new I.InstantiationService,i.optionsService=new x.OptionsService(t),i._instantiationService.setService(A.IOptionsService,i.optionsService),i._bufferService=i._instantiationService.createInstance(T.BufferService),i._instantiationService.setService(A.IBufferService,i._bufferService),i._logService=i._instantiationService.createInstance(P.LogService),i._instantiationService.setService(A.ILogService,i._logService),i._coreService=i._instantiationService.createInstance(O.CoreService,function(){return i.scrollToBottom()}),i._instantiationService.setService(A.ICoreService,i._coreService),i._coreService.onData(function(e){return i._onData.fire(e)}),i._coreMouseService=i._instantiationService.createInstance(B.CoreMouseService),i._instantiationService.setService(A.ICoreMouseService,i._coreMouseService),i._dirtyRowService=i._instantiationService.createInstance(H.DirtyRowService),i._instantiationService.setService(A.IDirtyRowService,i._dirtyRowService),i._setupOptionsListeners(),i._setup(),i._writeBuffer=new F.WriteBuffer(function(e){return i._inputHandler.parse(e)}),i}return n(t,e),Object.defineProperty(t.prototype,"options",{get:function(){return this.optionsService.options},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cols",{get:function(){return this._bufferService.cols},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rows",{get:function(){return this._bufferService.rows},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onCursorMove",{get:function(){return this._onCursorMove.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onData",{get:function(){return this._onData.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onKey",{get:function(){return this._onKey.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onLineFeed",{get:function(){return this._onLineFeed.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onRender",{get:function(){return this._onRender.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onResize",{get:function(){return this._onResize.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onSelectionChange",{get:function(){return this._onSelectionChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onTitleChange",{get:function(){return this._onTitleChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onFocus",{get:function(){return this._onFocus.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBlur",{get:function(){return this._onBlur.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onA11yChar",{get:function(){return this.onA11yCharEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onA11yTab",{get:function(){return this.onA11yTabEmitter.event},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this._isDisposed||(e.prototype.dispose.call(this),this._windowsMode&&(this._windowsMode.dispose(),this._windowsMode=void 0),this._renderService&&this._renderService.dispose(),this._customKeyEventHandler=null,this.write=function(){},this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element))},t.prototype._setup=function(){var e=this;this._parent=j?j.body:null,this.cursorState=0,this.cursorHidden=!1,this._customKeyEventHandler=null,this.applicationKeypad=!1,this.originMode=!1,this.insertMode=!1,this.wraparoundMode=!0,this.bracketedPasteMode=!1,this.charset=null,this.gcharset=null,this.glevel=0,this.charsets=[null],this.curAttrData=S.DEFAULT_ATTR_DATA.clone(),this._eraseAttrData=S.DEFAULT_ATTR_DATA.clone(),this.params=[],this.currentParam=0,this._userScrolling=!1,this._inputHandler=new l.InputHandler(this,this._bufferService,this._coreService,this._dirtyRowService,this._logService,this.optionsService,this._coreMouseService),this._inputHandler.onCursorMove(function(){return e._onCursorMove.fire()}),this._inputHandler.onLineFeed(function(){return e._onLineFeed.fire()}),this.register(this._inputHandler),this.linkifier=this.linkifier||new u.Linkifier(this._bufferService,this._logService),this.options.windowsMode&&(this._windowsMode=w.applyWindowsMode(this))},Object.defineProperty(t.prototype,"buffer",{get:function(){return this.buffers.active},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buffers",{get:function(){return this._bufferService.buffers},enumerable:!0,configurable:!0}),t.prototype.eraseAttrData=function(){return this._eraseAttrData.bg&=-67108864,this._eraseAttrData.bg|=67108863&this.curAttrData.bg,this._eraseAttrData},t.prototype.focus=function(){this.textarea&&this.textarea.focus({preventScroll:!0})},Object.defineProperty(t.prototype,"isFocused",{get:function(){return j.activeElement===this.textarea&&j.hasFocus()},enumerable:!0,configurable:!0}),t.prototype._setupOptionsListeners=function(){var e=this;this.optionsService.onOptionChange(function(t){switch(t){case"fontFamily":case"fontSize":e._renderService&&e._renderService.clear(),e._charSizeService&&e._charSizeService.measure();break;case"drawBoldTextInBrightColors":case"letterSpacing":case"lineHeight":case"fontWeight":case"fontWeightBold":e._renderService&&(e._renderService.clear(),e._renderService.onResize(e.cols,e.rows),e.refresh(0,e.rows-1));break;case"rendererType":e._renderService&&(e._renderService.setRenderer(e._createRenderer()),e._renderService.onResize(e.cols,e.rows));break;case"scrollback":e.buffers.resize(e.cols,e.rows),e.viewport&&e.viewport.syncScrollArea();break;case"screenReaderMode":e.optionsService.options.screenReaderMode?!e._accessibilityManager&&e._renderService&&(e._accessibilityManager=new y.AccessibilityManager(e,e._renderService)):e._accessibilityManager&&(e._accessibilityManager.dispose(),e._accessibilityManager=null);break;case"tabStopWidth":e.buffers.setupTabStops();break;case"theme":e._setTheme(e.optionsService.options.theme);break;case"windowsMode":e.optionsService.options.windowsMode?e._windowsMode||(e._windowsMode=w.applyWindowsMode(e)):e._windowsMode&&(e._windowsMode.dispose(),e._windowsMode=void 0)}})},t.prototype._onTextAreaFocus=function(e){this.sendFocus&&this._coreService.triggerDataEvent(c.C0.ESC+"[I"),this.updateCursorStyle(e),this.element.classList.add("focus"),this.showCursor(),this._onFocus.fire()},t.prototype.blur=function(){return this.textarea.blur()},t.prototype._onTextAreaBlur=function(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.sendFocus&&this._coreService.triggerDataEvent(c.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()},t.prototype._initGlobal=function(){var e=this;this._bindKeys(),this.register(d.addDisposableDomListener(this.element,"copy",function(t){e.hasSelection()&&a.copyHandler(t,e._selectionService)}));var t=function(t){return a.handlePasteEvent(t,e.textarea,e.bracketedPasteMode,e._coreService)};this.register(d.addDisposableDomListener(this.textarea,"paste",t)),this.register(d.addDisposableDomListener(this.element,"paste",t)),_.isFirefox?this.register(d.addDisposableDomListener(this.element,"mousedown",function(t){2===t.button&&a.rightClickHandler(t,e.textarea,e.screenElement,e._selectionService,e.options.rightClickSelectsWord)})):this.register(d.addDisposableDomListener(this.element,"contextmenu",function(t){a.rightClickHandler(t,e.textarea,e.screenElement,e._selectionService,e.options.rightClickSelectsWord)})),_.isLinux&&this.register(d.addDisposableDomListener(this.element,"auxclick",function(t){1===t.button&&a.moveTextAreaUnderMouseCursor(t,e.textarea,e.screenElement)}))},t.prototype._bindKeys=function(){var e=this;this.register(d.addDisposableDomListener(this.textarea,"keyup",function(t){return e._keyUp(t)},!0)),this.register(d.addDisposableDomListener(this.textarea,"keydown",function(t){return e._keyDown(t)},!0)),this.register(d.addDisposableDomListener(this.textarea,"keypress",function(t){return e._keyPress(t)},!0)),this.register(d.addDisposableDomListener(this.textarea,"compositionstart",function(){return e._compositionHelper.compositionstart()})),this.register(d.addDisposableDomListener(this.textarea,"compositionupdate",function(t){return e._compositionHelper.compositionupdate(t)})),this.register(d.addDisposableDomListener(this.textarea,"compositionend",function(){return e._compositionHelper.compositionend()})),this.register(this.onRender(function(){return e._compositionHelper.updateCompositionElements()})),this.register(this.onRender(function(t){return e._queueLinkification(t.start,t.end)}))},t.prototype.open=function(e){var t=this;if(this._parent=e||this._parent,!this._parent)throw new Error("Terminal requires a parent element.");j.body.contains(e)||this._logService.warn("Terminal.open was called on an element that was not attached to the DOM"),this._document=this._parent.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),this.element.setAttribute("tabindex","0"),this._parent.appendChild(this.element);var i=j.createDocumentFragment();this._viewportElement=j.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),i.appendChild(this._viewportElement),this._viewportScrollArea=j.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=j.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._helperContainer=j.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),i.appendChild(this.screenElement),this.textarea=j.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",p.promptLabel),this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this.register(d.addDisposableDomListener(this.textarea,"focus",function(e){return t._onTextAreaFocus(e)})),this.register(d.addDisposableDomListener(this.textarea,"blur",function(){return t._onTextAreaBlur()})),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(D.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(k.ICharSizeService,this._charSizeService),this._compositionView=j.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(s.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this.element.appendChild(i),this._theme=this.options.theme||this._theme,this.options.theme=void 0,this._colorManager=new E.ColorManager(j,this.options.allowTransparency),this._colorManager.setTheme(this._theme);var r=this._createRenderer();this._renderService=this._instantiationService.createInstance(L.RenderService,r,this.rows,this.screenElement),this._instantiationService.setService(k.IRenderService,this._renderService),this._renderService.onRender(function(e){return t._onRender.fire(e)}),this.onResize(function(e){return t._renderService.resize(e.cols,e.rows)}),this._soundService=this._instantiationService.createInstance(v.SoundService),this._instantiationService.setService(k.ISoundService,this._soundService),this._mouseService=this._instantiationService.createInstance(M.MouseService),this._instantiationService.setService(k.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(o.Viewport,function(e,i){return t.scrollLines(e,i)},this._viewportElement,this._viewportScrollArea),this.viewport.onThemeChange(this._colorManager.colors),this.register(this.viewport),this.register(this.onCursorMove(function(){return t._renderService.onCursorMove()})),this.register(this.onResize(function(){return t._renderService.onResize(t.cols,t.rows)})),this.register(this.onBlur(function(){return t._renderService.onBlur()})),this.register(this.onFocus(function(){return t._renderService.onFocus()})),this.register(this._renderService.onDimensionsChange(function(){return t.viewport.syncScrollArea()})),this._selectionService=this._instantiationService.createInstance(f.SelectionService,function(e,i){return t.scrollLines(e,i)},this.element,this.screenElement),this._instantiationService.setService(k.ISelectionService,this._selectionService),this.register(this._selectionService.onSelectionChange(function(){return t._onSelectionChange.fire()})),this.register(this._selectionService.onRedrawRequest(function(e){return t._renderService.onSelectionChanged(e.start,e.end,e.columnSelectMode)})),this.register(this._selectionService.onLinuxMouseSelection(function(e){t.textarea.value=e,t.textarea.focus(),t.textarea.select()})),this.register(this.onScroll(function(){t.viewport.syncScrollArea(),t._selectionService.refresh()})),this.register(d.addDisposableDomListener(this._viewportElement,"scroll",function(){return t._selectionService.refresh()})),this._mouseZoneManager=this._instantiationService.createInstance(g.MouseZoneManager,this.element,this.screenElement),this.register(this._mouseZoneManager),this.register(this.onScroll(function(){return t._mouseZoneManager.clearAll()})),this.linkifier.attachToDom(this.element,this._mouseZoneManager),this.register(d.addDisposableDomListener(this.element,"mousedown",function(e){return t._selectionService.onMouseDown(e)})),this.mouseEvents?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager=new y.AccessibilityManager(this,this._renderService)),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()},t.prototype._createRenderer=function(){switch(this.options.rendererType){case"canvas":return new h.Renderer(this._colorManager.colors,this,this._bufferService,this._charSizeService,this.optionsService);case"dom":return new m.DomRenderer(this,this._colorManager.colors,this._charSizeService,this.optionsService);default:throw new Error('Unrecognized rendererType "'+this.options.rendererType+'"')}},t.prototype._setTheme=function(e){this._theme=e,this._colorManager&&this._colorManager.setTheme(e),this._renderService&&this._renderService.setColors(this._colorManager.colors),this.viewport&&this.viewport.onThemeChange(this._colorManager.colors)},t.prototype.bindMouse=function(){var e=this,t=this,i=this.element;function r(e){var i,r,n;if(!(i=t._mouseService.getRawByteCoords(e,t.screenElement,t.cols,t.rows)))return!1;switch(e.overrideType||e.type){case"mousemove":n=32,void 0===e.buttons?(r=3,void 0!==e.button&&(r=e.button<3?e.button:3)):r=1&e.buttons?0:4&e.buttons?1:2&e.buttons?2:3;break;case"mouseup":n=0,r=e.button<3?e.button:3;break;case"mousedown":n=1,r=e.button<3?e.button:3;break;case"wheel":0!==e.deltaY&&(n=e.deltaY<0?0:1),r=4;break;default:return!1}return!(void 0===n||void 0===r||r>4)&&t._coreMouseService.triggerMouseEvent({col:i.x-33,row:i.y-33,button:r,action:n,ctrl:e.ctrlKey,alt:e.altKey,shift:e.shiftKey})}var n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},s=function(t){return r(t),t.buttons||(e._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&e._document.removeEventListener("mousemove",n.mousedrag)),e.cancel(t)},o=function(t){return r(t),t.preventDefault(),e.cancel(t)},a=function(e){e.buttons&&r(e)},l=function(e){e.buttons||r(e)};this._coreMouseService.onProtocolChange(function(t){e.mouseEvents=t,t?("debug"===e.optionsService.options.logLevel&&e._logService.debug("Binding to mouse events:",e._coreMouseService.explainEvents(t)),e.element.classList.add("enable-mouse-events"),e._selectionService.disable()):(e._logService.debug("Unbinding from mouse events."),e.element.classList.remove("enable-mouse-events"),e._selectionService.enable()),8&t?n.mousemove||(i.addEventListener("mousemove",l),n.mousemove=l):(i.removeEventListener("mousemove",n.mousemove),n.mousemove=null),16&t?n.wheel||(i.addEventListener("wheel",o),n.wheel=o):(i.removeEventListener("wheel",n.wheel),n.wheel=null),2&t?n.mouseup||(n.mouseup=s):(e._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),4&t?n.mousedrag||(n.mousedrag=a):(e._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)}),this._coreMouseService.activeProtocol=this._coreMouseService.activeProtocol,this.register(d.addDisposableDomListener(i,"mousedown",function(t){if(t.preventDefault(),e.focus(),e.mouseEvents&&!e._selectionService.shouldForceSelection(t))return r(t),n.mouseup&&e._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&e._document.addEventListener("mousemove",n.mousedrag),e.cancel(t)})),this.register(d.addDisposableDomListener(i,"wheel",function(t){if(n.wheel);else if(!e.buffer.hasScrollback){var i=e.viewport.getLinesScrolled(t);if(0===i)return;for(var r=c.C0.ESC+(e._coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(t.deltaY<0?"A":"B"),s="",o=0;o<Math.abs(i);o++)s+=r;e._coreService.triggerDataEvent(s,!0)}})),this.register(d.addDisposableDomListener(i,"wheel",function(t){if(!n.wheel)return e.viewport.onWheel(t)?void 0:e.cancel(t)})),this.register(d.addDisposableDomListener(i,"touchstart",function(t){if(!e.mouseEvents)return e.viewport.onTouchStart(t),e.cancel(t)})),this.register(d.addDisposableDomListener(i,"touchmove",function(t){if(!e.mouseEvents)return e.viewport.onTouchMove(t)?void 0:e.cancel(t)}))},t.prototype.refresh=function(e,t){this._renderService&&this._renderService.refreshRows(e,t)},t.prototype._queueLinkification=function(e,t){this.linkifier&&this.linkifier.linkifyRows(e,t)},t.prototype.updateCursorStyle=function(e){this._selectionService&&this._selectionService.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")},t.prototype.showCursor=function(){this.cursorState||(this.cursorState=1,this.refresh(this.buffer.y,this.buffer.y))},t.prototype.scroll=function(e){var t;void 0===e&&(e=!1),t=this._blankLine;var i=this.eraseAttrData();t&&t.length===this.cols&&t.getFg(0)===i.fg&&t.getBg(0)===i.bg||(t=this.buffer.getBlankLine(i,e),this._blankLine=t),t.isWrapped=e;var r=this.buffer.ybase+this.buffer.scrollTop,n=this.buffer.ybase+this.buffer.scrollBottom;if(0===this.buffer.scrollTop){var s=this.buffer.lines.isFull;n===this.buffer.lines.length-1?s?this.buffer.lines.recycle().copyFrom(t):this.buffer.lines.push(t.clone()):this.buffer.lines.splice(n+1,0,t.clone()),s?this._userScrolling&&(this.buffer.ydisp=Math.max(this.buffer.ydisp-1,0)):(this.buffer.ybase++,this._userScrolling||this.buffer.ydisp++)}else{var o=n-r+1;this.buffer.lines.shiftElements(r+1,o-1,-1),this.buffer.lines.set(n,t.clone())}this._userScrolling||(this.buffer.ydisp=this.buffer.ybase),this._dirtyRowService.markRangeDirty(this.buffer.scrollTop,this.buffer.scrollBottom),this._onScroll.fire(this.buffer.ydisp)},t.prototype.scrollLines=function(e,t){if(e<0){if(0===this.buffer.ydisp)return;this._userScrolling=!0}else e+this.buffer.ydisp>=this.buffer.ybase&&(this._userScrolling=!1);var i=this.buffer.ydisp;this.buffer.ydisp=Math.max(Math.min(this.buffer.ydisp+e,this.buffer.ybase),0),i!==this.buffer.ydisp&&(t||this._onScroll.fire(this.buffer.ydisp),this.refresh(0,this.rows-1))},t.prototype.scrollPages=function(e){this.scrollLines(e*(this.rows-1))},t.prototype.scrollToTop=function(){this.scrollLines(-this.buffer.ydisp)},t.prototype.scrollToBottom=function(){this.scrollLines(this.buffer.ybase-this.buffer.ydisp)},t.prototype.scrollToLine=function(e){var t=e-this.buffer.ydisp;0!==t&&this.scrollLines(t)},t.prototype.paste=function(e){a.paste(e,this.textarea,this.bracketedPasteMode,this._coreService)},t.prototype.attachCustomKeyEventHandler=function(e){this._customKeyEventHandler=e},t.prototype.addEscHandler=function(e,t){return this._inputHandler.addEscHandler(e,t)},t.prototype.addDcsHandler=function(e,t){return this._inputHandler.addDcsHandler(e,t)},t.prototype.addCsiHandler=function(e,t){return this._inputHandler.addCsiHandler(e,t)},t.prototype.addOscHandler=function(e,t){return this._inputHandler.addOscHandler(e,t)},t.prototype.registerLinkMatcher=function(e,t,i){var r=this.linkifier.registerLinkMatcher(e,t,i);return this.refresh(0,this.rows-1),r},t.prototype.deregisterLinkMatcher=function(e){this.linkifier.deregisterLinkMatcher(e)&&this.refresh(0,this.rows-1)},t.prototype.registerCharacterJoiner=function(e){var t=this._renderService.registerCharacterJoiner(e);return this.refresh(0,this.rows-1),t},t.prototype.deregisterCharacterJoiner=function(e){this._renderService.deregisterCharacterJoiner(e)&&this.refresh(0,this.rows-1)},Object.defineProperty(t.prototype,"markers",{get:function(){return this.buffer.markers},enumerable:!0,configurable:!0}),t.prototype.addMarker=function(e){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)},t.prototype.hasSelection=function(){return!!this._selectionService&&this._selectionService.hasSelection},t.prototype.select=function(e,t,i){this._selectionService.setSelection(e,t,i)},t.prototype.getSelection=function(){return this._selectionService?this._selectionService.selectionText:""},t.prototype.getSelectionPosition=function(){if(this._selectionService.hasSelection)return{startColumn:this._selectionService.selectionStart[0],startRow:this._selectionService.selectionStart[1],endColumn:this._selectionService.selectionEnd[0],endRow:this._selectionService.selectionEnd[1]}},t.prototype.clearSelection=function(){this._selectionService&&this._selectionService.clearSelection()},t.prototype.selectAll=function(){this._selectionService&&this._selectionService.selectAll()},t.prototype.selectLines=function(e,t){this._selectionService&&this._selectionService.selectLines(e,t)},t.prototype._keyDown=function(e){if(this._keyDownHandled=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(!this._compositionHelper.keydown(e))return this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;var t=b.evaluateKeyboardEvent(e,this._coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===t.type||2===t.type){var i=this.rows-1;return this.scrollLines(2===t.type?-i:i),this.cancel(e,!0)}return 1===t.type&&this.selectAll(),!!this._isThirdLevelShift(this.browser,e)||(t.cancel&&this.cancel(e,!0),!t.key||(t.key!==c.C0.ETX&&t.key!==c.C0.CR||(this.textarea.value=""),this._onKey.fire({key:t.key,domEvent:e}),this.showCursor(),this._coreService.triggerDataEvent(t.key,!0),this.optionsService.options.screenReaderMode?void(this._keyDownHandled=!0):this.cancel(e,!0)))},t.prototype._isThirdLevelShift=function(e,t){var i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey;return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)},t.prototype.setgLevel=function(e){this.glevel=e,this.charset=this.charsets[e]},t.prototype.setgCharset=function(e,t){this.charsets[e]=t,this.glevel===e&&(this.charset=t)},t.prototype._keyUp=function(e){this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return 16===e.keyCode||17===e.keyCode||18===e.keyCode}(e)||this.focus(),this.updateCursorStyle(e))},t.prototype._keyPress=function(e){var t;if(this._keyDownHandled)return!1;if(this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e))&&(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this.showCursor(),this._coreService.triggerDataEvent(t,!0),!0)},t.prototype.bell=function(){var e=this;this._soundBell()&&this._soundService.playBellSound(),this._visualBell()&&(this.element.classList.add("visual-bell-active"),clearTimeout(this._visualBellTimer),this._visualBellTimer=window.setTimeout(function(){e.element.classList.remove("visual-bell-active")},200))},t.prototype.resize=function(e,t){isNaN(e)||isNaN(t)||(e!==this.cols||t!==this.rows?(e<T.MINIMUM_COLS&&(e=T.MINIMUM_COLS),t<T.MINIMUM_ROWS&&(t=T.MINIMUM_ROWS),this.buffers.resize(e,t),this._bufferService.resize(e,t),this.buffers.setupTabStops(this.cols),this._charSizeService&&this._charSizeService.measure(),this.viewport.syncScrollArea(!0),this.refresh(0,this.rows-1),this._onResize.fire({cols:e,rows:t})):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure())},t.prototype.clear=function(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(var e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(S.DEFAULT_ATTR_DATA));this.refresh(0,this.rows-1),this._onScroll.fire(this.buffer.ydisp)}},t.prototype.is=function(e){return 0===(this.options.termName+"").indexOf(e)},t.prototype.handleTitle=function(e){this._onTitleChange.fire(e)},t.prototype.reset=function(){this.options.rows=this.rows,this.options.cols=this.cols;var e=this._customKeyEventHandler,t=this._inputHandler,i=this.cursorState,r=this._userScrolling;this._setup(),this._bufferService.reset(),this._coreService.reset(),this._coreMouseService.reset(),this._selectionService&&this._selectionService.reset(),this._customKeyEventHandler=e,this._inputHandler=t,this.cursorState=i,this._userScrolling=r,this.refresh(0,this.rows-1),this.viewport&&this.viewport.syncScrollArea()},t.prototype.cancel=function(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1},t.prototype._visualBell=function(){return!1},t.prototype._soundBell=function(){return"sound"===this.options.bellStyle},t.prototype.write=function(e,t){this._writeBuffer.write(e,t)},t.prototype.writeSync=function(e){this._writeBuffer.writeSync(e)},t}(R.Disposable);t.Terminal=W},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(5),o=i(0),a=function(){function e(e,t,i,r,n,s){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=r,this._charSizeService=n,this._coreService=s,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0}}return e.prototype.compositionstart=function(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._compositionView.classList.add("active")},e.prototype.compositionupdate=function(e){var t=this;this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(function(){t._compositionPosition.end=t._textarea.value.length},0)},e.prototype.compositionend=function(){this._finalizeComposition(!0)},e.prototype.keydown=function(e){if(this._isComposing||this._isSendingComposition){if(229===e.keyCode)return!1;if(16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)},e.prototype._finalizeComposition=function(e){var t=this;if(this._compositionView.classList.remove("active"),this._isComposing=!1,this._clearTextareaPosition(),e){var i={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(function(){if(t._isSendingComposition){t._isSendingComposition=!1;var e=void 0;e=t._isComposing?t._textarea.value.substring(i.start,i.end):t._textarea.value.substring(i.start),t._coreService.triggerDataEvent(e,!0)}},0)}else{this._isSendingComposition=!1;var r=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(r,!0)}},e.prototype._handleAnyTextareaChanges=function(){var e=this,t=this._textarea.value;setTimeout(function(){if(!e._isComposing){var i=e._textarea.value.replace(t,"");i.length>0&&e._coreService.triggerDataEvent(i,!0)}},0)},e.prototype.updateCompositionElements=function(e){var t=this;if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){var i=Math.ceil(this._charSizeService.height*this._optionsService.options.lineHeight),r=this._bufferService.buffer.y*i,n=this._bufferService.buffer.x*this._charSizeService.width;this._compositionView.style.left=n+"px",this._compositionView.style.top=r+"px",this._compositionView.style.height=i+"px",this._compositionView.style.lineHeight=i+"px",this._compositionView.style.fontFamily=this._optionsService.options.fontFamily,this._compositionView.style.fontSize=this._optionsService.options.fontSize+"px";var s=this._compositionView.getBoundingClientRect();this._textarea.style.left=n+"px",this._textarea.style.top=r+"px",this._textarea.style.width=s.width+"px",this._textarea.style.height=s.height+"px",this._textarea.style.lineHeight=s.height+"px"}e||setTimeout(function(){return t.updateCompositionElements(!0)},0)}},e.prototype._clearTextareaPosition=function(){this._textarea.style.left="",this._textarea.style.top=""},e=r([n(2,o.IBufferService),n(3,o.IOptionsService),n(4,s.ICharSizeService),n(5,o.ICoreService)],e)}();t.CompositionHelper=a},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},o=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var a=i(2),c=i(7),l=i(5),h=i(0),u=15,f=function(e){function t(t,i,r,n,s,o,a){var l=e.call(this)||this;return l._scrollLines=t,l._viewportElement=i,l._scrollArea=r,l._bufferService=n,l._optionsService=s,l._charSizeService=o,l._renderService=a,l.scrollBarWidth=0,l._currentRowHeight=0,l._lastRecordedBufferLength=0,l._lastRecordedViewportHeight=0,l._lastRecordedBufferHeight=0,l._lastTouchY=0,l._lastScrollTop=0,l._wheelPartialScroll=0,l._refreshAnimationFrame=null,l._ignoreNextScrollEvent=!1,l.scrollBarWidth=l._viewportElement.offsetWidth-l._scrollArea.offsetWidth||u,l.register(c.addDisposableDomListener(l._viewportElement,"scroll",l._onScroll.bind(l))),setTimeout(function(){return l.syncScrollArea()},0),l}return n(t,e),t.prototype.onThemeChange=function(e){this._viewportElement.style.backgroundColor=e.background.css},t.prototype._refresh=function(e){var t=this;if(e)return this._innerRefresh(),void(null!==this._refreshAnimationFrame&&cancelAnimationFrame(this._refreshAnimationFrame));null===this._refreshAnimationFrame&&(this._refreshAnimationFrame=requestAnimationFrame(function(){return t._innerRefresh()}))},t.prototype._innerRefresh=function(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderService.dimensions.scaledCellHeight/window.devicePixelRatio,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;var e=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.canvasHeight);this._lastRecordedBufferHeight!==e&&(this._lastRecordedBufferHeight=e,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}var t=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==t&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=t),this._refreshAnimationFrame=null},t.prototype.syncScrollArea=function(e){if(void 0===e&&(e=!1),this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(e);if(this._lastRecordedViewportHeight===this._renderService.dimensions.canvasHeight){var t=this._bufferService.buffer.ydisp*this._currentRowHeight;this._lastScrollTop===t&&this._lastScrollTop===this._viewportElement.scrollTop&&this._renderService.dimensions.scaledCellHeight/window.devicePixelRatio===this._currentRowHeight||this._refresh(e)}else this._refresh(e)},t.prototype._onScroll=function(e){if(this._lastScrollTop=this._viewportElement.scrollTop,this._viewportElement.offsetParent)if(this._ignoreNextScrollEvent)this._ignoreNextScrollEvent=!1;else{var t=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._scrollLines(t,!0)}},t.prototype._bubbleScroll=function(e,t){var i=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(t<0&&0!==this._viewportElement.scrollTop||t>0&&i<this._lastRecordedBufferHeight)||(e.cancelable&&e.preventDefault(),!1)},t.prototype.onWheel=function(e){var t=this._getPixelsScrolled(e);return 0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))},t.prototype._getPixelsScrolled=function(e){if(0===e.deltaY)return 0;var t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_LINE?t*=this._currentRowHeight:e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._currentRowHeight*this._bufferService.rows),t},t.prototype.getLinesScrolled=function(e){if(0===e.deltaY)return 0;var t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(t/=this._currentRowHeight+0,this._wheelPartialScroll+=t,t=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._bufferService.rows),t},t.prototype._applyScrollModifier=function(e,t){var i=this._optionsService.options.fastScrollModifier;return"alt"===i&&t.altKey||"ctrl"===i&&t.ctrlKey||"shift"===i&&t.shiftKey?e*this._optionsService.options.fastScrollSensitivity*this._optionsService.options.scrollSensitivity:e*this._optionsService.options.scrollSensitivity},t.prototype.onTouchStart=function(e){this._lastTouchY=e.touches[0].pageY},t.prototype.onTouchMove=function(e){var t=this._lastTouchY-e.touches[0].pageY;return this._lastTouchY=e.touches[0].pageY,0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))},t=s([o(3,h.IBufferService),o(4,h.IOptionsService),o(5,l.ICharSizeService),o(6,l.IRenderService)],t)}(a.Disposable);t.Viewport=f},function(e,t,i){"use strict";function r(e){return e.replace(/\r?\n/g,"\r")}function n(e,t){return t?"\e[200~"+e+"\e[201~":e}function s(e,t,i,s){e=n(e=r(e),i),s.triggerDataEvent(e,!0),t.value=""}function o(e,t,i){var r=i.getBoundingClientRect(),n=e.clientX-r.left-10,s=e.clientY-r.top-10;t.style.position="absolute",t.style.width="20px",t.style.height="20px",t.style.left=n+"px",t.style.top=s+"px",t.style.zIndex="1000",t.focus(),setTimeout(function(){t.style.position=null,t.style.width=null,t.style.height=null,t.style.left=null,t.style.top=null,t.style.zIndex=null},200)}Object.defineProperty(t,"__esModule",{value:!0}),t.prepareTextForTerminal=r,t.bracketTextForPaste=n,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,i,r){e.stopPropagation(),e.clipboardData&&s(e.clipboardData.getData("text/plain"),t,i,r)},t.paste=s,t.moveTextAreaUnderMouseCursor=o,t.rightClickHandler=function(e,t,i,r,n){o(e,t,i),n&&!r.isClickInSelection(e)&&r.selectWordAtCursor(e),t.value=r.selectionText,t.select()}},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(11),o=i(17),a=i(18),c=i(38),l=i(2),h=i(14),u=i(8),f=i(15),_=i(1),d=i(3),p=i(4),v=i(6),g=i(20),y=i(22),m={"(":0,")":1,"*":2,"+":3,"-":1,".":2},b=function(){function e(e,t,i,r){this._bufferService=e,this._coreService=t,this._logService=i,this._optionsService=r,this._data=new Uint32Array(0)}return e.prototype.hook=function(e){this._data=new Uint32Array(0)},e.prototype.put=function(e,t,i){this._data=h.concat(this._data,e.subarray(t,i))},e.prototype.unhook=function(e){if(e){var t=u.utf32ToString(this._data);switch(this._data=new Uint32Array(0),t){case'"q':return this._coreService.triggerDataEvent(s.C0.ESC+'P1$r0"q'+s.C0.ESC+"\\");case'"p':return this._coreService.triggerDataEvent(s.C0.ESC+'P1$r61"p'+s.C0.ESC+"\\");case"r":var i=this._bufferService.buffer.scrollTop+1+";"+(this._bufferService.buffer.scrollBottom+1)+"r";return this._coreService.triggerDataEvent(s.C0.ESC+"P1$r"+i+s.C0.ESC+"\\");case"m":return this._coreService.triggerDataEvent(s.C0.ESC+"P1$r0m"+s.C0.ESC+"\\");case" q":var r={block:2,underline:4,bar:6}[this._optionsService.options.cursorStyle];return r-=this._optionsService.options.cursorBlink?1:0,this._coreService.triggerDataEvent(s.C0.ESC+"P1$r"+r+" q"+s.C0.ESC+"\\");default:this._logService.debug("Unknown DCS $q %s",t),this._coreService.triggerDataEvent(s.C0.ESC+"P0$r"+s.C0.ESC+"\\")}}else this._data=new Uint32Array(0)},e}(),C=function(e){function t(t,i,r,n,a,l,h,f){void 0===f&&(f=new c.EscapeSequenceParser);var d=e.call(this)||this;d._terminal=t,d._bufferService=i,d._coreService=r,d._dirtyRowService=n,d._logService=a,d._optionsService=l,d._coreMouseService=h,d._parser=f,d._parseBuffer=new Uint32Array(4096),d._stringDecoder=new u.StringToUtf32,d._utf8Decoder=new u.Utf8ToUtf32,d._workCell=new p.CellData,d._onCursorMove=new _.EventEmitter,d._onLineFeed=new _.EventEmitter,d._onScroll=new _.EventEmitter,d.register(d._parser),d._parser.setCsiHandlerFallback(function(e,t){d._logService.debug("Unknown CSI code: ",{identifier:d._parser.identToString(e),params:t.toArray()})}),d._parser.setEscHandlerFallback(function(e){d._logService.debug("Unknown ESC code: ",{identifier:d._parser.identToString(e)})}),d._parser.setExecuteHandlerFallback(function(e){d._logService.debug("Unknown EXECUTE code: ",{code:e})}),d._parser.setOscHandlerFallback(function(e,t,i){d._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})}),d._parser.setDcsHandlerFallback(function(e,t,i){"HOOK"===t&&(i=i.toArray()),d._logService.debug("Unknown DCS code: ",{identifier:d._parser.identToString(e),action:t,payload:i})}),d._parser.setPrintHandler(function(e,t,i){return d.print(e,t,i)}),d._parser.setCsiHandler({final:"@"},function(e){return d.insertChars(e)}),d._parser.setCsiHandler({intermediates:" ",final:"@"},function(e){return d.scrollLeft(e)}),d._parser.setCsiHandler({final:"A"},function(e){return d.cursorUp(e)}),d._parser.setCsiHandler({intermediates:" ",final:"A"},function(e){return d.scrollRight(e)}),d._parser.setCsiHandler({final:"B"},function(e){return d.cursorDown(e)}),d._parser.setCsiHandler({final:"C"},function(e){return d.cursorForward(e)}),d._parser.setCsiHandler({final:"D"},function(e){return d.cursorBackward(e)}),d._parser.setCsiHandler({final:"E"},function(e){return d.cursorNextLine(e)}),d._parser.setCsiHandler({final:"F"},function(e){return d.cursorPrecedingLine(e)}),d._parser.setCsiHandler({final:"G"},function(e){return d.cursorCharAbsolute(e)}),d._parser.setCsiHandler({final:"H"},function(e){return d.cursorPosition(e)}),d._parser.setCsiHandler({final:"I"},function(e){return d.cursorForwardTab(e)}),d._parser.setCsiHandler({final:"J"},function(e){return d.eraseInDisplay(e)}),d._parser.setCsiHandler({prefix:"?",final:"J"},function(e){return d.eraseInDisplay(e)}),d._parser.setCsiHandler({final:"K"},function(e){return d.eraseInLine(e)}),d._parser.setCsiHandler({prefix:"?",final:"K"},function(e){return d.eraseInLine(e)}),d._parser.setCsiHandler({final:"L"},function(e){return d.insertLines(e)}),d._parser.setCsiHandler({final:"M"},function(e){return d.deleteLines(e)}),d._parser.setCsiHandler({final:"P"},function(e){return d.deleteChars(e)}),d._parser.setCsiHandler({final:"S"},function(e){return d.scrollUp(e)}),d._parser.setCsiHandler({final:"T"},function(e){return d.scrollDown(e)}),d._parser.setCsiHandler({final:"X"},function(e){return d.eraseChars(e)}),d._parser.setCsiHandler({final:"Z"},function(e){return d.cursorBackwardTab(e)}),d._parser.setCsiHandler({final:"`"},function(e){return d.charPosAbsolute(e)}),d._parser.setCsiHandler({final:"a"},function(e){return d.hPositionRelative(e)}),d._parser.setCsiHandler({final:"b"},function(e){return d.repeatPrecedingCharacter(e)}),d._parser.setCsiHandler({final:"c"},function(e){return d.sendDeviceAttributesPrimary(e)}),d._parser.setCsiHandler({prefix:">",final:"c"},function(e){return d.sendDeviceAttributesSecondary(e)}),d._parser.setCsiHandler({final:"d"},function(e){return d.linePosAbsolute(e)}),d._parser.setCsiHandler({final:"e"},function(e){return d.vPositionRelative(e)}),d._parser.setCsiHandler({final:"f"},function(e){return d.hVPosition(e)}),d._parser.setCsiHandler({final:"g"},function(e){return d.tabClear(e)}),d._parser.setCsiHandler({final:"h"},function(e){return d.setMode(e)}),d._parser.setCsiHandler({prefix:"?",final:"h"},function(e){return d.setModePrivate(e)}),d._parser.setCsiHandler({final:"l"},function(e){return d.resetMode(e)}),d._parser.setCsiHandler({prefix:"?",final:"l"},function(e){return d.resetModePrivate(e)}),d._parser.setCsiHandler({final:"m"},function(e){return d.charAttributes(e)}),d._parser.setCsiHandler({final:"n"},function(e){return d.deviceStatus(e)}),d._parser.setCsiHandler({prefix:"?",final:"n"},function(e){return d.deviceStatusPrivate(e)}),d._parser.setCsiHandler({intermediates:"!",final:"p"},function(e){return d.softReset(e)}),d._parser.setCsiHandler({intermediates:" ",final:"q"},function(e){return d.setCursorStyle(e)}),d._parser.setCsiHandler({final:"r"},function(e){return d.setScrollRegion(e)}),d._parser.setCsiHandler({final:"s"},function(e){return d.saveCursor(e)}),d._parser.setCsiHandler({final:"u"},function(e){return d.restoreCursor(e)}),d._parser.setCsiHandler({intermediates:"'",final:"}"},function(e){return d.insertColumns(e)}),d._parser.setCsiHandler({intermediates:"'",final:"~"},function(e){return d.deleteColumns(e)}),d._parser.setExecuteHandler(s.C0.BEL,function(){return d.bell()}),d._parser.setExecuteHandler(s.C0.LF,function(){return d.lineFeed()}),d._parser.setExecuteHandler(s.C0.VT,function(){return d.lineFeed()}),d._parser.setExecuteHandler(s.C0.FF,function(){return d.lineFeed()}),d._parser.setExecuteHandler(s.C0.CR,function(){return d.carriageReturn()}),d._parser.setExecuteHandler(s.C0.BS,function(){return d.backspace()}),d._parser.setExecuteHandler(s.C0.HT,function(){return d.tab()}),d._parser.setExecuteHandler(s.C0.SO,function(){return d.shiftOut()}),d._parser.setExecuteHandler(s.C0.SI,function(){return d.shiftIn()}),d._parser.setExecuteHandler(s.C1.IND,function(){return d.index()}),d._parser.setExecuteHandler(s.C1.NEL,function(){return d.nextLine()}),d._parser.setExecuteHandler(s.C1.HTS,function(){return d.tabSet()}),d._parser.setOscHandler(0,new g.OscHandler(function(e){return d.setTitle(e)})),d._parser.setOscHandler(2,new g.OscHandler(function(e){return d.setTitle(e)})),d._parser.setEscHandler({final:"7"},function(){return d.saveCursor()}),d._parser.setEscHandler({final:"8"},function(){return d.restoreCursor()}),d._parser.setEscHandler({final:"D"},function(){return d.index()}),d._parser.setEscHandler({final:"E"},function(){return d.nextLine()}),d._parser.setEscHandler({final:"H"},function(){return d.tabSet()}),d._parser.setEscHandler({final:"M"},function(){return d.reverseIndex()}),d._parser.setEscHandler({final:"="},function(){return d.keypadApplicationMode()}),d._parser.setEscHandler({final:">"},function(){return d.keypadNumericMode()}),d._parser.setEscHandler({final:"c"},function(){return d.reset()}),d._parser.setEscHandler({final:"n"},function(){return d.setgLevel(2)}),d._parser.setEscHandler({final:"o"},function(){return d.setgLevel(3)}),d._parser.setEscHandler({final:"|"},function(){return d.setgLevel(3)}),d._parser.setEscHandler({final:"}"},function(){return d.setgLevel(2)}),d._parser.setEscHandler({final:"~"},function(){return d.setgLevel(1)}),d._parser.setEscHandler({intermediates:"%",final:"@"},function(){return d.selectDefaultCharset()}),d._parser.setEscHandler({intermediates:"%",final:"G"},function(){return d.selectDefaultCharset()});var v=function(e){y._parser.setEscHandler({intermediates:"(",final:e},function(){return d.selectCharset("("+e)}),y._parser.setEscHandler({intermediates:")",final:e},function(){return d.selectCharset(")"+e)}),y._parser.setEscHandler({intermediates:"*",final:e},function(){return d.selectCharset("*"+e)}),y._parser.setEscHandler({intermediates:"+",final:e},function(){return d.selectCharset("+"+e)}),y._parser.setEscHandler({intermediates:"-",final:e},function(){return d.selectCharset("-"+e)}),y._parser.setEscHandler({intermediates:".",final:e},function(){return d.selectCharset("."+e)}),y._parser.setEscHandler({intermediates:"/",final:e},function(){return d.selectCharset("/"+e)})},y=this;for(var m in o.CHARSETS)v(m);return d._parser.setEscHandler({intermediates:"#",final:"8"},function(){return d.screenAlignmentPattern()}),d._parser.setErrorHandler(function(e){return d._logService.error("Parsing error: ",e),e}),d._parser.setDcsHandler({intermediates:"$",final:"q"},new b(d._bufferService,d._coreService,d._logService,d._optionsService)),d}return n(t,e),Object.defineProperty(t.prototype,"onCursorMove",{get:function(){return this._onCursorMove.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onLineFeed",{get:function(){return this._onLineFeed.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.parse=function(e){var t=this._bufferService.buffer,i=t.x,r=t.y;if(this._logService.debug("parsing data",e),this._parseBuffer.length<e.length&&this._parseBuffer.length<131072&&(this._parseBuffer=new Uint32Array(Math.min(e.length,131072))),e.length>131072)for(var n=0;n<e.length;n+=131072){var s=n+131072<e.length?n+131072:e.length,o="string"==typeof e?this._stringDecoder.decode(e.substring(n,s),this._parseBuffer):this._utf8Decoder.decode(e.subarray(n,s),this._parseBuffer);this._parser.parse(this._parseBuffer,o)}else{o="string"==typeof e?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);this._parser.parse(this._parseBuffer,o)}(t=this._bufferService.buffer).x===i&&t.y===r||this._onCursorMove.fire(),this._terminal.refresh(this._dirtyRowService.start,this._dirtyRowService.end)},t.prototype.print=function(e,t,i){var r,n,s=this._bufferService.buffer,o=this._terminal.charset,c=this._optionsService.options.screenReaderMode,l=this._bufferService.cols,h=this._terminal.wraparoundMode,f=this._terminal.insertMode,_=this._terminal.curAttrData,p=s.lines.get(s.y+s.ybase);this._dirtyRowService.markDirty(s.y);for(var v=t;v<i;++v){if(r=e[v],n=a.wcwidth(r),r<127&&o){var g=o[String.fromCharCode(r)];g&&(r=g.charCodeAt(0))}if(c&&this._terminal.onA11yCharEmitter.fire(u.stringFromCodePoint(r)),n||!s.x){if(s.x+n-1>=l)if(h)s.x=0,s.y++,s.y===s.scrollBottom+1?(s.y--,this._terminal.scroll(!0)):(s.y>=this._bufferService.rows&&(s.y=this._bufferService.rows-1),s.lines.get(s.y).isWrapped=!0),p=s.lines.get(s.y+s.ybase);else if(s.x=l-1,2===n)continue;if(f&&(p.insertCells(s.x,n,s.getNullCell(_)),2===p.getWidth(l-1)&&p.setCellFromCodePoint(l-1,d.NULL_CELL_CODE,d.NULL_CELL_WIDTH,_.fg,_.bg)),p.setCellFromCodePoint(s.x++,r,n,_.fg,_.bg),n>0)for(;--n;)p.setCellFromCodePoint(s.x++,0,0,_.fg,_.bg)}else p.getWidth(s.x-1)?p.addCodepointToCell(s.x-1,r):p.addCodepointToCell(s.x-2,r)}i&&(p.loadCell(s.x-1,this._workCell),2===this._workCell.getWidth()||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),this._dirtyRowService.markDirty(s.y)},t.prototype.addCsiHandler=function(e,t){return this._parser.addCsiHandler(e,t)},t.prototype.addDcsHandler=function(e,t){return this._parser.addDcsHandler(e,new y.DcsHandler(t))},t.prototype.addEscHandler=function(e,t){return this._parser.addEscHandler(e,t)},t.prototype.addOscHandler=function(e,t){return this._parser.addOscHandler(e,new g.OscHandler(t))},t.prototype.bell=function(){this._terminal.bell()},t.prototype.lineFeed=function(){var e=this._bufferService.buffer;this._optionsService.options.convertEol&&(e.x=0),e.y++,e.y===e.scrollBottom+1?(e.y--,this._terminal.scroll()):e.y>=this._bufferService.rows&&(e.y=this._bufferService.rows-1),e.x>=this._bufferService.cols&&e.x--,this._onLineFeed.fire()},t.prototype.carriageReturn=function(){this._bufferService.buffer.x=0},t.prototype.backspace=function(){this._restrictCursor(),this._bufferService.buffer.x>0&&this._bufferService.buffer.x--},t.prototype.tab=function(){if(!(this._bufferService.buffer.x>=this._bufferService.cols)){var e=this._bufferService.buffer.x;this._bufferService.buffer.x=this._bufferService.buffer.nextStop(),this._optionsService.options.screenReaderMode&&this._terminal.onA11yTabEmitter.fire(this._bufferService.buffer.x-e)}},t.prototype.shiftOut=function(){this._terminal.setgLevel(1)},t.prototype.shiftIn=function(){this._terminal.setgLevel(0)},t.prototype._restrictCursor=function(){this._bufferService.buffer.x=Math.min(this._bufferService.cols-1,Math.max(0,this._bufferService.buffer.x)),this._bufferService.buffer.y=this._terminal.originMode?Math.min(this._bufferService.buffer.scrollBottom,Math.max(this._bufferService.buffer.scrollTop,this._bufferService.buffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._bufferService.buffer.y))},t.prototype._setCursor=function(e,t){this._terminal.originMode?(this._bufferService.buffer.x=e,this._bufferService.buffer.y=this._bufferService.buffer.scrollTop+t):(this._bufferService.buffer.x=e,this._bufferService.buffer.y=t),this._restrictCursor()},t.prototype._moveCursor=function(e,t){this._restrictCursor(),this._setCursor(this._bufferService.buffer.x+e,this._bufferService.buffer.y+t)},t.prototype.cursorUp=function(e){var t=this._bufferService.buffer.y-this._bufferService.buffer.scrollTop;t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1))},t.prototype.cursorDown=function(e){var t=this._bufferService.buffer.scrollBottom-this._bufferService.buffer.y;t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1)},t.prototype.cursorForward=function(e){this._moveCursor(e.params[0]||1,0)},t.prototype.cursorBackward=function(e){this._moveCursor(-(e.params[0]||1),0)},t.prototype.cursorNextLine=function(e){this.cursorDown(e),this._bufferService.buffer.x=0},t.prototype.cursorPrecedingLine=function(e){this.cursorUp(e),this._bufferService.buffer.x=0},t.prototype.cursorCharAbsolute=function(e){this._setCursor((e.params[0]||1)-1,this._bufferService.buffer.y)},t.prototype.cursorPosition=function(e){this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1)},t.prototype.charPosAbsolute=function(e){this._setCursor((e.params[0]||1)-1,this._bufferService.buffer.y)},t.prototype.hPositionRelative=function(e){this._moveCursor(e.params[0]||1,0)},t.prototype.linePosAbsolute=function(e){this._setCursor(this._bufferService.buffer.x,(e.params[0]||1)-1)},t.prototype.vPositionRelative=function(e){this._moveCursor(0,e.params[0]||1)},t.prototype.hVPosition=function(e){this.cursorPosition(e)},t.prototype.tabClear=function(e){var t=e.params[0];0===t?delete this._bufferService.buffer.tabs[this._bufferService.buffer.x]:3===t&&(this._bufferService.buffer.tabs={})},t.prototype.cursorForwardTab=function(e){if(!(this._bufferService.buffer.x>=this._bufferService.cols))for(var t=e.params[0]||1;t--;)this._bufferService.buffer.x=this._bufferService.buffer.nextStop()},t.prototype.cursorBackwardTab=function(e){if(!(this._bufferService.buffer.x>=this._bufferService.cols))for(var t=e.params[0]||1,i=this._bufferService.buffer;t--;)i.x=i.prevStop()},t.prototype._eraseInBufferLine=function(e,t,i,r){void 0===r&&(r=!1);var n=this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase+e);n.replaceCells(t,i,this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),r&&(n.isWrapped=!1)},t.prototype._resetBufferLine=function(e){var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase+e);t.fill(this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),t.isWrapped=!1},t.prototype.eraseInDisplay=function(e){var t;switch(this._restrictCursor(),e.params[0]){case 0:for(t=this._bufferService.buffer.y,this._dirtyRowService.markDirty(t),this._eraseInBufferLine(t++,this._bufferService.buffer.x,this._bufferService.cols,0===this._bufferService.buffer.x);t<this._bufferService.rows;t++)this._resetBufferLine(t);this._dirtyRowService.markDirty(t);break;case 1:for(t=this._bufferService.buffer.y,this._dirtyRowService.markDirty(t),this._eraseInBufferLine(t,0,this._bufferService.buffer.x+1,!0),this._bufferService.buffer.x+1>=this._bufferService.cols&&(this._bufferService.buffer.lines.get(t+1).isWrapped=!1);t--;)this._resetBufferLine(t);this._dirtyRowService.markDirty(0);break;case 2:for(t=this._bufferService.rows,this._dirtyRowService.markDirty(t-1);t--;)this._resetBufferLine(t);this._dirtyRowService.markDirty(0);break;case 3:var i=this._bufferService.buffer.lines.length-this._bufferService.rows;i>0&&(this._bufferService.buffer.lines.trimStart(i),this._bufferService.buffer.ybase=Math.max(this._bufferService.buffer.ybase-i,0),this._bufferService.buffer.ydisp=Math.max(this._bufferService.buffer.ydisp-i,0),this._onScroll.fire(0))}},t.prototype.eraseInLine=function(e){switch(this._restrictCursor(),e.params[0]){case 0:this._eraseInBufferLine(this._bufferService.buffer.y,this._bufferService.buffer.x,this._bufferService.cols);break;case 1:this._eraseInBufferLine(this._bufferService.buffer.y,0,this._bufferService.buffer.x+1);break;case 2:this._eraseInBufferLine(this._bufferService.buffer.y,0,this._bufferService.cols)}this._dirtyRowService.markDirty(this._bufferService.buffer.y)},t.prototype.insertLines=function(e){this._restrictCursor();var t=e.params[0]||1,i=this._bufferService.buffer;if(!(i.y>i.scrollBottom||i.y<i.scrollTop)){for(var r=i.y+i.ybase,n=this._bufferService.rows-1-i.scrollBottom,s=this._bufferService.rows-1+i.ybase-n+1;t--;)i.lines.splice(s-1,1),i.lines.splice(r,0,i.getBlankLine(this._terminal.eraseAttrData()));this._dirtyRowService.markRangeDirty(i.y,i.scrollBottom),i.x=0}},t.prototype.deleteLines=function(e){this._restrictCursor();var t=e.params[0]||1,i=this._bufferService.buffer;if(!(i.y>i.scrollBottom||i.y<i.scrollTop)){var r,n=i.y+i.ybase;for(r=this._bufferService.rows-1-i.scrollBottom,r=this._bufferService.rows-1+i.ybase-r;t--;)i.lines.splice(n,1),i.lines.splice(r,0,i.getBlankLine(this._terminal.eraseAttrData()));this._dirtyRowService.markRangeDirty(i.y,i.scrollBottom),i.x=0}},t.prototype.insertChars=function(e){this._restrictCursor();var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.y+this._bufferService.buffer.ybase);t&&(t.insertCells(this._bufferService.buffer.x,e.params[0]||1,this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),this._dirtyRowService.markDirty(this._bufferService.buffer.y))},t.prototype.deleteChars=function(e){this._restrictCursor();var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.y+this._bufferService.buffer.ybase);t&&(t.deleteCells(this._bufferService.buffer.x,e.params[0]||1,this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),this._dirtyRowService.markDirty(this._bufferService.buffer.y))},t.prototype.scrollUp=function(e){for(var t=e.params[0]||1,i=this._bufferService.buffer;t--;)i.lines.splice(i.ybase+i.scrollTop,1),i.lines.splice(i.ybase+i.scrollBottom,0,i.getBlankLine(this._terminal.eraseAttrData()));this._dirtyRowService.markRangeDirty(i.scrollTop,i.scrollBottom)},t.prototype.scrollDown=function(e){for(var t=e.params[0]||1,i=this._bufferService.buffer;t--;)i.lines.splice(i.ybase+i.scrollBottom,1),i.lines.splice(i.ybase+i.scrollTop,0,i.getBlankLine(f.DEFAULT_ATTR_DATA));this._dirtyRowService.markRangeDirty(i.scrollTop,i.scrollBottom)},t.prototype.scrollLeft=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=t.lines.get(t.ybase+r);n.deleteCells(0,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.scrollRight=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=t.lines.get(t.ybase+r);n.insertCells(0,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.insertColumns=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=this._bufferService.buffer.lines.get(t.ybase+r);n.insertCells(t.x,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.deleteColumns=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=t.lines.get(t.ybase+r);n.deleteCells(t.x,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.eraseChars=function(e){this._restrictCursor();var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.y+this._bufferService.buffer.ybase);t&&(t.replaceCells(this._bufferService.buffer.x,this._bufferService.buffer.x+(e.params[0]||1),this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),this._dirtyRowService.markDirty(this._bufferService.buffer.y))},t.prototype.repeatPrecedingCharacter=function(e){if(this._parser.precedingCodepoint){for(var t=e.params[0]||1,i=new Uint32Array(t),r=0;r<t;++r)i[r]=this._parser.precedingCodepoint;this.print(i,0,i.length)}},t.prototype.sendDeviceAttributesPrimary=function(e){e.params[0]>0||(this._terminal.is("xterm")||this._terminal.is("rxvt-unicode")||this._terminal.is("screen")?this._coreService.triggerDataEvent(s.C0.ESC+"[?1;2c"):this._terminal.is("linux")&&this._coreService.triggerDataEvent(s.C0.ESC+"[?6c"))},t.prototype.sendDeviceAttributesSecondary=function(e){e.params[0]>0||(this._terminal.is("xterm")?this._coreService.triggerDataEvent(s.C0.ESC+"[>0;276;0c"):this._terminal.is("rxvt-unicode")?this._coreService.triggerDataEvent(s.C0.ESC+"[>85;95;0c"):this._terminal.is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._terminal.is("screen")&&this._coreService.triggerDataEvent(s.C0.ESC+"[>83;40003;0c"))},t.prototype.setMode=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 4:this._terminal.insertMode=!0}},t.prototype.setModePrivate=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._terminal.setgCharset(0,o.DEFAULT_CHARSET),this._terminal.setgCharset(1,o.DEFAULT_CHARSET),this._terminal.setgCharset(2,o.DEFAULT_CHARSET),this._terminal.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._terminal.savedCols=this._bufferService.cols,this._terminal.resize(132,this._bufferService.rows),this._terminal.reset();break;case 6:this._terminal.originMode=!0,this._setCursor(0,0);break;case 7:this._terminal.wraparoundMode=!0;break;case 12:break;case 66:this._logService.debug("Serial port requested application keypad."),this._terminal.applicationKeypad=!0,this._terminal.viewport&&this._terminal.viewport.syncScrollArea();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._terminal.sendFocus=!0;break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 25:this._terminal.cursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._terminal.eraseAttrData()),this._terminal.refresh(0,this._bufferService.rows-1),this._terminal.viewport&&this._terminal.viewport.syncScrollArea(),this._terminal.showCursor();break;case 2004:this._terminal.bracketedPasteMode=!0}},t.prototype.resetMode=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 4:this._terminal.insertMode=!1}},t.prototype.resetModePrivate=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:132===this._bufferService.cols&&this._terminal.savedCols&&this._terminal.resize(this._terminal.savedCols,this._bufferService.rows),delete this._terminal.savedCols,this._terminal.reset();break;case 6:this._terminal.originMode=!1,this._setCursor(0,0);break;case 7:this._terminal.wraparoundMode=!1;break;case 12:break;case 66:this._logService.debug("Switching back to normal keypad."),this._terminal.applicationKeypad=!1,this._terminal.viewport&&this._terminal.viewport.syncScrollArea();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._terminal.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._terminal.cursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),1049===e.params[t]&&this.restoreCursor(),this._terminal.refresh(0,this._bufferService.rows-1),this._terminal.viewport&&this._terminal.viewport.syncScrollArea(),this._terminal.showCursor();break;case 2004:this._terminal.bracketedPasteMode=!1}},t.prototype._extractColor=function(e,t,i){var r=[0,0,-1,0,0,0],n=0,s=0;do{if(r[s+n]=e.params[t+s],e.hasSubParams(t+s)){var o=e.getSubParams(t+s),a=0;do{5===r[1]&&(n=1),r[s+a+1+n]=o[a]}while(++a<o.length&&a+s+1+n<r.length);break}if(5===r[1]&&s+n>=2||2===r[1]&&s+n>=5)break;r[1]&&(n=1)}while(++s+t<e.length&&s+n<r.length);for(a=2;a<r.length;++a)-1===r[a]&&(r[a]=0);return 38===r[0]?2===r[1]?(i.fg|=50331648,i.fg&=-16777216,i.fg|=v.AttributeData.fromColorRGB([r[3],r[4],r[5]])):5===r[1]&&(i.fg&=-50331904,i.fg|=33554432|255&r[3]):48===r[0]&&(2===r[1]?(i.bg|=50331648,i.bg&=-16777216,i.bg|=v.AttributeData.fromColorRGB([r[3],r[4],r[5]])):5===r[1]&&(i.bg&=-50331904,i.bg|=33554432|255&r[3])),s},t.prototype.charAttributes=function(e){if(1===e.length&&0===e.params[0])return this._terminal.curAttrData.fg=f.DEFAULT_ATTR_DATA.fg,void(this._terminal.curAttrData.bg=f.DEFAULT_ATTR_DATA.bg);for(var t,i=e.length,r=this._terminal.curAttrData,n=0;n<i;n++)(t=e.params[n])>=30&&t<=37?(r.fg&=-50331904,r.fg|=16777216|t-30):t>=40&&t<=47?(r.bg&=-50331904,r.bg|=16777216|t-40):t>=90&&t<=97?(r.fg&=-50331904,r.fg|=16777224|t-90):t>=100&&t<=107?(r.bg&=-50331904,r.bg|=16777224|t-100):0===t?(r.fg=f.DEFAULT_ATTR_DATA.fg,r.bg=f.DEFAULT_ATTR_DATA.bg):1===t?r.fg|=134217728:3===t?r.bg|=67108864:4===t?r.fg|=268435456:5===t?r.fg|=536870912:7===t?r.fg|=67108864:8===t?r.fg|=1073741824:2===t?r.bg|=134217728:22===t?(r.fg&=-134217729,r.bg&=-134217729):23===t?r.bg&=-67108865:24===t?r.fg&=-268435457:25===t?r.fg&=-536870913:27===t?r.fg&=-67108865:28===t?r.fg&=-1073741825:39===t?(r.fg&=-67108864,r.fg|=16777215&f.DEFAULT_ATTR_DATA.fg):49===t?(r.bg&=-67108864,r.bg|=16777215&f.DEFAULT_ATTR_DATA.bg):38===t||48===t?n+=this._extractColor(e,n,r):100===t?(r.fg&=-67108864,r.fg|=16777215&f.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&f.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",t)},t.prototype.deviceStatus=function(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(s.C0.ESC+"[0n");break;case 6:var t=this._bufferService.buffer.y+1,i=this._bufferService.buffer.x+1;this._coreService.triggerDataEvent(s.C0.ESC+"["+t+";"+i+"R")}},t.prototype.deviceStatusPrivate=function(e){switch(e.params[0]){case 6:var t=this._bufferService.buffer.y+1,i=this._bufferService.buffer.x+1;this._coreService.triggerDataEvent(s.C0.ESC+"[?"+t+";"+i+"R")}},t.prototype.softReset=function(e){this._terminal.cursorHidden=!1,this._terminal.insertMode=!1,this._terminal.originMode=!1,this._terminal.wraparoundMode=!0,this._terminal.applicationKeypad=!1,this._terminal.viewport&&this._terminal.viewport.syncScrollArea(),this._coreService.decPrivateModes.applicationCursorKeys=!1,this._bufferService.buffer.scrollTop=0,this._bufferService.buffer.scrollBottom=this._bufferService.rows-1,this._terminal.curAttrData=f.DEFAULT_ATTR_DATA.clone(),this._bufferService.buffer.x=this._bufferService.buffer.y=0,this._terminal.charset=null,this._terminal.glevel=0,this._terminal.charsets=[null]},t.prototype.setCursorStyle=function(e){var t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}var i=t%2==1;this._optionsService.options.cursorBlink=i},t.prototype.setScrollRegion=function(e){var t,i=e.params[0]||1;(e.length<2||(t=e.params[1])>this._bufferService.rows||0===t)&&(t=this._bufferService.rows),t>i&&(this._bufferService.buffer.scrollTop=i-1,this._bufferService.buffer.scrollBottom=t-1,this._setCursor(0,0))},t.prototype.saveCursor=function(e){this._bufferService.buffer.savedX=this._bufferService.buffer.x,this._bufferService.buffer.savedY=this._bufferService.buffer.ybase+this._bufferService.buffer.y,this._bufferService.buffer.savedCurAttrData.fg=this._terminal.curAttrData.fg,this._bufferService.buffer.savedCurAttrData.bg=this._terminal.curAttrData.bg,this._bufferService.buffer.savedCharset=this._terminal.charset},t.prototype.restoreCursor=function(e){this._bufferService.buffer.x=this._bufferService.buffer.savedX||0,this._bufferService.buffer.y=Math.max(this._bufferService.buffer.savedY-this._bufferService.buffer.ybase,0),this._terminal.curAttrData.fg=this._bufferService.buffer.savedCurAttrData.fg,this._terminal.curAttrData.bg=this._bufferService.buffer.savedCurAttrData.bg,this._terminal.charset=this._savedCharset,this._bufferService.buffer.savedCharset&&(this._terminal.charset=this._bufferService.buffer.savedCharset),this._restrictCursor()},t.prototype.setTitle=function(e){this._terminal.handleTitle(e)},t.prototype.nextLine=function(){this._bufferService.buffer.x=0,this.index()},t.prototype.keypadApplicationMode=function(){this._logService.debug("Serial port requested application keypad."),this._terminal.applicationKeypad=!0,this._terminal.viewport&&this._terminal.viewport.syncScrollArea()},t.prototype.keypadNumericMode=function(){this._logService.debug("Switching back to normal keypad."),this._terminal.applicationKeypad=!1,this._terminal.viewport&&this._terminal.viewport.syncScrollArea()},t.prototype.selectDefaultCharset=function(){this._terminal.setgLevel(0),this._terminal.setgCharset(0,o.DEFAULT_CHARSET)},t.prototype.selectCharset=function(e){2===e.length?"/"!==e[0]&&this._terminal.setgCharset(m[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET):this.selectDefaultCharset()},t.prototype.index=function(){this._restrictCursor();var e=this._bufferService.buffer;this._bufferService.buffer.y++,e.y===e.scrollBottom+1?(e.y--,this._terminal.scroll()):e.y>=this._bufferService.rows&&(e.y=this._bufferService.rows-1),this._restrictCursor()},t.prototype.tabSet=function(){this._bufferService.buffer.tabs[this._bufferService.buffer.x]=!0},t.prototype.reverseIndex=function(){this._restrictCursor();var e=this._bufferService.buffer;if(e.y===e.scrollTop){var t=e.scrollBottom-e.scrollTop;e.lines.shiftElements(e.y+e.ybase,t,1),e.lines.set(e.y+e.ybase,e.getBlankLine(this._terminal.eraseAttrData())),this._dirtyRowService.markRangeDirty(e.scrollTop,e.scrollBottom)}else e.y--,this._restrictCursor()},t.prototype.reset=function(){this._parser.reset(),this._terminal.reset()},t.prototype.setgLevel=function(e){this._terminal.setgLevel(e)},t.prototype.screenAlignmentPattern=function(){var e=new p.CellData;e.content=1<<22|"E".charCodeAt(0),e.fg=this._terminal.curAttrData.fg,e.bg=this._terminal.curAttrData.bg;var t=this._bufferService.buffer;this._setCursor(0,0);for(var i=0;i<this._bufferService.rows;++i){var r=t.y+t.ybase+i;t.lines.get(r).fill(e),t.lines.get(r).isWrapped=!1}this._dirtyRowService.markAllDirty(),this._setCursor(0,0)},t}(l.Disposable);t.InputHandler=C},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(2),o=i(14),a=i(19),c=i(20),l=i(22),h=function(){function e(e){this.table=new Uint8Array(e)}return e.prototype.setDefault=function(e,t){o.fill(this.table,e<<4|t)},e.prototype.add=function(e,t,i,r){this.table[t<<8|e]=i<<4|r},e.prototype.addMany=function(e,t,i,r){for(var n=0;n<e.length;n++)this.table[t<<8|e[n]]=i<<4|r},e}();t.TransitionTable=h;t.VT500_TRANSITION_TABLE=function(){var e=new h(4095),t=Array.apply(null,Array(256)).map(function(e,t){return t}),i=function(e,i){return t.slice(e,i)},r=i(32,127),n=i(0,24);n.push(25),n.push.apply(n,i(28,32));var s,o=i(0,14);for(s in e.setDefault(1,0),e.addMany(r,0,2,0),o)e.addMany([24,26,153,154],s,3,0),e.addMany(i(128,144),s,3,0),e.addMany(i(144,152),s,3,0),e.add(156,s,0,0),e.add(27,s,11,1),e.add(157,s,4,8),e.addMany([152,158,159],s,0,7),e.add(155,s,11,3),e.add(144,s,11,9);return e.addMany(n,0,3,0),e.addMany(n,1,3,1),e.add(127,1,0,1),e.addMany(n,8,0,8),e.addMany(n,3,3,3),e.add(127,3,0,3),e.addMany(n,4,3,4),e.add(127,4,0,4),e.addMany(n,6,3,6),e.addMany(n,5,3,5),e.add(127,5,0,5),e.addMany(n,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(n,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(n,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(n,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(n,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(n,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(n,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}();var u=function(e){function i(i){void 0===i&&(i=t.VT500_TRANSITION_TABLE);var r=e.call(this)||this;return r.TRANSITIONS=i,r.initialState=0,r.currentState=r.initialState,r._params=new a.Params,r._params.addParam(0),r._collect=0,r.precedingCodepoint=0,r._printHandlerFb=function(e,t,i){},r._executeHandlerFb=function(e){},r._csiHandlerFb=function(e,t){},r._escHandlerFb=function(e){},r._errorHandlerFb=function(e){return e},r._printHandler=r._printHandlerFb,r._executeHandlers=Object.create(null),r._csiHandlers=Object.create(null),r._escHandlers=Object.create(null),r._oscParser=new c.OscParser,r._dcsParser=new l.DcsParser,r._errorHandler=r._errorHandlerFb,r.setEscHandler({final:"\\"},function(){}),r}return n(i,e),i.prototype._identifier=function(e,t){void 0===t&&(t=[64,126]);var i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if((i=e.prefix.charCodeAt(0))&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(var r=0;r<e.intermediates.length;++r){var n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=n}}if(1!==e.final.length)throw new Error("final must be a single byte");var s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error("final must be in range "+t[0]+" .. "+t[1]);return i<<=8,i|=s},i.prototype.identToString=function(e){for(var t=[];e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")},i.prototype.dispose=function(){this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null),this._oscParser.dispose(),this._dcsParser.dispose()},i.prototype.setPrintHandler=function(e){this._printHandler=e},i.prototype.clearPrintHandler=function(){this._printHandler=this._printHandlerFb},i.prototype.addEscHandler=function(e,t){var i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);var r=this._escHandlers[i];return r.push(t),{dispose:function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}}},i.prototype.setEscHandler=function(e,t){this._escHandlers[this._identifier(e,[48,126])]=[t]},i.prototype.clearEscHandler=function(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]},i.prototype.setEscHandlerFallback=function(e){this._escHandlerFb=e},i.prototype.setExecuteHandler=function(e,t){this._executeHandlers[e.charCodeAt(0)]=t},i.prototype.clearExecuteHandler=function(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]},i.prototype.setExecuteHandlerFallback=function(e){this._executeHandlerFb=e},i.prototype.addCsiHandler=function(e,t){var i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);var r=this._csiHandlers[i];return r.push(t),{dispose:function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}}},i.prototype.setCsiHandler=function(e,t){this._csiHandlers[this._identifier(e)]=[t]},i.prototype.clearCsiHandler=function(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]},i.prototype.setCsiHandlerFallback=function(e){this._csiHandlerFb=e},i.prototype.addDcsHandler=function(e,t){return this._dcsParser.addHandler(this._identifier(e),t)},i.prototype.setDcsHandler=function(e,t){this._dcsParser.setHandler(this._identifier(e),t)},i.prototype.clearDcsHandler=function(e){this._dcsParser.clearHandler(this._identifier(e))},i.prototype.setDcsHandlerFallback=function(e){this._dcsParser.setHandlerFallback(e)},i.prototype.addOscHandler=function(e,t){return this._oscParser.addHandler(e,t)},i.prototype.setOscHandler=function(e,t){this._oscParser.setHandler(e,t)},i.prototype.clearOscHandler=function(e){this._oscParser.clearHandler(e)},i.prototype.setOscHandlerFallback=function(e){this._oscParser.setHandlerFallback(e)},i.prototype.setErrorHandler=function(e){this._errorHandler=e},i.prototype.clearErrorHandler=function(){this._errorHandler=this._errorHandlerFb},i.prototype.reset=function(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0},i.prototype.parse=function(e,t){for(var i=0,r=0,n=this.currentState,s=this._oscParser,o=this._dcsParser,a=this._collect,c=this._params,l=this.TRANSITIONS.table,h=0;h<t;++h){switch((r=l[n<<8|((i=e[h])<160?i:160)])>>4){case 2:for(var u=h+1;;++u){if(u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingCodepoint=0;break;case 0:break;case 1:if(this._errorHandler({position:h,code:i,currentState:n,collect:a,params:c,abort:!1}).abort)return;break;case 7:for(var f=this._csiHandlers[a<<8|i],_=f?f.length-1:-1;_>=0&&!1===f[_](c);_--);_<0&&this._csiHandlerFb(a<<8|i,c),this.precedingCodepoint=0;break;case 8:do{switch(i){case 59:c.addParam(0);break;case 58:c.addSubParam(-1);break;default:c.addDigit(i-48)}}while(++h<t&&(i=e[h])>47&&i<60);h--;break;case 9:a<<=8,a|=i;break;case 10:for(var d=this._escHandlers[a<<8|i],p=d?d.length-1:-1;p>=0&&!1===d[p]();p--);p<0&&this._escHandlerFb(a<<8|i),this.precedingCodepoint=0;break;case 11:c.reset(),c.addParam(0),a=0;break;case 12:o.hook(a<<8|i,c);break;case 13:for(var v=h+1;;++v)if(v>=t||24===(i=e[v])||26===i||27===i||i>127&&i<160){o.put(e,h,v),h=v-1;break}break;case 14:o.unhook(24!==i&&26!==i),27===i&&(r|=1),c.reset(),c.addParam(0),a=0,this.precedingCodepoint=0;break;case 4:s.start();break;case 5:for(var g=h+1;;g++)if(g>=t||(i=e[g])<32||i>127&&i<=159){s.put(e,h,g),h=g-1;break}break;case 6:s.end(24!==i&&26!==i),27===i&&(r|=1),c.reset(),c.addParam(0),a=0,this.precedingCodepoint=0}n=15&r}this._collect=a,this.currentState=n},i}(s.Disposable);t.EscapeSequenceParser=u},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(40),o=i(45),a=i(46),c=i(47),l=i(27),h=i(2),u=i(23),f=1,_=function(e){function t(t,i,r,n,h){var u=e.call(this)||this;u._colors=t,u._terminal=i,u.bufferService=r,u._charSizeService=n,u.optionsService=h,u._id=f++;var _=u._terminal.options.allowTransparency;return u._characterJoinerRegistry=new l.CharacterJoinerRegistry(r),u._renderLayers=[new s.TextRenderLayer(u._terminal.screenElement,0,u._colors,u._characterJoinerRegistry,_,u._id,r,h),new o.SelectionRenderLayer(u._terminal.screenElement,1,u._colors,u._id,r,h),new c.LinkRenderLayer(u._terminal.screenElement,2,u._colors,u._id,u._terminal.linkifier,r,h),new a.CursorRenderLayer(u._terminal.screenElement,3,u._colors,u._terminal,u._id,r,h)],u.dimensions={scaledCharWidth:null,scaledCharHeight:null,scaledCellWidth:null,scaledCellHeight:null,scaledCharLeft:null,scaledCharTop:null,scaledCanvasWidth:null,scaledCanvasHeight:null,canvasWidth:null,canvasHeight:null,actualCellWidth:null,actualCellHeight:null},u._devicePixelRatio=window.devicePixelRatio,u._updateDimensions(),u.onOptionsChanged(),u}return n(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._renderLayers.forEach(function(e){return e.dispose()}),u.removeTerminalFromCache(this._id)},t.prototype.onDevicePixelRatioChange=function(){this._devicePixelRatio!==window.devicePixelRatio&&(this._devicePixelRatio=window.devicePixelRatio,this.onResize(this._terminal.cols,this._terminal.rows))},t.prototype.setColors=function(e){var t=this;this._colors=e,this._renderLayers.forEach(function(e){e.setColors(t._colors),e.reset()})},t.prototype.onResize=function(e,t){var i=this;this._updateDimensions(),this._renderLayers.forEach(function(e){return e.resize(i.dimensions)}),this._terminal.screenElement.style.width=this.dimensions.canvasWidth+"px",this._terminal.screenElement.style.height=this.dimensions.canvasHeight+"px"},t.prototype.onCharSizeChanged=function(){this.onResize(this._terminal.cols,this._terminal.rows)},t.prototype.onBlur=function(){this._runOperation(function(e){return e.onBlur()})},t.prototype.onFocus=function(){this._runOperation(function(e){return e.onFocus()})},t.prototype.onSelectionChanged=function(e,t,i){void 0===i&&(i=!1),this._runOperation(function(r){return r.onSelectionChanged(e,t,i)})},t.prototype.onCursorMove=function(){this._runOperation(function(e){return e.onCursorMove()})},t.prototype.onOptionsChanged=function(){this._runOperation(function(e){return e.onOptionsChanged()})},t.prototype.clear=function(){this._runOperation(function(e){return e.reset()})},t.prototype._runOperation=function(e){this._renderLayers.forEach(function(t){return e(t)})},t.prototype.renderRows=function(e,t){this._renderLayers.forEach(function(i){return i.onGridChanged(e,t)})},t.prototype._updateDimensions=function(){this._charSizeService.hasValidSize&&(this.dimensions.scaledCharWidth=Math.floor(this._charSizeService.width*window.devicePixelRatio),this.dimensions.scaledCharHeight=Math.ceil(this._charSizeService.height*window.devicePixelRatio),this.dimensions.scaledCellHeight=Math.floor(this.dimensions.scaledCharHeight*this._terminal.options.lineHeight),this.dimensions.scaledCharTop=1===this._terminal.options.lineHeight?0:Math.round((this.dimensions.scaledCellHeight-this.dimensions.scaledCharHeight)/2),this.dimensions.scaledCellWidth=this.dimensions.scaledCharWidth+Math.round(this._terminal.options.letterSpacing),this.dimensions.scaledCharLeft=Math.floor(this._terminal.options.letterSpacing/2),this.dimensions.scaledCanvasHeight=this._terminal.rows*this.dimensions.scaledCellHeight,this.dimensions.scaledCanvasWidth=this._terminal.cols*this.dimensions.scaledCellWidth,this.dimensions.canvasHeight=Math.round(this.dimensions.scaledCanvasHeight/window.devicePixelRatio),this.dimensions.canvasWidth=Math.round(this.dimensions.scaledCanvasWidth/window.devicePixelRatio),this.dimensions.actualCellHeight=this.dimensions.canvasHeight/this._terminal.rows,this.dimensions.actualCellWidth=this.dimensions.canvasWidth/this._terminal.cols)},t.prototype.registerCharacterJoiner=function(e){return this._characterJoinerRegistry.registerCharacterJoiner(e)},t.prototype.deregisterCharacterJoiner=function(e){return this._characterJoinerRegistry.deregisterCharacterJoiner(e)},t}(h.Disposable);t.Renderer=_},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(41),o=i(12),a=i(6),c=i(3),l=i(27),h=i(4),u=function(e){function t(t,i,r,n,o,a,c,l){var u=e.call(this,t,"text",i,o,r,a,c,l)||this;return u.bufferService=c,u.optionsService=l,u._characterWidth=0,u._characterFont="",u._characterOverlapCache={},u._workCell=new h.CellData,u._state=new s.GridCache,u._characterJoinerRegistry=n,u}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t);var i=this._getFont(!1,!1);this._characterWidth===t.scaledCharWidth&&this._characterFont===i||(this._characterWidth=t.scaledCharWidth,this._characterFont=i,this._characterOverlapCache={}),this._state.clear(),this._state.resize(this._bufferService.cols,this._bufferService.rows)},t.prototype.reset=function(){this._state.clear(),this._clearAll()},t.prototype._forEachCell=function(e,t,i,r){for(var n=e;n<=t;n++)for(var s=n+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.lines.get(s),a=i?i.getJoinedCharacters(s):[],h=0;h<this._bufferService.cols;h++){o.loadCell(h,this._workCell);var u=this._workCell,f=!1,_=h;if(0!==u.getWidth()){if(a.length>0&&h===a[0][0]){f=!0;var d=a.shift();u=new l.JoinedCellData(this._workCell,o.translateToString(!0,d[0],d[1]),d[1]-d[0]),_=d[1]-1}!f&&this._isOverlapping(u)&&_<o.length-1&&o.getCodePoint(_+1)===c.NULL_CELL_CODE&&(u.content&=-12582913,u.content|=2<<22),r(u,h,n),h=_}}},t.prototype._drawBackground=function(e,t){var i=this,r=this._ctx,n=this._bufferService.cols,s=0,o=0,c=null;r.save(),this._forEachCell(e,t,null,function(e,t,l){var h=null;e.isInverse()?h=e.isFgDefault()?i._colors.foreground.css:e.isFgRGB()?"rgb("+a.AttributeData.toColorRGB(e.getFgColor()).join(",")+")":i._colors.ansi[e.getFgColor()].css:e.isBgRGB()?h="rgb("+a.AttributeData.toColorRGB(e.getBgColor()).join(",")+")":e.isBgPalette()&&(h=i._colors.ansi[e.getBgColor()].css),null===c&&(s=t,o=l),l!==o?(r.fillStyle=c||"",i._fillCells(s,o,n-s,1),s=t,o=l):c!==h&&(r.fillStyle=c||"",i._fillCells(s,o,t-s,1),s=t,o=l),c=h}),null!==c&&(r.fillStyle=c,this._fillCells(s,o,n-s,1)),r.restore()},t.prototype._drawForeground=function(e,t){var i=this;this._forEachCell(e,t,this._characterJoinerRegistry,function(e,t,r){if(!e.isInvisible()&&(i._drawChars(e,t,r),e.isUnderline())){if(i._ctx.save(),e.isInverse())e.isBgDefault()?i._ctx.fillStyle=i._colors.background.css:e.isBgRGB()?i._ctx.fillStyle="rgb("+a.AttributeData.toColorRGB(e.getBgColor()).join(",")+")":i._ctx.fillStyle=i._colors.ansi[e.getBgColor()].css;else if(e.isFgDefault())i._ctx.fillStyle=i._colors.foreground.css;else if(e.isFgRGB())i._ctx.fillStyle="rgb("+a.AttributeData.toColorRGB(e.getFgColor()).join(",")+")";else{var n=e.getFgColor();i._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&n<8&&(n+=8),i._ctx.fillStyle=i._colors.ansi[n].css}i._fillBottomLineAtCells(t,r,e.getWidth()),i._ctx.restore()}})},t.prototype.onGridChanged=function(e,t){0!==this._state.cache.length&&(this._charAtlas&&this._charAtlas.beginFrame(),this._clearCells(0,e,this._bufferService.cols,t-e+1),this._drawBackground(e,t),this._drawForeground(e,t))},t.prototype.onOptionsChanged=function(){this._setTransparency(this._optionsService.options.allowTransparency)},t.prototype._isOverlapping=function(e){if(1!==e.getWidth())return!1;if(e.getCode()<256)return!1;var t=e.getChars();if(this._characterOverlapCache.hasOwnProperty(t))return this._characterOverlapCache[t];this._ctx.save(),this._ctx.font=this._characterFont;var i=Math.floor(this._ctx.measureText(t).width)>this._characterWidth;return this._ctx.restore(),this._characterOverlapCache[t]=i,i},t}(o.BaseRenderLayer);t.TextRenderLayer=u},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.cache=[]}return e.prototype.resize=function(e,t){for(var i=0;i<e;i++){this.cache.length<=i&&this.cache.push([]);for(var r=this.cache[i].length;r<t;r++)this.cache[i].push(void 0);this.cache[i].length=t}this.cache.length=e},e.prototype.clear=function(){for(var e=0;e<this.cache.length;e++)for(var t=0;t<this.cache[e].length;t++)this.cache[e][t]=void 0},e}();t.GridCache=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(9),o=i(43),a=i(25),c=i(44),l=i(10),h=i(26),u=1024,f=1024,_={css:"rgba(0, 0, 0, 0)",rgba:0};function d(e){return e.code<<21|e.bg<<12|e.fg<<3|(e.bold?0:4)+(e.dim?0:2)+(e.italic?0:1)}t.getGlyphCacheKey=d;var p=function(e){function t(t,i){var r=e.call(this)||this;r._config=i,r._drawToCacheCount=0,r._glyphsWaitingOnBitmap=[],r._bitmapCommitTimeout=null,r._bitmap=null,r._cacheCanvas=t.createElement("canvas"),r._cacheCanvas.width=u,r._cacheCanvas.height=f,r._cacheCtx=h.throwIfFalsy(r._cacheCanvas.getContext("2d",{alpha:!0}));var n=t.createElement("canvas");n.width=r._config.scaledCharWidth,n.height=r._config.scaledCharHeight,r._tmpCtx=h.throwIfFalsy(n.getContext("2d",{alpha:r._config.allowTransparency})),r._width=Math.floor(u/r._config.scaledCharWidth),r._height=Math.floor(f/r._config.scaledCharHeight);var s=r._width*r._height;return r._cacheMap=new c.LRUMap(s),r._cacheMap.prealloc(s),r}return n(t,e),t.prototype.dispose=function(){null!==this._bitmapCommitTimeout&&(window.clearTimeout(this._bitmapCommitTimeout),this._bitmapCommitTimeout=null)},t.prototype.beginFrame=function(){this._drawToCacheCount=0},t.prototype.draw=function(e,t,i,r){if(32===t.code)return!0;if(!this._canCache(t))return!1;var n=d(t),s=this._cacheMap.get(n);if(null!=s)return this._drawFromCache(e,s,i,r),!0;if(this._drawToCacheCount<100){var o=void 0;o=this._cacheMap.size<this._cacheMap.capacity?this._cacheMap.size:this._cacheMap.peek().index;var a=this._drawToCache(t,o);return this._cacheMap.set(n,a),this._drawFromCache(e,a,i,r),!0}return!1},t.prototype._canCache=function(e){return e.code<256},t.prototype._toCoordinateX=function(e){return e%this._width*this._config.scaledCharWidth},t.prototype._toCoordinateY=function(e){return Math.floor(e/this._width)*this._config.scaledCharHeight},t.prototype._drawFromCache=function(e,t,i,r){if(!t.isEmpty){var n=this._toCoordinateX(t.index),s=this._toCoordinateY(t.index);e.drawImage(t.inBitmap?this._bitmap:this._cacheCanvas,n,s,this._config.scaledCharWidth,this._config.scaledCharHeight,i,r,this._config.scaledCharWidth,this._config.scaledCharHeight)}},t.prototype._getColorFromAnsiIndex=function(e){return e<this._config.colors.ansi.length?this._config.colors.ansi[e]:a.DEFAULT_ANSI_COLORS[e]},t.prototype._getBackgroundColor=function(e){return this._config.allowTransparency?_:e.bg===s.INVERTED_DEFAULT_COLOR?this._config.colors.foreground:e.bg<256?this._getColorFromAnsiIndex(e.bg):this._config.colors.background},t.prototype._getForegroundColor=function(e){return e.fg===s.INVERTED_DEFAULT_COLOR?this._config.colors.background:e.fg<256?this._getColorFromAnsiIndex(e.fg):this._config.colors.foreground},t.prototype._drawToCache=function(e,t){this._drawToCacheCount++,this._tmpCtx.save();var i=this._getBackgroundColor(e);this._tmpCtx.globalCompositeOperation="copy",this._tmpCtx.fillStyle=i.css,this._tmpCtx.fillRect(0,0,this._config.scaledCharWidth,this._config.scaledCharHeight),this._tmpCtx.globalCompositeOperation="source-over";var r=e.bold?this._config.fontWeightBold:this._config.fontWeight,n=e.italic?"italic":"";this._tmpCtx.font=n+" "+r+" "+this._config.fontSize*this._config.devicePixelRatio+"px "+this._config.fontFamily,this._tmpCtx.textBaseline="middle",this._tmpCtx.fillStyle=this._getForegroundColor(e).css,e.dim&&(this._tmpCtx.globalAlpha=s.DIM_OPACITY),this._tmpCtx.fillText(e.chars,0,this._config.scaledCharHeight/2),this._tmpCtx.restore();var o=this._tmpCtx.getImageData(0,0,this._config.scaledCharWidth,this._config.scaledCharHeight),a=!1;this._config.allowTransparency||(a=function(e,t){for(var i=!0,r=t.rgba>>>24,n=t.rgba>>>16&255,s=t.rgba>>>8&255,o=0;o<e.data.length;o+=4)e.data[o]===r&&e.data[o+1]===n&&e.data[o+2]===s?e.data[o+3]=0:i=!1;return i}(o,i));var c=this._toCoordinateX(t),l=this._toCoordinateY(t);this._cacheCtx.putImageData(o,c,l);var h={index:t,isEmpty:a,inBitmap:!1};return this._addGlyphToBitmap(h),h},t.prototype._addGlyphToBitmap=function(e){var t=this;"createImageBitmap"in window&&!l.isFirefox&&!l.isSafari&&(this._glyphsWaitingOnBitmap.push(e),null===this._bitmapCommitTimeout&&(this._bitmapCommitTimeout=window.setTimeout(function(){return t._generateBitmap()},100)))},t.prototype._generateBitmap=function(){var e=this,t=this._glyphsWaitingOnBitmap;this._glyphsWaitingOnBitmap=[],window.createImageBitmap(this._cacheCanvas).then(function(i){e._bitmap=i;for(var r=0;r<t.length;r++){t[r].inBitmap=!0}}),this._bitmapCommitTimeout=null},t}(o.BaseCharAtlas);t.DynamicCharAtlas=p;var v=function(e){function t(t,i){return e.call(this)||this}return n(t,e),t.prototype.draw=function(e,t,i,r){return!1},t}(o.BaseCharAtlas);t.NoneCharAtlas=v},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._didWarmUp=!1}return e.prototype.dispose=function(){},e.prototype.warmUp=function(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)},e.prototype._doWarmUp=function(){},e.prototype.beginFrame=function(){},e}();t.BaseCharAtlas=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this.capacity=e,this._map={},this._head=null,this._tail=null,this._nodePool=[],this.size=0}return e.prototype._unlinkNode=function(e){var t=e.prev,i=e.next;e===this._head&&(this._head=i),e===this._tail&&(this._tail=t),null!==t&&(t.next=i),null!==i&&(i.prev=t)},e.prototype._appendNode=function(e){var t=this._tail;null!==t&&(t.next=e),e.prev=t,e.next=null,this._tail=e,null===this._head&&(this._head=e)},e.prototype.prealloc=function(e){for(var t=this._nodePool,i=0;i<e;i++)t.push({prev:null,next:null,key:null,value:null})},e.prototype.get=function(e){var t=this._map[e];return void 0!==t?(this._unlinkNode(t),this._appendNode(t),t.value):null},e.prototype.peekValue=function(e){var t=this._map[e];return void 0!==t?t.value:null},e.prototype.peek=function(){var e=this._head;return null===e?null:e.value},e.prototype.set=function(e,t){var i=this._map[e];if(void 0!==i)i=this._map[e],this._unlinkNode(i),i.value=t;else if(this.size>=this.capacity)i=this._head,this._unlinkNode(i),delete this._map[i.key],i.key=e,i.value=t,this._map[e]=i;else{var r=this._nodePool;r.length>0?((i=r.pop()).key=e,i.value=t):i={prev:null,next:null,key:e,value:t},this._map[e]=i,this.size++}this._appendNode(i)},e}();t.LRUMap=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(t,i,r,n,s,o){var a=e.call(this,t,"selection",i,!0,r,n,s,o)||this;return a.bufferService=s,a.optionsService=o,a._clearState(),a}return n(t,e),t.prototype._clearState=function(){this._state={start:void 0,end:void 0,columnSelectMode:void 0,ydisp:void 0}},t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._clearState()},t.prototype.reset=function(){this._state.start&&this._state.end&&(this._clearState(),this._clearAll())},t.prototype.onSelectionChanged=function(e,t,i){if(this._didStateChange(e,t,i,this._bufferService.buffer.ydisp))if(this._clearAll(),e&&t){var r=e[1]-this._bufferService.buffer.ydisp,n=t[1]-this._bufferService.buffer.ydisp,s=Math.max(r,0),o=Math.min(n,this._bufferService.rows-1);if(!(s>=this._bufferService.rows||o<0)){if(this._ctx.fillStyle=this._colors.selection.css,i){var a=e[0],c=t[0]-a,l=o-s+1;this._fillCells(a,s,c,l)}else{a=r===s?e[0]:0;var h=s===o?t[0]:this._bufferService.cols;this._fillCells(a,s,h-a,1);var u=Math.max(o-s-1,0);if(this._fillCells(0,s+1,this._bufferService.cols,u),s!==o){var f=n===o?t[0]:this._bufferService.cols;this._fillCells(0,o,f,1)}}this._state.start=[e[0],e[1]],this._state.end=[t[0],t[1]],this._state.columnSelectMode=i,this._state.ydisp=this._bufferService.buffer.ydisp}}else this._clearState()},t.prototype._didStateChange=function(e,t,i,r){return!this._areCoordinatesEqual(e,this._state.start)||!this._areCoordinatesEqual(t,this._state.end)||i!==this._state.columnSelectMode||r!==this._state.ydisp},t.prototype._areCoordinatesEqual=function(e,t){return!(!e||!t)&&(e[0]===t[0]&&e[1]===t[1])},t}(i(12).BaseRenderLayer);t.SelectionRenderLayer=s},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(12),o=i(4),a=function(e){function t(t,i,r,n,s,a,c){var l=e.call(this,t,"cursor",i,!0,r,s,a,c)||this;return l._terminal=n,l.bufferService=a,l.optionsService=c,l._cell=new o.CellData,l._state={x:null,y:null,isFocused:null,style:null,width:null},l._cursorRenderers={bar:l._renderBarCursor.bind(l),block:l._renderBlockCursor.bind(l),underline:l._renderUnderlineCursor.bind(l)},l}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._state={x:null,y:null,isFocused:null,style:null,width:null}},t.prototype.reset=function(){this._clearCursor(),this._cursorBlinkStateManager&&(this._cursorBlinkStateManager.dispose(),this._cursorBlinkStateManager=null,this.onOptionsChanged())},t.prototype.onBlur=function(){this._cursorBlinkStateManager&&this._cursorBlinkStateManager.pause(),this._terminal.refresh(this._bufferService.buffer.y,this._bufferService.buffer.y)},t.prototype.onFocus=function(){this._cursorBlinkStateManager?this._cursorBlinkStateManager.resume():this._terminal.refresh(this._bufferService.buffer.y,this._bufferService.buffer.y)},t.prototype.onOptionsChanged=function(){var e=this;this._optionsService.options.cursorBlink?this._cursorBlinkStateManager||(this._cursorBlinkStateManager=new c(this._terminal.isFocused,function(){e._render(!0)})):this._cursorBlinkStateManager&&(this._cursorBlinkStateManager.dispose(),this._cursorBlinkStateManager=null),this._terminal.refresh(this._bufferService.buffer.y,this._bufferService.buffer.y)},t.prototype.onCursorMove=function(){this._cursorBlinkStateManager&&this._cursorBlinkStateManager.restartBlinkAnimation()},t.prototype.onGridChanged=function(e,t){!this._cursorBlinkStateManager||this._cursorBlinkStateManager.isPaused?this._render(!1):this._cursorBlinkStateManager.restartBlinkAnimation()},t.prototype._render=function(e){if(this._terminal.cursorState&&!this._terminal.cursorHidden){var t=this._bufferService.buffer.ybase+this._bufferService.buffer.y,i=t-this._bufferService.buffer.ydisp;if(i<0||i>=this._bufferService.rows)this._clearCursor();else if(this._bufferService.buffer.lines.get(t).loadCell(this._bufferService.buffer.x,this._cell),void 0!==this._cell.content){if(!this._terminal.isFocused){this._clearCursor(),this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css;var r=this._optionsService.options.cursorStyle;return r&&"block"!==r?this._cursorRenderers[r](this._bufferService.buffer.x,i,this._cell):this._renderBlurCursor(this._bufferService.buffer.x,i,this._cell),this._ctx.restore(),this._state.x=this._bufferService.buffer.x,this._state.y=i,this._state.isFocused=!1,this._state.style=r,void(this._state.width=this._cell.getWidth())}if(!this._cursorBlinkStateManager||this._cursorBlinkStateManager.isCursorVisible){if(this._state){if(this._state.x===this._bufferService.buffer.x&&this._state.y===i&&this._state.isFocused===this._terminal.isFocused&&this._state.style===this._optionsService.options.cursorStyle&&this._state.width===this._cell.getWidth())return;this._clearCursor()}this._ctx.save(),this._cursorRenderers[this._optionsService.options.cursorStyle||"block"](this._bufferService.buffer.x,i,this._cell),this._ctx.restore(),this._state.x=this._bufferService.buffer.x,this._state.y=i,this._state.isFocused=!1,this._state.style=this._optionsService.options.cursorStyle,this._state.width=this._cell.getWidth()}else this._clearCursor()}}else this._clearCursor()},t.prototype._clearCursor=function(){this._state&&(this._clearCells(this._state.x,this._state.y,this._state.width,1),this._state={x:null,y:null,isFocused:null,style:null,width:null})},t.prototype._renderBarCursor=function(e,t,i){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillLeftLineAtCell(e,t),this._ctx.restore()},t.prototype._renderBlockCursor=function(e,t,i){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillCells(e,t,i.getWidth(),1),this._ctx.fillStyle=this._colors.cursorAccent.css,this._fillCharTrueColor(i,e,t),this._ctx.restore()},t.prototype._renderUnderlineCursor=function(e,t,i){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillBottomLineAtCells(e,t),this._ctx.restore()},t.prototype._renderBlurCursor=function(e,t,i){this._ctx.save(),this._ctx.strokeStyle=this._colors.cursor.css,this._strokeRectAtCell(e,t,i.getWidth(),1),this._ctx.restore()},t}(s.BaseRenderLayer);t.CursorRenderLayer=a;var c=function(){function e(e,t){this._renderCallback=t,this.isCursorVisible=!0,e&&this._restartInterval()}return Object.defineProperty(e.prototype,"isPaused",{get:function(){return!(this._blinkStartTimeout||this._blinkInterval)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._blinkInterval&&(window.clearInterval(this._blinkInterval),this._blinkInterval=null),this._blinkStartTimeout&&(window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=null),this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=null)},e.prototype.restartBlinkAnimation=function(){var e=this;this.isPaused||(this._animationTimeRestarted=Date.now(),this.isCursorVisible=!0,this._animationFrame||(this._animationFrame=window.requestAnimationFrame(function(){e._renderCallback(),e._animationFrame=null})))},e.prototype._restartInterval=function(e){var t=this;void 0===e&&(e=600),this._blinkInterval&&window.clearInterval(this._blinkInterval),this._blinkStartTimeout=setTimeout(function(){if(t._animationTimeRestarted){var e=600-(Date.now()-t._animationTimeRestarted);if(t._animationTimeRestarted=null,e>0)return void t._restartInterval(e)}t.isCursorVisible=!1,t._animationFrame=window.requestAnimationFrame(function(){t._renderCallback(),t._animationFrame=null}),t._blinkInterval=setInterval(function(){if(t._animationTimeRestarted){var e=600-(Date.now()-t._animationTimeRestarted);return t._animationTimeRestarted=null,void t._restartInterval(e)}t.isCursorVisible=!t.isCursorVisible,t._animationFrame=window.requestAnimationFrame(function(){t._renderCallback(),t._animationFrame=null})},600)},e)},e.prototype.pause=function(){this.isCursorVisible=!0,this._blinkInterval&&(window.clearInterval(this._blinkInterval),this._blinkInterval=null),this._blinkStartTimeout&&(window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=null),this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=null)},e.prototype.resume=function(){this._animationTimeRestarted=null,this._restartInterval(),this.restartBlinkAnimation()},e}()},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(12),o=i(9),a=i(24),c=function(e){function t(t,i,r,n,s,o,a){var c=e.call(this,t,"link",i,!0,r,n,o,a)||this;return c.bufferService=o,c.optionsService=a,s.onLinkHover(function(e){return c._onLinkHover(e)}),s.onLinkLeave(function(e){return c._onLinkLeave(e)}),c}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._state=void 0},t.prototype.reset=function(){this._clearCurrentLink()},t.prototype._clearCurrentLink=function(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);var e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}},t.prototype._onLinkHover=function(e){if(e.fg===o.INVERTED_DEFAULT_COLOR?this._ctx.fillStyle=this._colors.background.css:e.fg&&a.is256Color(e.fg)?this._ctx.fillStyle=this._colors.ansi[e.fg].css:this._ctx.fillStyle=this._colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(var t=e.y1+1;t<e.y2;t++)this._fillBottomLineAtCells(0,t,e.cols);this._fillBottomLineAtCells(0,e.y2,e.x2)}this._state=e},t.prototype._onLinkLeave=function(e){this._clearCurrentLink()},t}(s.BaseRenderLayer);t.LinkRenderLayer=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(18),n=i(1),s=function(){function e(e,t){this._bufferService=e,this._logService=t,this._linkMatchers=[],this._nextLinkMatcherId=0,this._onLinkHover=new n.EventEmitter,this._onLinkLeave=new n.EventEmitter,this._onLinkTooltip=new n.EventEmitter,this._rowsToLinkify={start:void 0,end:void 0}}return Object.defineProperty(e.prototype,"onLinkHover",{get:function(){return this._onLinkHover.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onLinkLeave",{get:function(){return this._onLinkLeave.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onLinkTooltip",{get:function(){return this._onLinkTooltip.event},enumerable:!0,configurable:!0}),e.prototype.attachToDom=function(e,t){this._element=e,this._mouseZoneManager=t},e.prototype.linkifyRows=function(t,i){var r=this;this._mouseZoneManager&&(void 0===this._rowsToLinkify.start||void 0===this._rowsToLinkify.end?(this._rowsToLinkify.start=t,this._rowsToLinkify.end=i):(this._rowsToLinkify.start=Math.min(this._rowsToLinkify.start,t),this._rowsToLinkify.end=Math.max(this._rowsToLinkify.end,i)),this._mouseZoneManager.clearAll(t,i),this._rowsTimeoutId&&clearTimeout(this._rowsTimeoutId),this._rowsTimeoutId=setTimeout(function(){return r._linkifyRows()},e._timeBeforeLatency))},e.prototype._linkifyRows=function(){this._rowsTimeoutId=void 0;var e=this._bufferService.buffer;if(void 0!==this._rowsToLinkify.start&&void 0!==this._rowsToLinkify.end){var t=e.ydisp+this._rowsToLinkify.start;if(!(t>=e.lines.length)){for(var i=e.ydisp+Math.min(this._rowsToLinkify.end,this._bufferService.rows)+1,r=Math.ceil(2e3/this._bufferService.cols),n=this._bufferService.buffer.iterator(!1,t,i,r,r);n.hasNext();)for(var s=n.next(),o=0;o<this._linkMatchers.length;o++)this._doLinkifyRow(s.range.first,s.content,this._linkMatchers[o]);this._rowsToLinkify.start=void 0,this._rowsToLinkify.end=void 0}}else this._logService.debug("_rowToLinkify was unset before _linkifyRows was called")},e.prototype.registerLinkMatcher=function(e,t,i){if(void 0===i&&(i={}),!t)throw new Error("handler must be defined");var r={id:this._nextLinkMatcherId++,regex:e,handler:t,matchIndex:i.matchIndex,validationCallback:i.validationCallback,hoverTooltipCallback:i.tooltipCallback,hoverLeaveCallback:i.leaveCallback,willLinkActivate:i.willLinkActivate,priority:i.priority||0};return this._addLinkMatcherToList(r),r.id},e.prototype._addLinkMatcherToList=function(e){if(0!==this._linkMatchers.length){for(var t=this._linkMatchers.length-1;t>=0;t--)if(e.priority<=this._linkMatchers[t].priority)return void this._linkMatchers.splice(t+1,0,e);this._linkMatchers.splice(0,0,e)}else this._linkMatchers.push(e)},e.prototype.deregisterLinkMatcher=function(e){for(var t=0;t<this._linkMatchers.length;t++)if(this._linkMatchers[t].id===e)return this._linkMatchers.splice(t,1),!0;return!1},e.prototype._doLinkifyRow=function(e,t,i){for(var r,n=this,s=new RegExp(i.regex.source,(i.regex.flags||"")+"g"),o=-1,a=function(){var a=r["number"!=typeof i.matchIndex?0:i.matchIndex];if(!a)return c._logService.debug("match found without corresponding matchIndex",r,i),"break";if(o=t.indexOf(a,o+1),s.lastIndex=o+a.length,o<0)return"break";var l=c._bufferService.buffer.stringIndexToBufferIndex(e,o);if(l[0]<0)return"break";var h=c._bufferService.buffer.lines.get(l[0]);if(!h)return"break";var u=h.getFg(l[1]),f=u?u>>9&511:void 0;i.validationCallback?i.validationCallback(a,function(e){n._rowsTimeoutId||e&&n._addLink(l[1],l[0]-n._bufferService.buffer.ydisp,a,i,f)}):c._addLink(l[1],l[0]-c._bufferService.buffer.ydisp,a,i,f)},c=this;null!==(r=s.exec(t));){if("break"===a())break}},e.prototype._addLink=function(e,t,i,n,s){var a=this;if(this._mouseZoneManager&&this._element){var c=r.getStringCellWidth(i),l=e%this._bufferService.cols,h=t+Math.floor(e/this._bufferService.cols),u=(l+c)%this._bufferService.cols,f=h+Math.floor((l+c)/this._bufferService.cols);0===u&&(u=this._bufferService.cols,f--),this._mouseZoneManager.add(new o(l+1,h+1,u+1,f+1,function(e){if(n.handler)return n.handler(e,i);window.open(i,"_blank")},function(){a._onLinkHover.fire(a._createLinkHoverEvent(l,h,u,f,s)),a._element.classList.add("xterm-cursor-pointer")},function(e){a._onLinkTooltip.fire(a._createLinkHoverEvent(l,h,u,f,s)),n.hoverTooltipCallback&&n.hoverTooltipCallback(e,i,{start:{x:l,y:h},end:{x:u,y:f}})},function(){a._onLinkLeave.fire(a._createLinkHoverEvent(l,h,u,f,s)),a._element.classList.remove("xterm-cursor-pointer"),n.hoverLeaveCallback&&n.hoverLeaveCallback()},function(e){return!n.willLinkActivate||n.willLinkActivate(e,i)}))}},e.prototype._createLinkHoverEvent=function(e,t,i,r,n){return{x1:e,y1:t,x2:i,y2:r,cols:this._bufferService.cols,fg:n}},e._timeBeforeLatency=200,e}();t.Linkifier=s;var o=function(e,t,i,r,n,s,o,a,c){this.x1=e,this.y1=t,this.x2=i,this.y2=r,this.clickCallback=n,this.hoverCallback=s,this.tooltipCallback=o,this.leaveCallback=a,this.willLinkActivate=c};t.MouseZone=o},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(10),o=i(50),a=i(4),c=i(1),l=i(5),h=i(0),u=i(28),f=i(51),_=String.fromCharCode(160),d=new RegExp(_,"g"),p=function(){function e(e,t,i,r,n,s,l,h){var u=this;this._scrollLines=e,this._element=t,this._screenElement=i,this._charSizeService=r,this._bufferService=n,this._coreService=s,this._mouseService=l,this._optionsService=h,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new a.CellData,this._mouseDownTimeStamp=0,this._onLinuxMouseSelection=new c.EventEmitter,this._onRedrawRequest=new c.EventEmitter,this._onSelectionChange=new c.EventEmitter,this._mouseMoveListener=function(e){return u._onMouseMove(e)},this._mouseUpListener=function(e){return u._onMouseUp(e)},this._coreService.onUserInput(function(){u.hasSelection&&u.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(function(e){return u._onTrim(e)}),this._bufferService.buffers.onBufferActivate(function(e){return u._onBufferActivate(e)}),this.enable(),this._model=new o.SelectionModel(this._bufferService),this._activeSelectionMode=0}return Object.defineProperty(e.prototype,"onLinuxMouseSelection",{get:function(){return this._onLinuxMouseSelection.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onRedrawRequest",{get:function(){return this._onRedrawRequest.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onSelectionChange",{get:function(){return this._onSelectionChange.event},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._removeMouseDownListeners()},e.prototype.reset=function(){this.clearSelection()},e.prototype.disable=function(){this.clearSelection(),this._enabled=!1},e.prototype.enable=function(){this._enabled=!0},Object.defineProperty(e.prototype,"selectionStart",{get:function(){return this._model.finalSelectionStart},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selectionEnd",{get:function(){return this._model.finalSelectionEnd},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasSelection",{get:function(){var e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t)&&(e[0]!==t[0]||e[1]!==t[1])},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selectionText",{get:function(){var e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";var i=this._bufferService.buffer,r=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";for(var n=e[1];n<=t[1];n++){var o=i.translateBufferLineToString(n,!0,e[0],t[0]);r.push(o)}}else{var a=e[1]===t[1]?t[0]:void 0;r.push(i.translateBufferLineToString(e[1],!0,e[0],a));for(n=e[1]+1;n<=t[1]-1;n++){var c=i.lines.get(n);o=i.translateBufferLineToString(n,!0);c&&c.isWrapped?r[r.length-1]+=o:r.push(o)}if(e[1]!==t[1]){c=i.lines.get(t[1]),o=i.translateBufferLineToString(t[1],!0,0,t[0]);c&&c.isWrapped?r[r.length-1]+=o:r.push(o)}}return r.map(function(e){return e.replace(d," ")}).join(s.isWindows?"\r\n":"\n")},enumerable:!0,configurable:!0}),e.prototype.clearSelection=function(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()},e.prototype.refresh=function(e){var t=this;(this._refreshAnimationFrame||(this._refreshAnimationFrame=window.requestAnimationFrame(function(){return t._refresh()})),s.isLinux&&e)&&(this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText))},e.prototype._refresh=function(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})},e.prototype.isClickInSelection=function(e){var t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!!(i&&r&&t)&&this._areCoordsInSelection(t,i,r)},e.prototype._areCoordsInSelection=function(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]},e.prototype.selectWordAtCursor=function(e){var t=this._getMouseBufferCoords(e);t&&(this._selectWordAt(t,!1),this._model.selectionEnd=void 0,this.refresh(!0))},e.prototype.selectAll=function(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()},e.prototype.selectLines=function(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()},e.prototype._onTrim=function(e){this._model.onTrim(e)&&this.refresh()},e.prototype._getMouseBufferCoords=function(e){var t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t},e.prototype._getMouseEventScrollAmount=function(e){var t=u.getCoordsRelativeToElement(e,this._screenElement)[1],i=this._bufferService.rows*Math.ceil(this._charSizeService.height*this._optionsService.options.lineHeight);return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),(t/=50)/Math.abs(t)+Math.round(14*t))},e.prototype.shouldForceSelection=function(e){return s.isMac?e.altKey&&this._optionsService.options.macOptionClickForcesSelection:e.shiftKey},e.prototype.onMouseDown=function(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._onIncrementalClick(e):1===e.detail?this._onSingleClick(e):2===e.detail?this._onDoubleClick(e):3===e.detail&&this._onTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}},e.prototype._addMouseDownListeners=function(){var e=this;this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=window.setInterval(function(){return e._dragScroll()},50)},e.prototype._removeMouseDownListeners=function(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0},e.prototype._onIncrementalClick=function(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))},e.prototype._onSingleClick=function(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),this._model.selectionStart){this._model.selectionEnd=void 0;var t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}},e.prototype._onDoubleClick=function(e){var t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=1,this._selectWordAt(t,!0))},e.prototype._onTripleClick=function(e){var t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))},e.prototype.shouldColumnSelect=function(e){return e.altKey&&!(s.isMac&&this._optionsService.options.macOptionClickForcesSelection)},e.prototype._onMouseMove=function(e){if(e.stopImmediatePropagation(),this._model.selectionStart){var t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),this._model.selectionEnd){2===this._activeSelectionMode?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:1===this._activeSelectionMode&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),3!==this._activeSelectionMode&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));var i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){var r=i.lines.get(this._model.selectionEnd[1]);r&&0===r.hasWidth(this._model.selectionEnd[0])&&this._model.selectionEnd[0]++}t&&t[0]===this._model.selectionEnd[0]&&t[1]===this._model.selectionEnd[1]||this.refresh(!0)}else this.refresh(!0)}},e.prototype._dragScroll=function(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._scrollLines(this._dragScrollAmount,!1);var e=this._bufferService.buffer;this._dragScrollAmount>0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}},e.prototype._onMouseUp=function(e){var t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500){if(e.altKey&&this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){var i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&void 0!==i[0]&&void 0!==i[1]){var r=f.moveToCellSequence(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(r,!0)}}}else this.hasSelection&&this._onSelectionChange.fire()},e.prototype._onBufferActivate=function(e){var t=this;this.clearSelection(),this._trimListener&&this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(function(e){return t._onTrim(e)})},e.prototype._convertViewportColToCharacterIndex=function(e,t){for(var i=t[0],r=0;t[0]>=r;r++){var n=e.loadCell(r,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:n>1&&t[0]!==r&&(i+=n-1)}return i},e.prototype.setSelection=function(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh()},e.prototype._getWordAt=function(e,t,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=!0),!(e[0]>=this._bufferService.cols)){var n=this._bufferService.buffer,s=n.lines.get(e[1]);if(s){var o=n.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(s,e),c=a,l=e[0]-a,h=0,u=0,f=0,_=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;c<o.length&&" "===o.charAt(c+1);)c++}else{var d=e[0],p=e[0];0===s.getWidth(d)&&(h++,d--),2===s.getWidth(p)&&(u++,p++);var v=s.getString(p).length;for(v>1&&(_+=v-1,c+=v-1);d>0&&a>0&&!this._isCharWordSeparator(s.loadCell(d-1,this._workCell));){s.loadCell(d-1,this._workCell);var g=this._workCell.getChars().length;0===this._workCell.getWidth()?(h++,d--):g>1&&(f+=g-1,a-=g-1),a--,d--}for(;p<s.length&&c+1<o.length&&!this._isCharWordSeparator(s.loadCell(p+1,this._workCell));){s.loadCell(p+1,this._workCell);var y=this._workCell.getChars().length;2===this._workCell.getWidth()?(u++,p++):y>1&&(_+=y-1,c+=y-1),c++,p++}}c++;var m=a+l-h+f,b=Math.min(this._bufferService.cols,c-a+h+u-f-_);if(t||""!==o.slice(a,c).trim()){if(i&&0===m&&32!==s.getCodePoint(0)){var C=n.lines.get(e[1]-1);if(C&&s.isWrapped&&32!==C.getCodePoint(this._bufferService.cols-1)){var S=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(S){var w=this._bufferService.cols-S.start;m-=w,b+=w}}}if(r&&m+b===this._bufferService.cols&&32!==s.getCodePoint(this._bufferService.cols-1)){var E=n.lines.get(e[1]+1);if(E&&E.isWrapped&&32!==E.getCodePoint(0)){var L=this._getWordAt([0,e[1]+1],!1,!1,!0);L&&(b+=L.length)}}return{start:m,length:b}}}}},e.prototype._selectWordAt=function(e,t){var i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}},e.prototype._selectToWordAt=function(e){var t=this._getWordAt(e,!0);if(t){for(var i=e[1];t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}},e.prototype._isCharWordSeparator=function(e){return 0!==e.getWidth()&&this._optionsService.options.wordSeparator.indexOf(e.getChars())>=0},e.prototype._selectLineAt=function(e){var t=this._bufferService.buffer.getWrappedRangeForLine(e);this._model.selectionStart=[0,t.first],this._model.selectionEnd=[this._bufferService.cols,t.last],this._model.selectionStartLength=0},e=r([n(3,l.ICharSizeService),n(4,h.IBufferService),n(5,h.ICoreService),n(6,l.IMouseService),n(7,h.IOptionsService)],e)}();t.SelectionService=p},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}return e.prototype.clearSelection=function(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0},Object.defineProperty(e.prototype,"finalSelectionStart",{get:function(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"finalSelectionEnd",{get:function(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){var e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}return this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]?[Math.max(this.selectionStart[0]+this.selectionStartLength,this.selectionEnd[0]),this.selectionEnd[1]]:this.selectionEnd}},enumerable:!0,configurable:!0}),e.prototype.areSelectionValuesReversed=function(){var e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])},e.prototype.onTrim=function(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)},e}();t.SelectionModel=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(11);function n(e,t,i,r){var n=e-s(i,e),o=t-s(i,t);return h(Math.abs(n-o)-function(e,t,i){for(var r=0,n=e-s(i,e),o=t-s(i,t),c=0;c<Math.abs(n-o);c++){var l="A"===a(e,t)?-1:1,h=i.buffer.lines.get(n+l*c);h&&h.isWrapped&&r++}return r}(e,t,i),l(a(e,t),r))}function s(e,t){for(var i=0,r=e.buffer.lines.get(t),n=r&&r.isWrapped;n&&t>=0&&t<e.rows;)i++,n=(r=e.buffer.lines.get(--t))&&r.isWrapped;return i}function o(e,t,i,r,o,a){var c;return c=n(i,r,o,a).length>0?r-s(o,r):t,e<i&&c<=r||e>=i&&c<r?"C":"D"}function a(e,t){return e>t?"A":"B"}function c(e,t,i,r,n,s){for(var o=e,a=t,c="";o!==i||a!==r;)o+=n?1:-1,n&&o>s.cols-1?(c+=s.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!n&&o<0&&(c+=s.buffer.translateBufferLineToString(a,!1,0,e+1),e=o=s.cols-1,a--);return c+s.buffer.translateBufferLineToString(a,!1,e,o)}function l(e,t){var i=t?"O":"[";return r.C0.ESC+i+e}function h(e,t){e=Math.floor(e);for(var i="",r=0;r<e;r++)i+=t;return i}t.moveToCellSequence=function(e,t,i,r){var a=i.buffer.x,u=i.buffer.y;return i.buffer.hasScrollback?function(e,t,i,r,n,s){var a=o(e,t,i,r,n,s);return h(Math.abs(e-i),l(a,s))}(a,u,e,t,i,r):function(e,t,i,r,o,a){if(0===n(t,r,o,a).length)return"";return h(c(e,t,e,t-s(o,t),!1,o).length,l("D",a))}(a,u,0,t,i,r)+n(u,t,i,r)+function(e,t,i,r,a,u){var f;f=n(t,r,a,u).length>0?r-s(a,r):t;var _=r,d=o(e,t,i,r,a,u);return h(c(e,f,i,_,"C"===d,a).length,l(d,u))}(a,u,e,t,i,r)}},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=function(){function e(e){this._optionsService=e}return Object.defineProperty(e,"audioContext",{get:function(){if(!e._audioContext){var t=window.AudioContext||window.webkitAudioContext;if(!t)return console.warn("Web Audio API is not supported by this browser. Consider upgrading to the latest version"),null;e._audioContext=new t}return e._audioContext},enumerable:!0,configurable:!0}),e.prototype.playBellSound=function(){var t=e.audioContext;if(t){var i=t.createBufferSource();t.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)),function(e){i.buffer=e,i.connect(t.destination),i.start(0)})}},e.prototype._base64ToArrayBuffer=function(e){for(var t=window.atob(e),i=t.length,r=new Uint8Array(i),n=0;n<i;n++)r[n]=t.charCodeAt(n);return r.buffer},e.prototype._removeMimeType=function(e){return e.split(",")[1]},e=r([n(0,s.IOptionsService)],e)}();t.SoundService=o},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},o=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var a=i(2),c=i(7),l=i(5),h=i(0),u=function(e){function t(t,i,r,n,s){var o=e.call(this)||this;return o._element=t,o._screenElement=i,o._bufferService=r,o._mouseService=n,o._selectionService=s,o._zones=[],o._areZonesActive=!1,o._lastHoverCoords=[void 0,void 0],o._initialSelectionLength=0,o.register(c.addDisposableDomListener(o._element,"mousedown",function(e){return o._onMouseDown(e)})),o._mouseMoveListener=function(e){return o._onMouseMove(e)},o._mouseLeaveListener=function(e){return o._onMouseLeave(e)},o._clickListener=function(e){return o._onClick(e)},o}return n(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._deactivate()},t.prototype.add=function(e){this._zones.push(e),1===this._zones.length&&this._activate()},t.prototype.clearAll=function(e,t){if(0!==this._zones.length){e&&t||(e=0,t=this._bufferService.rows-1);for(var i=0;i<this._zones.length;i++){var r=this._zones[i];(r.y1>e&&r.y1<=t+1||r.y2>e&&r.y2<=t+1||r.y1<e&&r.y2>t+1)&&(this._currentZone&&this._currentZone===r&&(this._currentZone.leaveCallback(),this._currentZone=void 0),this._zones.splice(i--,1))}0===this._zones.length&&this._deactivate()}},t.prototype._activate=function(){this._areZonesActive||(this._areZonesActive=!0,this._element.addEventListener("mousemove",this._mouseMoveListener),this._element.addEventListener("mouseleave",this._mouseLeaveListener),this._element.addEventListener("click",this._clickListener))},t.prototype._deactivate=function(){this._areZonesActive&&(this._areZonesActive=!1,this._element.removeEventListener("mousemove",this._mouseMoveListener),this._element.removeEventListener("mouseleave",this._mouseLeaveListener),this._element.removeEventListener("click",this._clickListener))},t.prototype._onMouseMove=function(e){this._lastHoverCoords[0]===e.pageX&&this._lastHoverCoords[1]===e.pageY||(this._onHover(e),this._lastHoverCoords=[e.pageX,e.pageY])},t.prototype._onHover=function(e){var t=this,i=this._findZoneEventAt(e);i!==this._currentZone&&(this._currentZone&&(this._currentZone.leaveCallback(),this._currentZone=void 0,this._tooltipTimeout&&clearTimeout(this._tooltipTimeout)),i&&(this._currentZone=i,i.hoverCallback&&i.hoverCallback(e),this._tooltipTimeout=setTimeout(function(){return t._onTooltip(e)},500)))},t.prototype._onTooltip=function(e){this._tooltipTimeout=void 0;var t=this._findZoneEventAt(e);t&&t.tooltipCallback&&t.tooltipCallback(e)},t.prototype._onMouseDown=function(e){if(this._initialSelectionLength=this._getSelectionLength(),this._areZonesActive){var t=this._findZoneEventAt(e);t&&t.willLinkActivate(e)&&(e.preventDefault(),e.stopImmediatePropagation())}},t.prototype._onMouseLeave=function(e){this._currentZone&&(this._currentZone.leaveCallback(),this._currentZone=void 0,this._tooltipTimeout&&clearTimeout(this._tooltipTimeout))},t.prototype._onClick=function(e){var t=this._findZoneEventAt(e),i=this._getSelectionLength();t&&i===this._initialSelectionLength&&(t.clickCallback(e),e.preventDefault(),e.stopImmediatePropagation())},t.prototype._getSelectionLength=function(){var e=this._selectionService.selectionText;return e?e.length:0},t.prototype._findZoneEventAt=function(e){var t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows);if(t)for(var i=t[0],r=t[1],n=0;n<this._zones.length;n++){var s=this._zones[n];if(s.y1===s.y2){if(r===s.y1&&i>=s.x1&&i<s.x2)return s}else if(r===s.y1&&i>=s.x1||r===s.y2&&i<s.x2||r>s.y1&&r<s.y2)return s}},t=s([o(2,h.IBufferService),o(3,l.IMouseService),o(4,l.ISelectionService)],t)}(a.Disposable);t.MouseZoneManager=u},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(16),o=i(10),a=i(29),c=i(7),l=i(2),h=i(30),u=function(e){function t(t,i){var r=e.call(this)||this;r._terminal=t,r._renderService=i,r._liveRegionLineCount=0,r._charsToConsume=[],r._charsToAnnounce="",r._accessibilityTreeRoot=document.createElement("div"),r._accessibilityTreeRoot.classList.add("xterm-accessibility"),r._rowContainer=document.createElement("div"),r._rowContainer.classList.add("xterm-accessibility-tree"),r._rowElements=[];for(var n=0;n<r._terminal.rows;n++)r._rowElements[n]=r._createAccessibilityTreeNode(),r._rowContainer.appendChild(r._rowElements[n]);return r._topBoundaryFocusListener=function(e){return r._onBoundaryFocus(e,0)},r._bottomBoundaryFocusListener=function(e){return r._onBoundaryFocus(e,1)},r._rowElements[0].addEventListener("focus",r._topBoundaryFocusListener),r._rowElements[r._rowElements.length-1].addEventListener("focus",r._bottomBoundaryFocusListener),r._refreshRowsDimensions(),r._accessibilityTreeRoot.appendChild(r._rowContainer),r._renderRowsDebouncer=new a.RenderDebouncer(r._renderRows.bind(r)),r._refreshRows(),r._liveRegion=document.createElement("div"),r._liveRegion.classList.add("live-region"),r._liveRegion.setAttribute("aria-live","assertive"),r._accessibilityTreeRoot.appendChild(r._liveRegion),r._terminal.element.insertAdjacentElement("afterbegin",r._accessibilityTreeRoot),r.register(r._renderRowsDebouncer),r.register(r._terminal.onResize(function(e){return r._onResize(e.rows)})),r.register(r._terminal.onRender(function(e){return r._refreshRows(e.start,e.end)})),r.register(r._terminal.onScroll(function(){return r._refreshRows()})),r.register(r._terminal.onA11yChar(function(e){return r._onChar(e)})),r.register(r._terminal.onLineFeed(function(){return r._onChar("\n")})),r.register(r._terminal.onA11yTab(function(e){return r._onTab(e)})),r.register(r._terminal.onKey(function(e){return r._onKey(e.key)})),r.register(r._terminal.onBlur(function(){return r._clearLiveRegion()})),r.register(r._renderService.onDimensionsChange(function(){return r._refreshRowsDimensions()})),r._screenDprMonitor=new h.ScreenDprMonitor,r.register(r._screenDprMonitor),r._screenDprMonitor.setListener(function(){return r._refreshRowsDimensions()}),r.register(c.addDisposableDomListener(window,"resize",function(){return r._refreshRowsDimensions()})),r}return n(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._terminal.element.removeChild(this._accessibilityTreeRoot),this._rowElements.length=0},t.prototype._onBoundaryFocus=function(e,t){var i=e.target,r=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")!==(0===t?"1":""+this._terminal.buffer.lines.length)&&e.relatedTarget===r){var n,s;if(0===t?(n=i,s=this._rowElements.pop(),this._rowContainer.removeChild(s)):(n=this._rowElements.shift(),s=i,this._rowContainer.removeChild(n)),n.removeEventListener("focus",this._topBoundaryFocusListener),s.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){var o=this._createAccessibilityTreeNode();this._rowElements.unshift(o),this._rowContainer.insertAdjacentElement("afterbegin",o)}else{o=this._createAccessibilityTreeNode();this._rowElements.push(o),this._rowContainer.appendChild(o)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}},t.prototype._onResize=function(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(var t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()},t.prototype._createAccessibilityTreeNode=function(){var e=document.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e},t.prototype._onTab=function(e){for(var t=0;t<e;t++)this._onChar(" ")},t.prototype._onChar=function(e){var t=this;if(this._liveRegionLineCount<21){if(this._charsToConsume.length>0)this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e);else this._charsToAnnounce+=e;"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=s.tooMuchOutput)),o.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout(function(){t._accessibilityTreeRoot.appendChild(t._liveRegion)},0)}},t.prototype._clearLiveRegion=function(){this._liveRegion.textContent="",this._liveRegionLineCount=0,o.isMac&&this._liveRegion.parentNode&&this._accessibilityTreeRoot.removeChild(this._liveRegion)},t.prototype._onKey=function(e){this._clearLiveRegion(),this._charsToConsume.push(e)},t.prototype._refreshRows=function(e,t){this._renderRowsDebouncer.refresh(e,t,this._terminal.rows)},t.prototype._renderRows=function(e,t){for(var i=this._terminal.buffer,r=i.lines.length.toString(),n=e;n<=t;n++){var s=i.translateBufferLineToString(i.ydisp+n,!0),o=(i.ydisp+n+1).toString(),a=this._rowElements[n];a&&(0===s.length?a.innerHTML="&nbsp;":a.textContent=s,a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",r))}this._announceCharacters()},t.prototype._refreshRowsDimensions=function(){if(this._renderService.dimensions.actualCellHeight){this._rowElements.length!==this._terminal.rows&&this._onResize(this._terminal.rows);for(var e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e])}},t.prototype._refreshRowDimensions=function(e){e.style.height=this._renderService.dimensions.actualCellHeight+"px"},t.prototype._announceCharacters=function(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")},t}(l.Disposable);t.AccessibilityManager=u},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(56),o=i(9),a=i(2),c="xterm-dom-renderer-owner-",l="xterm-rows",h="xterm-selection",u=1,f=function(e){function t(t,i,r,n){var o=e.call(this)||this;return o._terminal=t,o._colors=i,o._charSizeService=r,o._optionsService=n,o._terminalClass=u++,o._rowElements=[],o._rowContainer=document.createElement("div"),o._rowContainer.classList.add(l),o._rowContainer.style.lineHeight="normal",o._rowContainer.setAttribute("aria-hidden","true"),o._refreshRowElements(o._terminal.cols,o._terminal.rows),o._selectionContainer=document.createElement("div"),o._selectionContainer.classList.add(h),o._selectionContainer.setAttribute("aria-hidden","true"),o.dimensions={scaledCharWidth:null,scaledCharHeight:null,scaledCellWidth:null,scaledCellHeight:null,scaledCharLeft:null,scaledCharTop:null,scaledCanvasWidth:null,scaledCanvasHeight:null,canvasWidth:null,canvasHeight:null,actualCellWidth:null,actualCellHeight:null},o._updateDimensions(),o._injectCss(),o._rowFactory=new s.DomRendererRowFactory(document,o._optionsService),o._terminal.element.classList.add(c+o._terminalClass),o._terminal.screenElement.appendChild(o._rowContainer),o._terminal.screenElement.appendChild(o._selectionContainer),o._terminal.linkifier.onLinkHover(function(e){return o._onLinkHover(e)}),o._terminal.linkifier.onLinkLeave(function(e){return o._onLinkLeave(e)}),o}return n(t,e),t.prototype.dispose=function(){this._terminal.element.classList.remove(c+this._terminalClass),this._terminal.screenElement.removeChild(this._rowContainer),this._terminal.screenElement.removeChild(this._selectionContainer),this._terminal.screenElement.removeChild(this._themeStyleElement),this._terminal.screenElement.removeChild(this._dimensionsStyleElement),e.prototype.dispose.call(this)},t.prototype._updateDimensions=function(){var e=this;this.dimensions.scaledCharWidth=this._charSizeService.width*window.devicePixelRatio,this.dimensions.scaledCharHeight=Math.ceil(this._charSizeService.height*window.devicePixelRatio),this.dimensions.scaledCellWidth=this.dimensions.scaledCharWidth+Math.round(this._terminal.options.letterSpacing),this.dimensions.scaledCellHeight=Math.floor(this.dimensions.scaledCharHeight*this._terminal.options.lineHeight),this.dimensions.scaledCharLeft=0,this.dimensions.scaledCharTop=0,this.dimensions.scaledCanvasWidth=this.dimensions.scaledCellWidth*this._terminal.cols,this.dimensions.scaledCanvasHeight=this.dimensions.scaledCellHeight*this._terminal.rows,this.dimensions.canvasWidth=Math.round(this.dimensions.scaledCanvasWidth/window.devicePixelRatio),this.dimensions.canvasHeight=Math.round(this.dimensions.scaledCanvasHeight/window.devicePixelRatio),this.dimensions.actualCellWidth=this.dimensions.canvasWidth/this._terminal.cols,this.dimensions.actualCellHeight=this.dimensions.canvasHeight/this._terminal.rows,this._rowElements.forEach(function(t){t.style.width=e.dimensions.canvasWidth+"px",t.style.height=e.dimensions.actualCellHeight+"px",t.style.lineHeight=e.dimensions.actualCellHeight+"px",t.style.overflow="hidden"}),this._dimensionsStyleElement||(this._dimensionsStyleElement=document.createElement("style"),this._terminal.screenElement.appendChild(this._dimensionsStyleElement));var t=this._terminalSelector+" ."+l+" span { display: inline-block; height: 100%; vertical-align: top; width: "+this.dimensions.actualCellWidth+"px}";this._dimensionsStyleElement.innerHTML=t,this._selectionContainer.style.height=this._terminal._viewportElement.style.height,this._terminal.screenElement.style.width=this.dimensions.canvasWidth+"px",this._terminal.screenElement.style.height=this.dimensions.canvasHeight+"px"},t.prototype.setColors=function(e){this._colors=e,this._injectCss()},t.prototype._injectCss=function(){var e=this;this._themeStyleElement||(this._themeStyleElement=document.createElement("style"),this._terminal.screenElement.appendChild(this._themeStyleElement));var t=this._terminalSelector+" ."+l+" { color: "+this._colors.foreground.css+"; background-color: "+this._colors.background.css+"; font-family: "+this._terminal.options.fontFamily+"; font-size: "+this._terminal.options.fontSize+"px;}";t+=this._terminalSelector+" span:not(."+s.BOLD_CLASS+") { font-weight: "+this._terminal.options.fontWeight+";}"+this._terminalSelector+" span."+s.BOLD_CLASS+" { font-weight: "+this._terminal.options.fontWeightBold+";}"+this._terminalSelector+" span."+s.ITALIC_CLASS+" { font-style: italic;}",t+="@keyframes blink_box_shadow { 50% {  box-shadow: none; }}",t+="@keyframes blink_block { 0% {  background-color: "+this._colors.cursor.css+";  color: "+this._colors.cursorAccent.css+"; } 50% {  background-color: "+this._colors.cursorAccent.css+";  color: "+this._colors.cursor.css+"; }}",t+=this._terminalSelector+" ."+l+":not(.xterm-focus) ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_BLOCK_CLASS+" { outline: 1px solid "+this._colors.cursor.css+"; outline-offset: -1px;}"+this._terminalSelector+" ."+l+".xterm-focus ."+s.CURSOR_CLASS+"."+s.CURSOR_BLINK_CLASS+":not(."+s.CURSOR_STYLE_BLOCK_CLASS+") { animation: blink_box_shadow 1s step-end infinite;}"+this._terminalSelector+" ."+l+".xterm-focus ."+s.CURSOR_CLASS+"."+s.CURSOR_BLINK_CLASS+"."+s.CURSOR_STYLE_BLOCK_CLASS+" { animation: blink_block 1s step-end infinite;}"+this._terminalSelector+" ."+l+".xterm-focus ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_BLOCK_CLASS+" { background-color: "+this._colors.cursor.css+"; color: "+this._colors.cursorAccent.css+";}"+this._terminalSelector+" ."+l+" ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_BAR_CLASS+" { box-shadow: 1px 0 0 "+this._colors.cursor.css+" inset;}"+this._terminalSelector+" ."+l+" ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_UNDERLINE_CLASS+" { box-shadow: 0 -1px 0 "+this._colors.cursor.css+" inset;}",t+=this._terminalSelector+" ."+h+" { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}"+this._terminalSelector+" ."+h+" div { position: absolute; background-color: "+this._colors.selection.css+";}",this._colors.ansi.forEach(function(i,r){t+=e._terminalSelector+" .xterm-fg-"+r+" { color: "+i.css+"; }"+e._terminalSelector+" .xterm-bg-"+r+" { background-color: "+i.css+"; }"}),t+=this._terminalSelector+" .xterm-fg-"+o.INVERTED_DEFAULT_COLOR+" { color: "+this._colors.background.css+"; }"+this._terminalSelector+" .xterm-bg-"+o.INVERTED_DEFAULT_COLOR+" { background-color: "+this._colors.foreground.css+"; }",this._themeStyleElement.innerHTML=t},t.prototype.onDevicePixelRatioChange=function(){this._updateDimensions()},t.prototype._refreshRowElements=function(e,t){for(var i=this._rowElements.length;i<=t;i++){var r=document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())},t.prototype.onResize=function(e,t){this._refreshRowElements(e,t),this._updateDimensions()},t.prototype.onCharSizeChanged=function(){this._updateDimensions()},t.prototype.onBlur=function(){this._rowContainer.classList.remove("xterm-focus")},t.prototype.onFocus=function(){this._rowContainer.classList.add("xterm-focus")},t.prototype.onSelectionChanged=function(e,t,i){for(;this._selectionContainer.children.length;)this._selectionContainer.removeChild(this._selectionContainer.children[0]);if(e&&t){var r=e[1]-this._terminal.buffer.ydisp,n=t[1]-this._terminal.buffer.ydisp,s=Math.max(r,0),o=Math.min(n,this._terminal.rows-1);if(!(s>=this._terminal.rows||o<0)){var a=document.createDocumentFragment();if(i)a.appendChild(this._createSelectionElement(s,e[0],t[0],o-s+1));else{var c=r===s?e[0]:0,l=s===o?t[0]:this._terminal.cols;a.appendChild(this._createSelectionElement(s,c,l));var h=o-s-1;if(a.appendChild(this._createSelectionElement(s+1,0,this._terminal.cols,h)),s!==o){var u=n===o?t[0]:this._terminal.cols;a.appendChild(this._createSelectionElement(o,0,u))}}this._selectionContainer.appendChild(a)}}},t.prototype._createSelectionElement=function(e,t,i,r){void 0===r&&(r=1);var n=document.createElement("div");return n.style.height=r*this.dimensions.actualCellHeight+"px",n.style.top=e*this.dimensions.actualCellHeight+"px",n.style.left=t*this.dimensions.actualCellWidth+"px",n.style.width=this.dimensions.actualCellWidth*(i-t)+"px",n},t.prototype.onCursorMove=function(){},t.prototype.onOptionsChanged=function(){this._updateDimensions(),this._injectCss(),this._terminal.refresh(0,this._terminal.rows-1)},t.prototype.clear=function(){this._rowElements.forEach(function(e){return e.innerHTML=""})},t.prototype.renderRows=function(e,t){for(var i=this._terminal,r=i.buffer.ybase+i.buffer.y,n=this._terminal.buffer.x,s=this._terminal.options.cursorBlink,o=e;o<=t;o++){var a=this._rowElements[o];a.innerHTML="";var c=o+i.buffer.ydisp,l=i.buffer.lines.get(c),h=i.options.cursorStyle;a.appendChild(this._rowFactory.createRow(l,c===r,h,n,s,this.dimensions.actualCellWidth,i.cols))}},Object.defineProperty(t.prototype,"_terminalSelector",{get:function(){return"."+c+this._terminalClass},enumerable:!0,configurable:!0}),t.prototype.registerCharacterJoiner=function(e){return-1},t.prototype.deregisterCharacterJoiner=function(e){return!1},t.prototype._onLinkHover=function(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)},t.prototype._onLinkLeave=function(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)},t.prototype._setCellUnderline=function(e,t,i,r,n,s){for(;e!==t||i!==r;){var o=this._rowElements[i];if(!o)return;var a=o.children[e];a&&(a.style.textDecoration=s?"underline":"none"),++e>=n&&(e=0,i++)}},t}(a.Disposable);t.DomRenderer=f},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(9),n=i(6),s=i(3),o=i(4);t.BOLD_CLASS="xterm-bold",t.DIM_CLASS="xterm-dim",t.ITALIC_CLASS="xterm-italic",t.UNDERLINE_CLASS="xterm-underline",t.CURSOR_CLASS="xterm-cursor",t.CURSOR_BLINK_CLASS="xterm-cursor-blink",t.CURSOR_STYLE_BLOCK_CLASS="xterm-cursor-block",t.CURSOR_STYLE_BAR_CLASS="xterm-cursor-bar",t.CURSOR_STYLE_UNDERLINE_CLASS="xterm-cursor-underline";var a=function(){function e(e,t){this._document=e,this._optionsService=t,this._workCell=new o.CellData}return e.prototype.createRow=function(e,i,o,a,c,l,h){for(var u=this._document.createDocumentFragment(),f=0,_=Math.min(e.length,h)-1;_>=0;_--)if(e.loadCell(_,this._workCell).getCode()!==s.NULL_CELL_CODE||i&&_===a){f=_+1;break}for(_=0;_<f;_++){e.loadCell(_,this._workCell);var d=this._workCell.getWidth();if(0!==d){var p=this._document.createElement("span");if(d>1&&(p.style.width=l*d+"px"),i&&_===a)switch(p.classList.add(t.CURSOR_CLASS),c&&p.classList.add(t.CURSOR_BLINK_CLASS),o){case"bar":p.classList.add(t.CURSOR_STYLE_BAR_CLASS);break;case"underline":p.classList.add(t.CURSOR_STYLE_UNDERLINE_CLASS);break;default:p.classList.add(t.CURSOR_STYLE_BLOCK_CLASS)}this._workCell.isBold()&&p.classList.add(t.BOLD_CLASS),this._workCell.isItalic()&&p.classList.add(t.ITALIC_CLASS),this._workCell.isDim()&&p.classList.add(t.DIM_CLASS),this._workCell.isUnderline()&&p.classList.add(t.UNDERLINE_CLASS),p.textContent=this._workCell.getChars()||s.WHITESPACE_CELL_CHAR;var v=this._workCell.isInverse();if(this._workCell.isFgRGB()){var g=p.getAttribute("style")||"";g+=(v?"background-":"")+"color:rgb("+n.AttributeData.toColorRGB(this._workCell.getFgColor()).join(",")+");",p.setAttribute("style",g)}else if(this._workCell.isFgPalette()){var y=this._workCell.getFgColor();this._workCell.isBold()&&y<8&&!v&&this._optionsService.options.drawBoldTextInBrightColors&&(y+=8),p.classList.add("xterm-"+(v?"b":"f")+"g-"+y)}else v&&p.classList.add("xterm-bg-"+r.INVERTED_DEFAULT_COLOR);if(this._workCell.isBgRGB()){g=p.getAttribute("style")||"";g+=(v?"":"background-")+"color:rgb("+n.AttributeData.toColorRGB(this._workCell.getBgColor()).join(",")+");",p.setAttribute("style",g)}else this._workCell.isBgPalette()?p.classList.add("xterm-"+(v?"f":"b")+"g-"+this._workCell.getBgColor()):v&&p.classList.add("xterm-fg-"+r.INVERTED_DEFAULT_COLOR);u.appendChild(p)}}return u},e}();t.DomRendererRowFactory=a},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(11),n={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};t.evaluateKeyboardEvent=function(e,t,i,s){var o={type:0,cancel:!1,key:void 0},a=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?o.key=t?r.C0.ESC+"OA":r.C0.ESC+"[A":"UIKeyInputLeftArrow"===e.key?o.key=t?r.C0.ESC+"OD":r.C0.ESC+"[D":"UIKeyInputRightArrow"===e.key?o.key=t?r.C0.ESC+"OC":r.C0.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(o.key=t?r.C0.ESC+"OB":r.C0.ESC+"[B");break;case 8:if(e.shiftKey){o.key=r.C0.BS;break}if(e.altKey){o.key=r.C0.ESC+r.C0.DEL;break}o.key=r.C0.DEL;break;case 9:if(e.shiftKey){o.key=r.C0.ESC+"[Z";break}o.key=r.C0.HT,o.cancel=!0;break;case 13:o.key=r.C0.CR,o.cancel=!0;break;case 27:o.key=r.C0.ESC,o.cancel=!0;break;case 37:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"D",o.key===r.C0.ESC+"[1;3D"&&(o.key=r.C0.ESC+(i?"b":"[1;5D"))):o.key=t?r.C0.ESC+"OD":r.C0.ESC+"[D";break;case 39:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"C",o.key===r.C0.ESC+"[1;3C"&&(o.key=r.C0.ESC+(i?"f":"[1;5C"))):o.key=t?r.C0.ESC+"OC":r.C0.ESC+"[C";break;case 38:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"A",i||o.key!==r.C0.ESC+"[1;3A"||(o.key=r.C0.ESC+"[1;5A")):o.key=t?r.C0.ESC+"OA":r.C0.ESC+"[A";break;case 40:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"B",i||o.key!==r.C0.ESC+"[1;3B"||(o.key=r.C0.ESC+"[1;5B")):o.key=t?r.C0.ESC+"OB":r.C0.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(o.key=r.C0.ESC+"[2~");break;case 46:o.key=a?r.C0.ESC+"[3;"+(a+1)+"~":r.C0.ESC+"[3~";break;case 36:o.key=a?r.C0.ESC+"[1;"+(a+1)+"H":t?r.C0.ESC+"OH":r.C0.ESC+"[H";break;case 35:o.key=a?r.C0.ESC+"[1;"+(a+1)+"F":t?r.C0.ESC+"OF":r.C0.ESC+"[F";break;case 33:e.shiftKey?o.type=2:o.key=r.C0.ESC+"[5~";break;case 34:e.shiftKey?o.type=3:o.key=r.C0.ESC+"[6~";break;case 112:o.key=a?r.C0.ESC+"[1;"+(a+1)+"P":r.C0.ESC+"OP";break;case 113:o.key=a?r.C0.ESC+"[1;"+(a+1)+"Q":r.C0.ESC+"OQ";break;case 114:o.key=a?r.C0.ESC+"[1;"+(a+1)+"R":r.C0.ESC+"OR";break;case 115:o.key=a?r.C0.ESC+"[1;"+(a+1)+"S":r.C0.ESC+"OS";break;case 116:o.key=a?r.C0.ESC+"[15;"+(a+1)+"~":r.C0.ESC+"[15~";break;case 117:o.key=a?r.C0.ESC+"[17;"+(a+1)+"~":r.C0.ESC+"[17~";break;case 118:o.key=a?r.C0.ESC+"[18;"+(a+1)+"~":r.C0.ESC+"[18~";break;case 119:o.key=a?r.C0.ESC+"[19;"+(a+1)+"~":r.C0.ESC+"[19~";break;case 120:o.key=a?r.C0.ESC+"[20;"+(a+1)+"~":r.C0.ESC+"[20~";break;case 121:o.key=a?r.C0.ESC+"[21;"+(a+1)+"~":r.C0.ESC+"[21~";break;case 122:o.key=a?r.C0.ESC+"[23;"+(a+1)+"~":r.C0.ESC+"[23~";break;case 123:o.key=a?r.C0.ESC+"[24;"+(a+1)+"~":r.C0.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!s||!e.altKey||e.metaKey)i&&!e.altKey&&!e.ctrlKey&&e.metaKey?65===e.keyCode&&(o.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?o.key=e.key:e.key&&e.ctrlKey&&"_"===e.key&&(o.key=r.C0.US);else{var c=n[e.keyCode],l=c&&c[e.shiftKey?1:0];if(l)o.key=r.C0.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){var h=e.ctrlKey?e.keyCode-64:e.keyCode+32;o.key=r.C0.ESC+String.fromCharCode(h)}}else e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?o.key=r.C0.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?o.key=r.C0.DEL:219===e.keyCode?o.key=r.C0.ESC:220===e.keyCode?o.key=r.C0.FS:221===e.keyCode&&(o.key=r.C0.GS)}return o}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(3);t.applyWindowsMode=function(e){return e.onLineFeed(function(){var t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1).get(e.cols-1);e.buffer.lines.get(e.buffer.ybase+e.buffer.y).isWrapped=t[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&t[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE})}},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},o=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var a=i(29),c=i(1),l=i(2),h=i(30),u=i(7),f=i(0),_=i(5),d=function(e){function t(t,i,r,n,s){var o=e.call(this)||this;if(o._renderer=t,o._rowCount=i,o.screenElement=r,o.optionsService=n,o.charSizeService=s,o._isPaused=!1,o._needsFullRefresh=!1,o._canvasWidth=0,o._canvasHeight=0,o._onDimensionsChange=new c.EventEmitter,o._onRender=new c.EventEmitter,o._onRefreshRequest=new c.EventEmitter,o._renderDebouncer=new a.RenderDebouncer(function(e,t){return o._renderRows(e,t)}),o.register(o._renderDebouncer),o._screenDprMonitor=new h.ScreenDprMonitor,o._screenDprMonitor.setListener(function(){return o.onDevicePixelRatioChange()}),o.register(o._screenDprMonitor),o.register(n.onOptionChange(function(){return o._renderer.onOptionsChanged()})),o.register(s.onCharSizeChange(function(){return o.onCharSizeChanged()})),o.register(u.addDisposableDomListener(window,"resize",function(){return o.onDevicePixelRatioChange()})),"IntersectionObserver"in window){var l=new IntersectionObserver(function(e){return o._onIntersectionChange(e[e.length-1])},{threshold:0});l.observe(r),o.register({dispose:function(){return l.disconnect()}})}return o}return n(t,e),Object.defineProperty(t.prototype,"onDimensionsChange",{get:function(){return this._onDimensionsChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onRender",{get:function(){return this._onRender.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onRefreshRequest",{get:function(){return this._onRefreshRequest.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dimensions",{get:function(){return this._renderer.dimensions},enumerable:!0,configurable:!0}),t.prototype._onIntersectionChange=function(e){this._isPaused=0===e.intersectionRatio,!this._isPaused&&this._needsFullRefresh&&(this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)},t.prototype.refreshRows=function(e,t){this._isPaused?this._needsFullRefresh=!0:this._renderDebouncer.refresh(e,t,this._rowCount)},t.prototype._renderRows=function(e,t){this._renderer.renderRows(e,t),this._onRender.fire({start:e,end:t})},t.prototype.resize=function(e,t){this._rowCount=t,this._fireOnCanvasResize()},t.prototype.changeOptions=function(){this._renderer.onOptionsChanged(),this._fireOnCanvasResize()},t.prototype._fireOnCanvasResize=function(){this._renderer.dimensions.canvasWidth===this._canvasWidth&&this._renderer.dimensions.canvasHeight===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.dimensions)},t.prototype.dispose=function(){this._renderer.dispose()},t.prototype.setRenderer=function(e){this._renderer.dispose(),this._renderer=e,this.refreshRows(0,this._rowCount-1)},t.prototype._fullRefresh=function(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)},t.prototype.setColors=function(e){this._renderer.setColors(e),this._fullRefresh()},t.prototype.onDevicePixelRatioChange=function(){this._renderer.onDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1)},t.prototype.onResize=function(e,t){this._renderer.onResize(e,t),this._fullRefresh()},t.prototype.onCharSizeChanged=function(){this._renderer.onCharSizeChanged()},t.prototype.onBlur=function(){this._renderer.onBlur()},t.prototype.onFocus=function(){this._renderer.onFocus()},t.prototype.onSelectionChanged=function(e,t,i){this._renderer.onSelectionChanged(e,t,i)},t.prototype.onCursorMove=function(){this._renderer.onCursorMove()},t.prototype.clear=function(){this._renderer.clear()},t.prototype.registerCharacterJoiner=function(e){return this._renderer.registerCharacterJoiner(e)},t.prototype.deregisterCharacterJoiner=function(e){return this._renderer.deregisterCharacterJoiner(e)},t=s([o(3,f.IOptionsService),o(4,_.ICharSizeService)],t)}(l.Disposable);t.RenderService=d},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(1),n=i(10),s=i(31);t.DEFAULT_BELL_SOUND="data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq",t.DEFAULT_OPTIONS=Object.freeze({cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",bellSound:t.DEFAULT_BELL_SOUND,bellStyle:"none",drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",lineHeight:1,letterSpacing:0,logLevel:"info",scrollback:1e3,scrollSensitivity:1,screenReaderMode:!1,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,disableStdin:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:n.isMac,rendererType:"canvas",windowsMode:!1,convertEol:!1,termName:"xterm",screenKeys:!1,cancelEvents:!1,useFlowControl:!1,wordSeparator:" ()[]{}',:;\""});var o=["cols","rows"],a=function(){function e(e){var i=this;this._onOptionChange=new r.EventEmitter,this.options=s.clone(t.DEFAULT_OPTIONS),Object.keys(e).forEach(function(t){if(t in i.options){var r=e[t];i.options[t]=r}})}return Object.defineProperty(e.prototype,"onOptionChange",{get:function(){return this._onOptionChange.event},enumerable:!0,configurable:!0}),e.prototype.setOption=function(e,i){if(!(e in t.DEFAULT_OPTIONS))throw new Error('No option with key "'+e+'"');if(-1!==o.indexOf(e))throw new Error('Option "'+e+'" can only be set in the constructor');this.options[e]!==i&&(i=this._sanitizeAndValidateOption(e,i),this.options[e]!==i&&(this.options[e]=i,this._onOptionChange.fire(e)))},e.prototype._sanitizeAndValidateOption=function(e,i){switch(e){case"bellStyle":case"cursorStyle":case"fontWeight":case"fontWeightBold":case"rendererType":case"wordSeparator":i||(i=t.DEFAULT_OPTIONS[e]);break;case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(e+" cannot be less than 1, value: "+i);break;case"scrollback":if((i=Math.min(i,4294967295))<0)throw new Error(e+" cannot be less than 0, value: "+i);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(e+" cannot be less than or equal to 0, value: "+i)}return i},e.prototype.getOption=function(e){if(!(e in t.DEFAULT_OPTIONS))throw new Error('No option with key "'+e+'"');return this.options[e]},e}();t.OptionsService=a},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(1),a=function(){function e(e,t,i){this.document=e,this.parentElement=t,this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=new o.EventEmitter,this._measureStrategy=new c(e,t,this._optionsService)}return Object.defineProperty(e.prototype,"hasValidSize",{get:function(){return this.width>0&&this.height>0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onCharSizeChange",{get:function(){return this._onCharSizeChange.event},enumerable:!0,configurable:!0}),e.prototype.measure=function(){var e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())},e=r([n(2,s.IOptionsService)],e)}();t.CharSizeService=a;var c=function(){function e(e,t,i){this._document=e,this._parentElement=t,this._optionsService=i,this._result={width:0,height:0},this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W",this._measureElement.setAttribute("aria-hidden","true"),this._parentElement.appendChild(this._measureElement)}return e.prototype.measure=function(){this._measureElement.style.fontFamily=this._optionsService.options.fontFamily,this._measureElement.style.fontSize=this._optionsService.options.fontSize+"px";var e=this._measureElement.getBoundingClientRect();return 0!==e.width&&0!==e.height&&(this._result.width=e.width,this._result.height=Math.ceil(e.height)),this._result},e}()},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(63);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;var a=function(){function e(e){this._optionsService=e,this.cols=Math.max(e.options.cols,t.MINIMUM_COLS),this.rows=Math.max(e.options.rows,t.MINIMUM_ROWS),this.buffers=new o.BufferSet(e,this)}return Object.defineProperty(e.prototype,"buffer",{get:function(){return this.buffers.active},enumerable:!0,configurable:!0}),e.prototype.resize=function(e,t){this.cols=e,this.rows=t},e.prototype.reset=function(){this.buffers=new o.BufferSet(this._optionsService,this)},e=r([n(0,s.IOptionsService)],e)}();t.BufferService=a},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(64),n=i(1),s=function(){function e(e,t){this.optionsService=e,this.bufferService=t,this._onBufferActivate=new n.EventEmitter,this._normal=new r.Buffer(!0,e,t),this._normal.fillViewportRows(),this._alt=new r.Buffer(!1,e,t),this._activeBuffer=this._normal,this.setupTabStops()}return Object.defineProperty(e.prototype,"onBufferActivate",{get:function(){return this._onBufferActivate.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alt",{get:function(){return this._alt},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"active",{get:function(){return this._activeBuffer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"normal",{get:function(){return this._normal},enumerable:!0,configurable:!0}),e.prototype.activateNormalBuffer=function(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))},e.prototype.activateAltBuffer=function(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))},e.prototype.resize=function(e,t){this._normal.resize(e,t),this._alt.resize(e,t)},e.prototype.setupTabStops=function(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)},e}();t.BufferSet=s},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(65),n=i(15),s=i(4),o=i(3),a=i(66),c=i(67),l=i(17);t.MAX_BUFFER_SIZE=4294967295;var h=function(){function e(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.savedY=0,this.savedX=0,this.savedCurAttrData=n.DEFAULT_ATTR_DATA.clone(),this.savedCharset=l.DEFAULT_CHARSET,this.markers=[],this._nullCell=s.CellData.fromCharData([0,o.NULL_CELL_CHAR,o.NULL_CELL_WIDTH,o.NULL_CELL_CODE]),this._whitespaceCell=s.CellData.fromCharData([0,o.WHITESPACE_CELL_CHAR,o.WHITESPACE_CELL_WIDTH,o.WHITESPACE_CELL_CODE]),this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}return e.prototype.getNullCell=function(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg):(this._nullCell.fg=0,this._nullCell.bg=0),this._nullCell},e.prototype.getWhitespaceCell=function(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0),this._whitespaceCell},e.prototype.getBlankLine=function(e,t){return new n.BufferLine(this._bufferService.cols,this.getNullCell(e),t)},Object.defineProperty(e.prototype,"hasScrollback",{get:function(){return this._hasScrollback&&this.lines.maxLength>this._rows},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isCursorInViewport",{get:function(){var e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows},enumerable:!0,configurable:!0}),e.prototype._getCorrectBufferLength=function(e){if(!this._hasScrollback)return e;var i=e+this._optionsService.options.scrollback;return i>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:i},e.prototype.fillViewportRows=function(e){if(0===this.lines.length){void 0===e&&(e=n.DEFAULT_ATTR_DATA);for(var t=this._rows;t--;)this.lines.push(this.getBlankLine(e))}},e.prototype.clear=function(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()},e.prototype.resize=function(e,t){var i=this.getNullCell(n.DEFAULT_ATTR_DATA),r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(var s=0;s<this.lines.length;s++)this.lines.get(s).resize(e,i);var o=0;if(this._rows<t)for(var a=this._rows;a<t;a++)this.lines.length<t+this.ybase&&(this._optionsService.options.windowsMode?this.lines.push(new n.BufferLine(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new n.BufferLine(e,i)));else for(a=this._rows;a>t;a--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){var c=this.lines.length-r;c>0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(s=0;s<this.lines.length;s++)this.lines.get(s).resize(e,i);this._cols=e,this._rows=t},Object.defineProperty(e.prototype,"_isReflowEnabled",{get:function(){return this._hasScrollback&&!this._optionsService.options.windowsMode},enumerable:!0,configurable:!0}),e.prototype._reflow=function(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))},e.prototype._reflowLarger=function(e,t){var i=a.reflowLargerGetLinesToRemove(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(n.DEFAULT_ATTR_DATA));if(i.length>0){var r=a.reflowLargerCreateNewLayout(this.lines,i);a.reflowLargerApplyNewLayout(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}},e.prototype._reflowLargerAdjustViewport=function(e,t,i){for(var r=this.getNullCell(n.DEFAULT_ATTR_DATA),s=i;s-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new n.BufferLine(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)},e.prototype._reflowSmaller=function(e,t){for(var i=this.getNullCell(n.DEFAULT_ATTR_DATA),r=[],s=0,o=this.lines.length-1;o>=0;o--){var c=this.lines.get(o);if(!(!c||!c.isWrapped&&c.getTrimmedLength()<=e)){for(var l=[c];c.isWrapped&&o>0;)c=this.lines.get(--o),l.unshift(c);var h=this.ybase+this.y;if(!(h>=o&&h<o+l.length)){var u=l[l.length-1].getTrimmedLength(),f=a.reflowSmallerGetNewLineLengths(l,this._cols,e),_=f.length-l.length,d=void 0;d=0===this.ybase&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+_):Math.max(0,this.lines.length-this.lines.maxLength+_);for(var p=[],v=0;v<_;v++){var g=this.getBlankLine(n.DEFAULT_ATTR_DATA,!0);p.push(g)}p.length>0&&(r.push({start:o+l.length+s,newLines:p}),s+=p.length),l.push.apply(l,p);var y=f.length-1,m=f[y];0===m&&(m=f[--y]);for(var b=l.length-_-1,C=u;b>=0;){var S=Math.min(C,m);if(l[y].copyCellsFrom(l[b],C-S,m-S,S,!0),0===(m-=S)&&(m=f[--y]),0===(C-=S)){b--;var w=Math.max(b,0);C=a.getWrappedLineTrimmedLength(l,w,this._cols)}}for(v=0;v<l.length;v++)f[v]<e&&l[v].setCell(f[v],i);for(var E=_-d;E-- >0;)0===this.ybase?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+s)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+_,this.ybase+t-1)}}}if(r.length>0){var L=[],A=[];for(v=0;v<this.lines.length;v++)A.push(this.lines.get(v));var x=this.lines.length,k=x-1,D=0,T=r[D];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+s);var R=0;for(v=Math.min(this.lines.maxLength-1,x+s-1);v>=0;v--)if(T&&T.start>k+R){for(var M=T.newLines.length-1;M>=0;M--)this.lines.set(v--,T.newLines[M]);v++,L.push({index:k+1,amount:T.newLines.length}),R+=T.newLines.length,T=r[++D]}else this.lines.set(v,A[k--]);var O=0;for(v=L.length-1;v>=0;v--)L[v].index+=O,this.lines.onInsertEmitter.fire(L[v]),O+=L[v].amount;var P=Math.max(0,x+s-this.lines.maxLength);P>0&&this.lines.onTrimEmitter.fire(P)}},e.prototype.stringIndexToBufferIndex=function(e,t,i){for(void 0===i&&(i=!1);t;){var r=this.lines.get(e);if(!r)return[-1,-1];for(var n=i?r.getTrimmedLength():r.length,s=0;s<n;++s)if(r.get(s)[o.CHAR_DATA_WIDTH_INDEX]&&(t-=r.get(s)[o.CHAR_DATA_CHAR_INDEX].length||1),t<0)return[e,s];e++}return[e,0]},e.prototype.translateBufferLineToString=function(e,t,i,r){void 0===i&&(i=0);var n=this.lines.get(e);return n?n.translateToString(t,i,r):""},e.prototype.getWrappedRangeForLine=function(e){for(var t=e,i=e;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}},e.prototype.setupTabStops=function(e){for(null!=e?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.options.tabStopWidth)this.tabs[e]=!0},e.prototype.prevStop=function(e){for(null==e&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e},e.prototype.nextStop=function(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e},e.prototype.addMarker=function(e){var t=this,i=new c.Marker(e);return this.markers.push(i),i.register(this.lines.onTrim(function(e){i.line-=e,i.line<0&&i.dispose()})),i.register(this.lines.onInsert(function(e){i.line>=e.index&&(i.line+=e.amount)})),i.register(this.lines.onDelete(function(e){i.line>=e.index&&i.line<e.index+e.amount&&i.dispose(),i.line>e.index&&(i.line-=e.amount)})),i.register(i.onDispose(function(){return t._removeMarker(i)})),i},e.prototype._removeMarker=function(e){this.markers.splice(this.markers.indexOf(e),1)},e.prototype.iterator=function(e,t,i,r,n){return new u(this,e,t,i,r,n)},e}();t.Buffer=h;var u=function(){function e(e,t,i,r,n,s){void 0===i&&(i=0),void 0===r&&(r=e.lines.length),void 0===n&&(n=0),void 0===s&&(s=0),this._buffer=e,this._trimRight=t,this._startIndex=i,this._endIndex=r,this._startOverscan=n,this._endOverscan=s,this._startIndex<0&&(this._startIndex=0),this._endIndex>this._buffer.lines.length&&(this._endIndex=this._buffer.lines.length),this._current=this._startIndex}return e.prototype.hasNext=function(){return this._current<this._endIndex},e.prototype.next=function(){var e=this._buffer.getWrappedRangeForLine(this._current);e.first<this._startIndex-this._startOverscan&&(e.first=this._startIndex-this._startOverscan),e.last>this._endIndex+this._endOverscan&&(e.last=this._endIndex+this._endOverscan),e.first=Math.max(e.first,0),e.last=Math.min(e.last,this._buffer.lines.length);for(var t="",i=e.first;i<=e.last;++i)t+=this._buffer.translateBufferLineToString(i,this._trimRight);return this._current=e.last+1,{range:e,content:t}},e}();t.BufferStringIterator=u},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(1),n=function(){function e(e){this._maxLength=e,this.onDeleteEmitter=new r.EventEmitter,this.onInsertEmitter=new r.EventEmitter,this.onTrimEmitter=new r.EventEmitter,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}return Object.defineProperty(e.prototype,"onDelete",{get:function(){return this.onDeleteEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onInsert",{get:function(){return this.onInsertEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onTrim",{get:function(){return this.onTrimEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxLength",{get:function(){return this._maxLength},set:function(e){if(this._maxLength!==e){for(var t=new Array(e),i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return this._length},set:function(e){if(e>this._length)for(var t=this._length;t<e;t++)this._array[t]=void 0;this._length=e},enumerable:!0,configurable:!0}),e.prototype.get=function(e){return this._array[this._getCyclicIndex(e)]},e.prototype.set=function(e,t){this._array[this._getCyclicIndex(e)]=t},e.prototype.push=function(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++},e.prototype.recycle=function(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]},Object.defineProperty(e.prototype,"isFull",{get:function(){return this._length===this._maxLength},enumerable:!0,configurable:!0}),e.prototype.pop=function(){return this._array[this._getCyclicIndex(this._length---1)]},e.prototype.splice=function(e,t){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];if(t){for(var n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t}for(n=this._length-1;n>=e;n--)this._array[this._getCyclicIndex(n+i.length)]=this._array[this._getCyclicIndex(n)];for(n=0;n<i.length;n++)this._array[this._getCyclicIndex(e+n)]=i[n];if(this._length+i.length>this._maxLength){var s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length},e.prototype.trimStart=function(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)},e.prototype.shiftElements=function(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(var r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));var n=e+t+i-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(r=0;r<t;r++)this.set(e+r+i,this.get(e+r))}},e.prototype._getCyclicIndex=function(e){return(this._startIndex+e)%this._maxLength},e}();t.CircularList=n},function(e,t,i){"use strict";function r(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();var r=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),n=2===e[t+1].getWidth(0);return r&&n?i-1:i}Object.defineProperty(t,"__esModule",{value:!0}),t.reflowLargerGetLinesToRemove=function(e,t,i,n,s){for(var o=[],a=0;a<e.length-1;a++){var c=a,l=e.get(++c);if(l.isWrapped){for(var h=[e.get(a)];c<e.length&&l.isWrapped;)h.push(l),l=e.get(++c);if(n>=a&&n<c)a+=h.length-1;else{for(var u=0,f=r(h,u,t),_=1,d=0;_<h.length;){var p=r(h,_,t),v=p-d,g=i-f,y=Math.min(v,g);h[u].copyCellsFrom(h[_],d,f,y,!1),(f+=y)===i&&(u++,f=0),(d+=y)===p&&(_++,d=0),0===f&&0!==u&&2===h[u-1].getWidth(i-1)&&(h[u].copyCellsFrom(h[u-1],i-1,f++,1,!1),h[u-1].setCell(i-1,s))}h[u].replaceCells(f,i,s);for(var m=0,b=h.length-1;b>0&&(b>u||0===h[b].getTrimmedLength());b--)m++;m>0&&(o.push(a+h.length-m),o.push(m)),a+=h.length-1}}}return o},t.reflowLargerCreateNewLayout=function(e,t){for(var i=[],r=0,n=t[r],s=0,o=0;o<e.length;o++)if(n===o){var a=t[++r];e.onDeleteEmitter.fire({index:o-s,amount:a}),o+=a-1,s+=a,n=t[++r]}else i.push(o);return{layout:i,countRemoved:s}},t.reflowLargerApplyNewLayout=function(e,t){for(var i=[],r=0;r<t.length;r++)i.push(e.get(t[r]));for(r=0;r<i.length;r++)e.set(r,i[r]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,i){for(var n=[],s=e.map(function(i,n){return r(e,n,t)}).reduce(function(e,t){return e+t}),o=0,a=0,c=0;c<s;){if(s-c<i){n.push(s-c);break}o+=i;var l=r(e,a,t);o>l&&(o-=l,a++);var h=2===e[a].getWidth(o-1);h&&o--;var u=h?i-1:i;n.push(u),c+=u}return n},t.getWrappedLineTrimmedLength=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(1),o=function(e){function t(i){var r=e.call(this)||this;return r.line=i,r._id=t._nextId++,r.isDisposed=!1,r._onDispose=new s.EventEmitter,r}return n(t,e),Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{get:function(){return this._onDispose.event},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire())},t._nextId=1,t}(i(2).Disposable);t.Marker=o},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(5),o=i(28),a=function(){function e(e,t){this._renderService=e,this._charSizeService=t}return e.prototype.getCoords=function(e,t,i,r,n){return o.getCoords(e,t,i,r,this._charSizeService.hasValidSize,this._renderService.dimensions.actualCellWidth,this._renderService.dimensions.actualCellHeight,n)},e.prototype.getRawByteCoords=function(e,t,i,r){var n=this.getCoords(e,t,i,r);return o.getRawByteCoords(n)},e=r([n(0,s.IRenderService),n(1,s.ICharSizeService)],e)}();t.MouseService=a},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(1),a=i(31),c=Object.freeze({applicationCursorKeys:!1}),l=function(){function e(e,t,i,r){this._scrollToBottom=e,this._bufferService=t,this._logService=i,this._optionsService=r,this._onData=new o.EventEmitter,this._onUserInput=new o.EventEmitter,this.decPrivateModes=a.clone(c)}return Object.defineProperty(e.prototype,"onData",{get:function(){return this._onData.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onUserInput",{get:function(){return this._onUserInput.event},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this.decPrivateModes=a.clone(c)},e.prototype.triggerDataEvent=function(e,t){if(void 0===t&&(t=!1),!this._optionsService.options.disableStdin){var i=this._bufferService.buffer;i.ybase!==i.ydisp&&this._scrollToBottom(),t&&this._onUserInput.fire(),this._logService.debug('sending data "'+e+'"',function(){return e.split("").map(function(e){return e.charCodeAt(0)})}),this._onData.fire(e)}},e=r([n(1,s.IBufferService),n(2,s.ILogService),n(3,s.IOptionsService)],e)}();t.CoreService=l},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}},s=this&&this.__spreadArrays||function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var r=Array(e),n=0;for(t=0;t<i;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,n++)r[n]=s[o];return r};Object.defineProperty(t,"__esModule",{value:!0});var o,a=i(0);!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"}(o=t.LogLevel||(t.LogLevel={}));var c={debug:o.DEBUG,info:o.INFO,warn:o.WARN,error:o.ERROR,off:o.OFF},l=function(){function e(e){var t=this;this._optionsService=e,this._updateLogLevel(),this._optionsService.onOptionChange(function(e){"logLevel"===e&&t._updateLogLevel()})}return e.prototype._updateLogLevel=function(){this._logLevel=c[this._optionsService.options.logLevel]},e.prototype._evalLazyOptionalParams=function(e){for(var t=0;t<e.length;t++)"function"==typeof e[t]&&(e[t]=e[t]())},e.prototype._log=function(e,t,i){this._evalLazyOptionalParams(i),e.call.apply(e,s([console,"xterm.js: "+t],i))},e.prototype.debug=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.DEBUG&&this._log(console.log,e,t)},e.prototype.info=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.INFO&&this._log(console.info,e,t)},e.prototype.warn=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.WARN&&this._log(console.warn,e,t)},e.prototype.error=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.ERROR&&this._log(console.error,e,t)},e=r([n(0,a.IOptionsService)],e)}();t.LogService=l},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=function(){function e(e){this._bufferService=e,this.clearRange()}return Object.defineProperty(e.prototype,"start",{get:function(){return this._start},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"end",{get:function(){return this._end},enumerable:!0,configurable:!0}),e.prototype.clearRange=function(){this._start=this._bufferService.buffer.y,this._end=this._bufferService.buffer.y},e.prototype.markDirty=function(e){e<this._start?this._start=e:e>this._end&&(this._end=e)},e.prototype.markRangeDirty=function(e,t){if(e>t){var i=e;e=t,t=i}e<this._start&&(this._start=e),t>this._end&&(this._end=t)},e.prototype.markAllDirty=function(){this.markRangeDirty(0,this._bufferService.rows-1)},e=r([n(0,s.IBufferService)],e)}();t.DirtyRowService=o},function(e,t,i){"use strict";var r=this&&this.__spreadArrays||function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var r=Array(e),n=0;for(t=0;t<i;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,n++)r[n]=s[o];return r};Object.defineProperty(t,"__esModule",{value:!0});var n=i(0),s=i(13),o=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._entries=new Map;for(var i=0,r=e;i<r.length;i++){var n=r[i],s=n[0],o=n[1];this.set(s,o)}}return e.prototype.set=function(e,t){var i=this._entries.get(e);return this._entries.set(e,t),i},e.prototype.forEach=function(e){this._entries.forEach(function(t,i){return e(i,t)})},e.prototype.has=function(e){return this._entries.has(e)},e.prototype.get=function(e){return this._entries.get(e)},e}();t.ServiceCollection=o;var a=function(){function e(){this._services=new o,this._services.set(n.IInstantiationService,this)}return e.prototype.setService=function(e,t){this._services.set(e,t)},e.prototype.createInstance=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=s.getServiceDependencies(e).sort(function(e,t){return e.index-t.index}),o=[],a=0,c=n;a<c.length;a++){var l=c[a],h=this._services.get(l.id);if(!h)throw new Error("[createInstance] "+e.name+" depends on UNKNOWN service "+l.id+".");o.push(h)}var u=n.length>0?n[0].index:t.length;if(t.length!==u)throw new Error("[createInstance] First service dependency of "+e.name+" at position "+(u+1)+" conflicts with "+t.length+" static arguments");return new(e.bind.apply(e,r([void 0],r(t,o))))},e}();t.InstantiationService=a},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(1),a={NONE:{events:0,restrict:function(){return!1}},X10:{events:1,restrict:function(e){return 4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)}},VT200:{events:19,restrict:function(e){return 32!==e.action}},DRAG:{events:23,restrict:function(e){return 32!==e.action||3!==e.button}},ANY:{events:31,restrict:function(e){return!0}}};function c(e,t){var i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0!==e.action||t||(i|=3)),i}var l=String.fromCharCode,h={DEFAULT:function(e){var t=[c(e,!1)+32,e.col+32,e.row+32];return t=t.map(function(e){return e>127?127:e}),"\e[M"+l(t[0])+l(t[1])+l(t[2])},SGR:function(e){var t=0===e.action&&4!==e.button?"m":"M";return"\e[<"+c(e,!0)+";"+e.col+";"+e.row+t}},u=function(){function e(e,t){var i=this;this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._onProtocolChange=new o.EventEmitter,this._lastEvent=null,Object.keys(a).forEach(function(e){return i.addProtocol(e,a[e])}),Object.keys(h).forEach(function(e){return i.addEncoding(e,h[e])}),this.reset()}return e.prototype.addProtocol=function(e,t){this._protocols[e]=t},e.prototype.addEncoding=function(e,t){this._encodings[e]=t},Object.defineProperty(e.prototype,"activeProtocol",{get:function(){return this._activeProtocol},set:function(e){if(!this._protocols[e])throw new Error('unknown protocol "'+e+'"');this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activeEncoding",{get:function(){return this._activeEncoding},set:function(e){if(!this._encodings[e])throw new Error('unknown encoding "'+e+'"');this._activeEncoding=e},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null},Object.defineProperty(e.prototype,"onProtocolChange",{get:function(){return this._onProtocolChange.event},enumerable:!0,configurable:!0}),e.prototype.triggerMouseEvent=function(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows)return!1;if(4===e.button&&32===e.action)return!1;if(3===e.button&&32!==e.action)return!1;if(4!==e.button&&(2===e.action||3===e.action))return!1;if(e.col++,e.row++,32===e.action&&this._lastEvent&&this._compareEvents(this._lastEvent,e))return!1;if(!this._protocols[this._activeProtocol].restrict(e))return!1;var t=this._encodings[this._activeEncoding](e);return this._coreService.triggerDataEvent(t,!0),this._lastEvent=e,!0},e.prototype.explainEvents=function(e){return{DOWN:!!(1&e),UP:!!(2&e),DRAG:!!(4&e),MOVE:!!(8&e),WHEEL:!!(16&e)}},e.prototype._compareEvents=function(e,t){return e.col===t.col&&(e.row===t.row&&(e.button===t.button&&(e.action===t.action&&(e.ctrl===t.ctrl&&(e.alt===t.alt&&e.shift===t.shift)))))},e=r([n(0,s.IBufferService),n(1,s.ICoreService)],e)}();t.CoreMouseService=u},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0}return e.prototype.writeSync=function(e){if(this._writeBuffer.length){for(var t=this._bufferOffset;t<this._writeBuffer.length;++t){var i=this._writeBuffer[t],r=this._callbacks[t];this._action(i),r&&r()}this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=2147483647}this._action(e)},e.prototype.write=function(e,t){var i=this;if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");this._writeBuffer.length||(this._bufferOffset=0,setTimeout(function(){return i._innerWrite()})),this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)},e.prototype._innerWrite=function(){for(var e=this,t=Date.now();this._writeBuffer.length>this._bufferOffset;){var i=this._writeBuffer[this._bufferOffset],r=this._callbacks[this._bufferOffset];if(this._bufferOffset++,this._action(i),this._pendingData-=i.length,r&&r(),Date.now()-t>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(function(){return e._innerWrite()},0)):(this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0)},e}();t.WriteBuffer=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._addons=[]}return e.prototype.dispose=function(){for(var e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()},e.prototype.loadAddon=function(e,t){var i=this,r={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(r),t.dispose=function(){return i._wrappedAddonDispose(r)},t.activate(e)},e.prototype._wrappedAddonDispose=function(e){if(!e.isDisposed){for(var t=-1,i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(-1===t)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},e}();t.AddonManager=r}])});
+//# sourceMappingURL=xterm.js.map
\ No newline at end of file
diff --git a/node_modules/xterm/lib/xterm.js.map b/node_modules/xterm/lib/xterm.js.map
new file mode 100644 (file)
index 0000000..9afd254
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap","webpack:///./src/common/services/Services.ts","webpack:///./src/common/EventEmitter.ts","webpack:///./src/common/Lifecycle.ts","webpack:///./src/common/buffer/Constants.ts","webpack:///./src/common/buffer/CellData.ts","webpack:///./src/browser/services/Services.ts","webpack:///./src/common/buffer/AttributeData.ts","webpack:///./src/browser/Lifecycle.ts","webpack:///./src/common/input/TextDecoder.ts","webpack:///./src/browser/renderer/atlas/Constants.ts","webpack:///./src/common/Platform.ts","webpack:///./src/common/data/EscapeSequences.ts","webpack:///./src/browser/renderer/BaseRenderLayer.ts","webpack:///./src/common/services/ServiceRegistry.ts","webpack:///./src/common/TypedArrayUtils.ts","webpack:///./src/common/buffer/BufferLine.ts","webpack:///./src/browser/LocalizableStrings.ts","webpack:///./src/common/data/Charsets.ts","webpack:///./src/common/CharWidth.ts","webpack:///./src/common/parser/Params.ts","webpack:///./src/common/parser/OscParser.ts","webpack:///./src/common/parser/Constants.ts","webpack:///./src/common/parser/DcsParser.ts","webpack:///./src/browser/renderer/atlas/CharAtlasCache.ts","webpack:///./src/browser/renderer/atlas/CharAtlasUtils.ts","webpack:///./src/browser/ColorManager.ts","webpack:///./src/browser/renderer/RendererUtils.ts","webpack:///./src/browser/renderer/CharacterJoinerRegistry.ts","webpack:///./src/browser/input/Mouse.ts","webpack:///./src/browser/RenderDebouncer.ts","webpack:///./src/browser/ScreenDprMonitor.ts","webpack:///./src/common/Clone.ts","webpack:///./src/public/Terminal.ts","webpack:///./src/Terminal.ts","webpack:///./src/browser/input/CompositionHelper.ts","webpack:///./src/browser/Viewport.ts","webpack:///./src/browser/Clipboard.ts","webpack:///./src/InputHandler.ts","webpack:///./src/common/parser/EscapeSequenceParser.ts","webpack:///./src/renderer/Renderer.ts","webpack:///./src/browser/renderer/TextRenderLayer.ts","webpack:///./src/browser/renderer/GridCache.ts","webpack:///./src/browser/renderer/atlas/DynamicCharAtlas.ts","webpack:///./src/browser/renderer/atlas/BaseCharAtlas.ts","webpack:///./src/browser/renderer/atlas/LRUMap.ts","webpack:///./src/browser/renderer/SelectionRenderLayer.ts","webpack:///./src/renderer/CursorRenderLayer.ts","webpack:///./src/browser/renderer/LinkRenderLayer.ts","webpack:///./src/browser/Linkifier.ts","webpack:///./src/browser/services/SelectionService.ts","webpack:///./src/browser/selection/SelectionModel.ts","webpack:///./src/browser/input/MoveToCell.ts","webpack:///./src/browser/services/SoundService.ts","webpack:///./src/browser/MouseZoneManager.ts","webpack:///./src/AccessibilityManager.ts","webpack:///./src/renderer/dom/DomRenderer.ts","webpack:///./src/browser/renderer/dom/DomRendererRowFactory.ts","webpack:///./src/common/input/Keyboard.ts","webpack:///./src/WindowsMode.ts","webpack:///./src/browser/services/RenderService.ts","webpack:///./src/common/services/OptionsService.ts","webpack:///./src/browser/services/CharSizeService.ts","webpack:///./src/common/services/BufferService.ts","webpack:///./src/common/buffer/BufferSet.ts","webpack:///./src/common/buffer/Buffer.ts","webpack:///./src/common/CircularList.ts","webpack:///./src/common/buffer/BufferReflow.ts","webpack:///./src/common/buffer/Marker.ts","webpack:///./src/browser/services/MouseService.ts","webpack:///./src/common/services/CoreService.ts","webpack:///./src/common/services/LogService.ts","webpack:///./src/common/services/DirtyRowService.ts","webpack:///./src/common/services/InstantiationService.ts","webpack:///./src/common/services/CoreMouseService.ts","webpack:///./src/common/input/WriteBuffer.ts","webpack:///./src/public/AddonManager.ts"],"names":["root","factory","exports","module","define","amd","a","i","window","installedModules","__webpack_require__","moduleId","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","IBufferService","createDecorator","ICoreMouseService","ICoreService","IDirtyRowService","IInstantiationService","ILogService","IOptionsService","_listeners","this","_event","listener","push","dispose","length","splice","fire","data","queue","undefined","EventEmitter","_disposables","_isDisposed","forEach","register","unregister","index","indexOf","Disposable","DEFAULT_COLOR","DEFAULT_ATTR","CHAR_DATA_ATTR_INDEX","CHAR_DATA_CHAR_INDEX","CHAR_DATA_WIDTH_INDEX","CHAR_DATA_CODE_INDEX","NULL_CELL_CHAR","NULL_CELL_WIDTH","NULL_CELL_CODE","WHITESPACE_CELL_CHAR","WHITESPACE_CELL_WIDTH","WHITESPACE_CELL_CODE","content","fg","bg","combinedData","fromCharData","obj","CellData","setFromCharData","isCombined","getWidth","getChars","stringFromCodePoint","getCode","charCodeAt","combined","code","second","getAsCharData","AttributeData","ICharSizeService","IMouseService","IRenderService","ISelectionService","ISoundService","toColorRGB","fromColorRGB","clone","newObj","isInverse","isBold","isUnderline","isBlink","isInvisible","isItalic","isDim","getFgColorMode","getBgColorMode","isFgRGB","isBgRGB","isFgPalette","isBgPalette","isFgDefault","isBgDefault","getFgColor","getBgColor","node","type","handler","useCapture","addEventListener","removeEventListener","codePoint","String","fromCharCode","start","end","result","codepoint","_interim","clear","decode","input","target","size","startPos","StringToUtf32","interim","Uint8Array","fill","byte1","byte2","byte3","byte4","discardInterim","cp","pos","tmp","missing","fourStop","Utf8ToUtf32","INVERTED_DEFAULT_COLOR","DIM_OPACITY","CHAR_ATLAS_CELL_SPACING","isNode","navigator","userAgent","platform","contains","arr","el","isFirefox","isSafari","test","isMac","isIpad","isIphone","isWindows","isLinux","C0","NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL","BS","HT","LF","VT","FF","CR","SO","SI","DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB","CAN","EM","SUB","ESC","FS","GS","RS","US","SP","DEL","C1","PAD","HOP","BPH","NBH","IND","NEL","SSA","ESA","HTS","HTJ","VTS","PLD","PLU","RI","SS2","SS3","DCS","PU1","PU2","STS","CCH","MW","SPA","EPA","SOS","SGCI","SCI","CSI","ST","OSC","PM","APC","_container","id","zIndex","_alpha","_colors","_rendererId","_bufferService","_optionsService","_scaledCharWidth","_scaledCharHeight","_scaledCellWidth","_scaledCellHeight","_scaledCharLeft","_scaledCharTop","_currentGlyphIdentifier","chars","bold","dim","italic","_canvas","document","createElement","classList","add","style","toString","_initCanvas","appendChild","removeChild","_charAtlas","_ctx","throwIfFalsy","getContext","alpha","_clearAll","onOptionsChanged","onBlur","onFocus","onCursorMove","onGridChanged","startRow","endRow","onSelectionChanged","columnSelectMode","setColors","colorSet","_refreshCharAtlas","_setTransparency","oldCanvas","cloneNode","replaceChild","rows","acquireCharAtlas","options","warmUp","resize","scaledCellWidth","scaledCellHeight","scaledCharWidth","scaledCharHeight","scaledCharLeft","scaledCharTop","width","scaledCanvasWidth","height","scaledCanvasHeight","canvasWidth","canvasHeight","_fillCells","x","y","fillRect","_fillBottomLineAtCells","devicePixelRatio","_fillLeftLineAtCell","_strokeRectAtCell","lineWidth","strokeRect","clearRect","fillStyle","background","css","_clearCells","_fillCharTrueColor","cell","font","_getFont","textBaseline","_clipRow","fillText","_drawChars","_drawUncachedChars","drawBoldTextInBrightColors","draw","save","join","ansi","foreground","globalAlpha","restore","beginPath","rect","cols","clip","fontWeightBold","fontWeight","fontSize","fontFamily","BaseRenderLayer","DI_TARGET","DI_DEPENDENCIES","storeServiceDependency","serviceRegistry","Map","ctor","has","decorator","arguments","Error","set","fillFallback","array","b","constructor","CELL_SIZE","DEFAULT_ATTR_DATA","freeze","fillCellData","isWrapped","_combined","_data","Uint32Array","setCell","hasWidth","getFg","getBg","hasContent","getCodePoint","getString","loadCell","startIndex","setCellFromCodePoint","addCodepointToCell","insertCells","deleteCells","replaceCells","subarray","keys","parseInt","copyFrom","line","newLine","BufferLine","getTrimmedLength","copyCellsFrom","src","srcCol","destCol","applyInReverse","srcData","srcCombinedKeys","translateToString","trimRight","startCol","endCol","Math","min","promptLabel","tooMuchOutput","CHARSETS","DEFAULT_CHARSET","wcwidth","opts","COMBINING_BMP","COMBINING_HIGH","control","table","nul","num","ucs","mid","max","bisearch","MAX_SUBPARAMS","maxLength","maxSubParamsLength","params","Int32Array","_subParams","_subParamsLength","_subParamsIdx","Uint16Array","_rejectDigits","_rejectSubDigits","_digitIsSub","fromArray","values","Params","Array","k","addSubParam","addParam","newParams","toArray","res","slice","reset","hasSubParams","idx","getSubParams","getSubParamsAll","addDigit","store","cur","_state","_id","_handlers","_handlerFb","addHandler","ident","handlerList","handlerIndex","setHandler","clearHandler","setHandlerFallback","_start","handlers","j","_put","put","utf32ToString","_end","success","OscParser","_handler","_hitLimit","PAYLOAD_LIMIT","ret","OscHandler","EMPTY_HANDLERS","_active","_ident","unhook","hook","DcsParser","_params","DcsHandler","charAtlasCache","rendererId","colors","newConfig","generateConfig","ownedByIndex","entry","ownedBy","configEquals","config","atlas","newEntry","DynamicCharAtlas","clonedColors","cursor","cursorAccent","selection","allowTransparency","rgba","colorCode","DEFAULT_FOREGROUND","fromHex","DEFAULT_BACKGROUND","DEFAULT_CURSOR","DEFAULT_CURSOR_ACCENT","DEFAULT_SELECTION","toPaddedHex","DEFAULT_ANSI_COLORS","v","g","ch","canvas","ctx","globalCompositeOperation","_litmusColor","createLinearGradient","setTheme","theme","_parseColor","black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite","fallback","console","warn","getImageData","ColorManager","firstCell","_width","JoinedCellData","_characterJoiners","_nextCharacterJoinerId","_workCell","registerCharacterJoiner","joiner","deregisterCharacterJoiner","joinerId","getJoinedCharacters","row","buffer","lines","ranges","lineStr","rangeStartColumn","currentStringIndex","rangeStartStringIndex","rangeAttrFG","rangeAttrBG","joinedRanges","_getJoinedRanges","endIndex","lineData","text","substring","joinerRanges","CharacterJoinerRegistry","_mergeRanges","_stringRangesToCellRanges","currentRangeIndex","currentRangeStarted","currentRange","newRange","inRange","range","getCoordsRelativeToElement","event","element","getBoundingClientRect","clientX","left","clientY","top","colCount","rowCount","hasValidCharSize","actualCellWidth","actualCellHeight","isSelection","coords","ceil","_renderCallback","_animationFrame","cancelAnimationFrame","refresh","rowStart","rowEnd","_rowCount","_rowStart","_rowEnd","requestAnimationFrame","_innerRefresh","RenderDebouncer","_currentDevicePixelRatio","setListener","_listener","clearListener","_outerListener","_updateDpr","_resolutionMediaMatchList","removeListener","matchMedia","addListener","ScreenDprMonitor","val","depth","clonedObject","isArray","_core","Terminal","_addonManager","AddonManager","onLineFeed","onSelectionChange","onData","onTitleChange","onScroll","onKey","onRender","onResize","_parser","ParserApi","textarea","BufferApiView","markers","blur","focus","columns","_verifyIntegers","open","parent","attachCustomKeyEventHandler","customKeyEventHandler","registerLinkMatcher","regex","deregisterLinkMatcher","matcherId","addMarker","cursorYOffset","hasSelection","select","column","getSelection","getSelectionPosition","clearSelection","selectAll","selectLines","scrollLines","amount","scrollPages","pageCount","scrollToTop","scrollToBottom","scrollToLine","write","callback","writeUtf8","writeln","paste","getOption","optionsService","setOption","loadAddon","addon","Strings","Infinity","isNaN","_buffer","ydisp","ybase","getLine","BufferLineApiView","_line","getCell","BufferCellApiView","startColumn","endColumn","_x","addCsiHandler","addDcsHandler","addEscHandler","addOscHandler","browser","Browser","mouseEvents","_keyDownHandled","_blankLine","_onCursorMove","_onData","_onKey","_onLineFeed","_onRender","_onResize","_onScroll","_onSelectionChange","_onTitleChange","_onFocus","_onBlur","onA11yCharEmitter","onA11yTabEmitter","_instantiationService","InstantiationService","OptionsService","setService","createInstance","BufferService","_logService","LogService","_coreService","CoreService","e","_coreMouseService","CoreMouseService","_dirtyRowService","DirtyRowService","_setupOptionsListeners","_setup","_writeBuffer","WriteBuffer","_inputHandler","parse","_windowsMode","_renderService","_customKeyEventHandler","parentNode","_parent","body","cursorState","cursorHidden","applicationKeypad","originMode","insertMode","wraparoundMode","bracketedPasteMode","charset","gcharset","glevel","charsets","curAttrData","_eraseAttrData","currentParam","_userScrolling","InputHandler","linkifier","Linkifier","windowsMode","applyWindowsMode","buffers","active","eraseAttrData","preventScroll","activeElement","hasFocus","onOptionChange","_charSizeService","measure","setRenderer","_createRenderer","viewport","syncScrollArea","screenReaderMode","_accessibilityManager","AccessibilityManager","setupTabStops","_setTheme","_onTextAreaFocus","ev","sendFocus","triggerDataEvent","updateCursorStyle","showCursor","_onTextAreaBlur","remove","_initGlobal","_bindKeys","addDisposableDomListener","copyHandler","_selectionService","pasteHandlerWrapper","handlePasteEvent","button","rightClickHandler","screenElement","rightClickSelectsWord","moveTextAreaUnderMouseCursor","_keyUp","_keyDown","_keyPress","_compositionHelper","compositionstart","compositionupdate","compositionend","updateCompositionElements","_queueLinkification","_document","ownerDocument","dir","setAttribute","fragment","createDocumentFragment","_viewportElement","_viewportScrollArea","_helperContainer","tabIndex","CharSizeService","_compositionView","CompositionHelper","_theme","_colorManager","renderer","RenderService","_soundService","SoundService","_mouseService","MouseService","Viewport","suppressEvent","onThemeChange","onDimensionsChange","SelectionService","onRedrawRequest","onLinuxMouseSelection","_mouseZoneManager","MouseZoneManager","clearAll","attachToDom","onMouseDown","disable","enable","bindMouse","rendererType","Renderer","DomRenderer","self","sendEvent","but","action","getRawByteCoords","overrideType","buttons","deltaY","triggerMouseEvent","col","ctrl","ctrlKey","alt","altKey","shift","shiftKey","requestedEvents","mouseup","wheel","mousedrag","mousemove","eventListeners","cancel","preventDefault","onProtocolChange","events","logLevel","debug","explainEvents","activeProtocol","shouldForceSelection","hasScrollback","getLinesScrolled","sequence","decPrivateModes","applicationCursorKeys","abs","onWheel","onTouchStart","onTouchMove","refreshRows","linkifyRows","shouldColumnSelect","scroll","eraseAttr","getBlankLine","topRow","scrollTop","bottomRow","scrollBottom","willBufferBeTrimmed","isFull","recycle","scrollRegionHeight","shiftElements","markRangeDirty","disp","suppressScrollEvent","oldYdisp","scrollAmount","normal","setSelection","selectionText","selectionStart","selectionEnd","keydown","evaluateKeyboardEvent","macOptionIsMeta","scrollCount","_isThirdLevelShift","domEvent","thirdLevelKey","metaKey","keyCode","setgLevel","setgCharset","wasModifierKeyOnlyEvent","charCode","which","bell","_soundBell","playBellSound","_visualBell","clearTimeout","_visualBellTimer","setTimeout","MINIMUM_COLS","MINIMUM_ROWS","hasValidSize","is","term","termName","handleTitle","title","inputHandler","userScrolling","force","cancelEvents","stopPropagation","bellStyle","writeSync","_textarea","_isComposing","_isSendingComposition","_compositionPosition","textContent","_finalizeComposition","_handleAnyTextareaChanges","waitForPropagation","_clearTextareaPosition","oldValue","diff","replace","dontRecurse","isCursorInViewport","cellHeight","lineHeight","cursorTop","cursorLeft","compositionViewBounds","FALLBACK_SCROLL_BAR_WIDTH","_scrollLines","_scrollArea","scrollBarWidth","_currentRowHeight","_lastRecordedBufferLength","_lastRecordedViewportHeight","_lastRecordedBufferHeight","_lastTouchY","_lastScrollTop","_wheelPartialScroll","_refreshAnimationFrame","_ignoreNextScrollEvent","offsetWidth","backgroundColor","_refresh","immediate","dimensions","offsetHeight","newBufferHeight","round","newScrollTop","offsetParent","_bubbleScroll","scrollPosFromTop","cancelable","_getPixelsScrolled","_applyScrollModifier","deltaMode","WheelEvent","DOM_DELTA_LINE","DOM_DELTA_PAGE","DOM_DELTA_PIXEL","floor","modifier","fastScrollModifier","fastScrollSensitivity","scrollSensitivity","touches","pageY","prepareTextForTerminal","bracketTextForPaste","coreService","position","selectionService","clipboardData","setData","getData","shouldSelectWord","isClickInSelection","selectWordAtCursor","GLEVEL","concat","pt","cursorStyle","cursorBlink","_terminal","EscapeSequenceParser","_parseBuffer","_stringDecoder","_utf8Decoder","setCsiHandlerFallback","identifier","identToString","setEscHandlerFallback","setExecuteHandlerFallback","setOscHandlerFallback","setDcsHandlerFallback","payload","setPrintHandler","print","setCsiHandler","final","insertChars","intermediates","scrollLeft","cursorUp","scrollRight","cursorDown","cursorForward","cursorBackward","cursorNextLine","cursorPrecedingLine","cursorCharAbsolute","cursorPosition","cursorForwardTab","eraseInDisplay","prefix","eraseInLine","insertLines","deleteLines","deleteChars","scrollUp","scrollDown","eraseChars","cursorBackwardTab","charPosAbsolute","hPositionRelative","repeatPrecedingCharacter","sendDeviceAttributesPrimary","sendDeviceAttributesSecondary","linePosAbsolute","vPositionRelative","hVPosition","tabClear","setMode","setModePrivate","resetMode","resetModePrivate","charAttributes","deviceStatus","deviceStatusPrivate","softReset","setCursorStyle","setScrollRegion","saveCursor","restoreCursor","insertColumns","deleteColumns","setExecuteHandler","lineFeed","carriageReturn","backspace","tab","shiftOut","shiftIn","nextLine","tabSet","setOscHandler","setTitle","setEscHandler","reverseIndex","keypadApplicationMode","keypadNumericMode","selectDefaultCharset","flag","selectCharset","screenAlignmentPattern","setErrorHandler","state","error","setDcsHandler","DECRQSS","cursorStartX","cursorStartY","len","chWidth","curAttr","bufferRow","markDirty","getNullCell","precedingCodepoint","convertEol","_restrictCursor","originalX","nextStop","_setCursor","_moveCursor","diffToTop","diffToBottom","param","tabs","prevStop","_eraseInBufferLine","clearWrap","_resetBufferLine","scrollBackSize","trimStart","scrollBottomRowsOffset","scrollBottomAbsolute","savedCols","activeEncoding","activateAltBuffer","activateNormalBuffer","_extractColor","attr","accu","cSpace","advance","subparams","isBlinking","bottom","savedX","savedY","savedCurAttrData","savedCharset","_savedCharset","collectAndFlag","level","yOffset","markAllDirty","setDefault","next","addMany","codes","TransitionTable","VT500_TRANSITION_TABLE","blueprint","apply","map","unused","PRINTABLES","EXECUTABLES","states","TRANSITIONS","initialState","currentState","_collect","_printHandlerFb","_executeHandlerFb","_csiHandlerFb","_escHandlerFb","_errorHandlerFb","_printHandler","_executeHandlers","_csiHandlers","_escHandlers","_oscParser","_dcsParser","_errorHandler","_identifier","finalRange","intermediate","finalCode","reverse","clearPrintHandler","clearEscHandler","clearExecuteHandler","clearCsiHandler","clearDcsHandler","clearOscHandler","clearErrorHandler","transition","osc","dcs","collect","abort","handlersEsc","jj","nextRendererId","bufferService","_characterJoinerRegistry","_renderLayers","TextRenderLayer","SelectionRenderLayer","LinkRenderLayer","CursorRenderLayer","_devicePixelRatio","_updateDimensions","removeTerminalFromCache","onDevicePixelRatioChange","onCharSizeChanged","_runOperation","operation","renderRows","letterSpacing","container","characterJoinerRegistry","_characterWidth","_characterFont","_characterOverlapCache","GridCache","terminalFont","_forEachCell","firstRow","lastRow","joinerRegistry","isJoined","lastCharX","_isOverlapping","_drawBackground","startX","startY","prevFillStyle","nextFillStyle","_drawForeground","cache","beginFrame","overlaps","measureText","TEXTURE_WIDTH","TEXTURE_HEIGHT","TRANSPARENT_COLOR","getGlyphCacheKey","glyph","_config","_drawToCacheCount","_glyphsWaitingOnBitmap","_bitmapCommitTimeout","_bitmap","_cacheCanvas","_cacheCtx","tmpCanvas","_tmpCtx","_height","capacity","_cacheMap","LRUMap","prealloc","_canCache","glyphKey","cacheValue","_drawFromCache","peek","_drawToCache","_toCoordinateX","_toCoordinateY","isEmpty","cacheX","cacheY","drawImage","inBitmap","_getColorFromAnsiIndex","_getBackgroundColor","_getForegroundColor","fontStyle","imageData","color","offset","clearColor","putImageData","_addGlyphToBitmap","_generateBitmap","glyphsMovingToBitmap","createImageBitmap","then","bitmap","BaseCharAtlas","NoneCharAtlas","_didWarmUp","_doWarmUp","_map","_head","_tail","_nodePool","_unlinkNode","prev","_appendNode","tail","count","nodePool","peekValue","head","pop","_clearState","_didStateChange","viewportStartRow","viewportEndRow","viewportCappedStartRow","viewportCappedEndRow","startRowEndCol","middleRowsCount","_areCoordinatesEqual","coord1","coord2","_cell","isFocused","_cursorRenderers","_renderBarCursor","_renderBlockCursor","_renderUnderlineCursor","_clearCursor","_cursorBlinkStateManager","pause","resume","CursorBlinkStateManager","_render","restartBlinkAnimation","isPaused","triggeredByAnimationFrame","cursorY","viewportRelativeCursorY","_renderBlurCursor","isCursorVisible","strokeStyle","_restartInterval","_blinkStartTimeout","_blinkInterval","clearInterval","_animationTimeRestarted","Date","now","timeToStart","time","setInterval","onLinkHover","_onLinkHover","onLinkLeave","_onLinkLeave","_clearCurrentLink","x1","y1","middleRowCount","y2","x2","is256Color","_linkMatchers","_nextLinkMatcherId","_onLinkTooltip","_rowsToLinkify","mouseZoneManager","_element","_rowsTimeoutId","_linkifyRows","_timeBeforeLatency","absoluteRowIndexStart","absoluteRowIndexEnd","overscanLineLimit","iterator","hasNext","_doLinkifyRow","first","matcher","matchIndex","validationCallback","hoverTooltipCallback","tooltipCallback","hoverLeaveCallback","leaveCallback","willLinkActivate","priority","_addLinkMatcherToList","rowIndex","match","rex","RegExp","source","flags","stringIndex","uri","lastIndex","bufferIndex","stringIndexToBufferIndex","isValid","_addLink","exec","getStringCellWidth","MouseZone","_createLinkHoverEvent","clickCallback","hoverCallback","NON_BREAKING_SPACE_CHAR","ALL_NON_BREAKING_SPACE_REGEX","_screenElement","_dragScrollAmount","_enabled","_mouseDownTimeStamp","_onLinuxMouseSelection","_onRedrawRequest","_mouseMoveListener","_onMouseMove","_mouseUpListener","_onMouseUp","onUserInput","_trimListener","onTrim","_onTrim","onBufferActivate","_onBufferActivate","_model","SelectionModel","_activeSelectionMode","_removeMouseDownListeners","finalSelectionStart","finalSelectionEnd","lineText","translateBufferLineToString","bufferLine","isLinuxMouseSelection","_getMouseBufferCoords","_areCoordsInSelection","_selectWordAt","isSelectAllActive","getCoords","_getMouseEventScrollAmount","terminalHeight","macOptionClickForcesSelection","timeStamp","_onIncrementalClick","detail","_onSingleClick","_onDoubleClick","_onTripleClick","_addMouseDownListeners","_dragScrollIntervalTimer","_dragScroll","selectionStartLength","_selectLineAt","stopImmediatePropagation","previousSelectionEnd","_selectToWordAt","timeElapsed","coordinates","moveToCellSequence","activeBuffer","_convertViewportColToCharacterIndex","charIndex","_getWordAt","allowWhitespaceOnlySelection","followWrappedLinesAbove","followWrappedLinesBelow","charOffset","leftWideCharCount","rightWideCharCount","leftLongCharOffset","rightLongCharOffset","charAt","_isCharWordSeparator","trim","previousBufferLine","previousLineWordPosition","nextBufferLine","nextLineWordPosition","wordPosition","areSelectionValuesReversed","wordSeparator","wrappedRange","getWrappedRangeForLine","last","startPlusLength","moveToRequestedRow","targetY","applicationCursor","wrappedRowsForRow","repeat","wrappedRows","direction","verticalDirection","wrappedRowsCount","currentRow","lineWraps","horizontalDirection","targetX","forward","currentCol","bufferStr","mod","str","rpt","moveHorizontallyOnly","resetStartingRow","moveToRequestedCol","_audioContext","audioContextCtor","AudioContext","webkitAudioContext","audioContext","bellAudioSource","createBufferSource","decodeAudioData","_base64ToArrayBuffer","_removeMimeType","bellSound","connect","destination","base64","binaryString","atob","bytes","dataURI","split","_zones","_areZonesActive","_lastHoverCoords","_initialSelectionLength","_onMouseDown","_mouseLeaveListener","_onMouseLeave","_clickListener","_onClick","_deactivate","zone","_activate","_currentZone","pageX","_onHover","_findZoneEventAt","_tooltipTimeout","_onTooltip","_getSelectionLength","currentSelectionLength","_liveRegionLineCount","_charsToConsume","_charsToAnnounce","_accessibilityTreeRoot","_rowContainer","_rowElements","_createAccessibilityTreeNode","_topBoundaryFocusListener","_onBoundaryFocus","_bottomBoundaryFocusListener","_refreshRowsDimensions","_renderRowsDebouncer","_renderRows","_refreshRows","_liveRegion","insertAdjacentElement","onA11yChar","char","_onChar","onA11yTab","spaceCount","_onTab","_clearLiveRegion","_screenDprMonitor","boundaryElement","beforeBoundaryElement","getAttribute","relatedTarget","topBoundaryElement","bottomBoundaryElement","newElement","unshift","children","_refreshRowDimensions","MAX_ROWS_TO_READ","keyChar","setSize","posInSet","innerHTML","_announceCharacters","TERMINAL_CLASS_PREFIX","ROW_CONTAINER_CLASS","SELECTION_CLASS","nextTerminalId","_terminalClass","_refreshRowElements","_selectionContainer","_injectCss","_rowFactory","DomRendererRowFactory","_themeStyleElement","_dimensionsStyleElement","overflow","styles","_terminalSelector","BOLD_CLASS","ITALIC_CLASS","CURSOR_CLASS","CURSOR_STYLE_BLOCK_CLASS","CURSOR_BLINK_CLASS","CURSOR_STYLE_BAR_CLASS","CURSOR_STYLE_UNDERLINE_CLASS","documentFragment","_createSelectionElement","colStart","colEnd","terminal","cursorAbsoluteY","cursorX","rowElement","createRow","_setCellUnderline","enabled","span","textDecoration","DIM_CLASS","UNDERLINE_CLASS","isCursorRow","cellWidth","lineLength","charElement","swapColor","KEYCODE_KEY_MAPPINGS","48","49","50","51","52","53","54","55","56","57","186","187","188","189","190","191","192","219","220","221","222","applicationCursorMode","modifiers","keyMapping","lastChar","_renderer","charSizeService","_isPaused","_needsFullRefresh","_canvasWidth","_canvasHeight","_onDimensionsChange","_onRefreshRequest","_renderDebouncer","onCharSizeChange","IntersectionObserver","_onIntersectionChange","threshold","observe","disconnect","intersectionRatio","_fireOnCanvasResize","changeOptions","_fullRefresh","DEFAULT_BELL_SOUND","DEFAULT_OPTIONS","scrollback","disableStdin","tabStopWidth","screenKeys","useFlowControl","CONSTRUCTOR_ONLY_OPTIONS","_onOptionChange","newValue","_sanitizeAndValidateOption","parentElement","_onCharSizeChange","_measureStrategy","DomMeasureStrategy","_parentElement","_result","_measureElement","geometry","BufferSet","_normal","Buffer","fillViewportRows","_alt","_activeBuffer","inactiveBuffer","fillAttr","newCols","newRows","MAX_BUFFER_SIZE","_hasScrollback","_nullCell","_whitespaceCell","_cols","_rows","CircularList","_getCorrectBufferLength","getWhitespaceCell","relativeY","correctBufferLength","nullCell","newMaxLength","addToY","amountToTrim","_isReflowEnabled","_reflow","_reflowLarger","_reflowSmaller","toRemove","reflowLargerGetLinesToRemove","newLayoutResult","reflowLargerCreateNewLayout","reflowLargerApplyNewLayout","layout","_reflowLargerAdjustViewport","countRemoved","viewportAdjustments","toInsert","countToInsert","wrappedLines","absoluteY","lastLineLength","destLineLengths","reflowSmallerGetNewLineLengths","linesToAdd","trimmedLines","newLines","destLineIndex","srcLineIndex","cellsToCopy","wrappedLinesIndex","getWrappedLineTrimmedLength","insertEvents","originalLines","originalLinesLength","originalLineIndex","nextToInsertIndex","nextToInsert","countInsertedSoFar","nextI","insertCountEmitted","onInsertEmitter","onTrimEmitter","lineIndex","marker","Marker","onInsert","onDelete","onDispose","_removeMarker","startOverscan","endOverscan","BufferStringIterator","_trimRight","_startIndex","_endIndex","_startOverscan","_endOverscan","_current","_maxLength","onDeleteEmitter","_array","_length","newArray","_getCyclicIndex","newLength","deleteCount","items","countToTrim","expandListBy","endsInNull","followingLineStartsWithWide","oldCols","bufferAbsoluteY","srcTrimmedTineLength","srcRemainingCells","destRemainingCells","countToRemove","nextToRemoveIndex","nextToRemoveStart","countRemovedSoFar","newLayout","newLayoutLines","newLineLengths","cellsNeeded","reduce","srcLine","cellsAvailable","oldTrimmedLength","endsWithWide","_nextId","isDisposed","_onDispose","DEFAULT_DEC_PRIVATE_MODES","_scrollToBottom","_onUserInput","wasUserInput","LogLevel","optionsKeyToLogLevel","DEBUG","info","INFO","WARN","ERROR","off","OFF","_updateLogLevel","_logLevel","_evalLazyOptionalParams","optionalParams","_log","message","log","clearRange","temp","_entries","entries","service","instance","ServiceCollection","_services","serviceDependencies","getServiceDependencies","sort","serviceArgs","dependency","firstServiceArgPos","args","DEFAULT_PROTOCOLS","NONE","restrict","X10","VT200","DRAG","ANY","eventCode","isSGR","S","DEFAULT_ENCODINGS","DEFAULT","SGR","_protocols","_encodings","_activeProtocol","_activeEncoding","_onProtocolChange","_lastEvent","addProtocol","addEncoding","protocol","encoding","_compareEvents","report","DOWN","UP","MOVE","WHEEL","e1","e2","_action","_callbacks","_pendingData","_bufferOffset","cb","_innerWrite","startTime","_addons","loadedAddon","_wrappedAddonDispose","activate"],"mappings":"CAAA,SAA2CA,EAAMC,GAChD,GAAsB,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,SACb,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A4B,CAChCjD,SAAQ,EACRhwD,QAASgwD,EAAShwD,QAClBquD,YAAY,GAEdzuD,KAAKozD,QAAQjzD,KAAKkzD,GAClBjD,EAAShwD,QAAU,WAAM,SAAKkzD,qBAAqBD,IACnDjD,EAASmD,SAAc9Q,IAGjB,YAAA6Q,qBAAR,SAA6BD,GAC3B,IAAIA,EAAY5E,WAAhB,CAKA,IADA,IAAIxtD,GAAS,EACJ9D,EAAI,EAAGA,EAAI6C,KAAKozD,QAAQ/yD,OAAQlD,IACvC,GAAI6C,KAAKozD,QAAQj2D,KAAOk2D,EAAa,CACnCpyD,EAAQ9D,EACR,MAGJ,IAAe,IAAX8D,EACF,MAAM,IAAI2S,MAAM,uDAElBy/C,EAAY5E,YAAa,EACzB4E,EAAYjzD,QAAQomC,MAAM6sB,EAAYjD,UACtCpwD,KAAKozD,QAAQ9yD,OAAOW,EAAO,KAE/B,EA1CA,GAAa,EAAA2jB","file":"xterm.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 32);\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IEvent } from 'common/EventEmitter';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IDecPrivateModes, ICoreMouseEvent, CoreMouseEncoding, ICoreMouseProtocol, CoreMouseEventType } from 'common/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\n\nexport const IBufferService = createDecorator<IBufferService>('BufferService');\nexport interface IBufferService {\n  serviceBrand: any;\n\n  readonly cols: number;\n  readonly rows: number;\n  readonly buffer: IBuffer;\n  readonly buffers: IBufferSet;\n\n  // TODO: Move resize event here\n\n  resize(cols: number, rows: number): void;\n  reset(): void;\n}\n\nexport const ICoreMouseService = createDecorator<ICoreMouseService>('CoreMouseService');\nexport interface ICoreMouseService {\n  activeProtocol: string;\n  activeEncoding: string;\n  addProtocol(name: string, protocol: ICoreMouseProtocol): void;\n  addEncoding(name: string, encoding: CoreMouseEncoding): void;\n  reset(): void;\n\n  /**\n   * Triggers a mouse event to be sent.\n   *\n   * Returns true if the event passed all protocol restrictions and a report\n   * was sent, otherwise false. The return value may be used to decide whether\n   * the default event action in the bowser component should be omitted.\n   *\n   * Note: The method will change values of the given event object\n   * to fullfill protocol and encoding restrictions.\n   */\n  triggerMouseEvent(event: ICoreMouseEvent): boolean;\n\n  /**\n   * Event to announce changes in mouse tracking.\n   */\n  onProtocolChange: IEvent<CoreMouseEventType>;\n\n  /**\n   * Human readable version of mouse events.\n   */\n  explainEvents(events: CoreMouseEventType): {[event: string]: boolean};\n}\n\nexport const ICoreService = createDecorator<ICoreService>('CoreService');\nexport interface ICoreService {\n  serviceBrand: any;\n\n  readonly decPrivateModes: IDecPrivateModes;\n\n  readonly onData: IEvent<string>;\n  readonly onUserInput: IEvent<void>;\n\n  reset(): void;\n\n  /**\n   * Triggers the onData event in the public API.\n   * @param data The data that is being emitted.\n   * @param wasFromUser Whether the data originated from the user (as opposed to\n   * resulting from parsing incoming data). When true this will also:\n   * - Scroll to the bottom of the buffer.s\n   * - Fire the `onUserInput` event (so selection can be cleared).\n    */\n  triggerDataEvent(data: string, wasUserInput?: boolean): void;\n}\n\nexport const IDirtyRowService = createDecorator<IDirtyRowService>('DirtyRowService');\nexport interface IDirtyRowService {\n  serviceBrand: any;\n\n  readonly start: number;\n  readonly end: number;\n\n  clearRange(): void;\n  markDirty(y: number): void;\n  markRangeDirty(y1: number, y2: number): void;\n  markAllDirty(): void;\n}\n\nexport interface IServiceIdentifier<T> {\n  (...args: any[]): void;\n  type: T;\n}\n\nexport interface IConstructorSignature0<T> {\n  new(...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature1<A1, T> {\n  new(first: A1, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature2<A1, A2, T> {\n  new(first: A1, second: A2, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature3<A1, A2, A3, T> {\n  new(first: A1, second: A2, third: A3, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature4<A1, A2, A3, A4, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature5<A1, A2, A3, A4, A5, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport const IInstantiationService = createDecorator<IInstantiationService>('InstantiationService');\nexport interface IInstantiationService {\n  setService<T>(id: IServiceIdentifier<T>, instance: T): void;\n\n  createInstance<T>(ctor: IConstructorSignature0<T>): T;\n  createInstance<A1, T>(ctor: IConstructorSignature1<A1, T>, first: A1): T;\n  createInstance<A1, A2, T>(ctor: IConstructorSignature2<A1, A2, T>, first: A1, second: A2): T;\n  createInstance<A1, A2, A3, T>(ctor: IConstructorSignature3<A1, A2, A3, T>, first: A1, second: A2, third: A3): T;\n  createInstance<A1, A2, A3, A4, T>(ctor: IConstructorSignature4<A1, A2, A3, A4, T>, first: A1, second: A2, third: A3, fourth: A4): T;\n  createInstance<A1, A2, A3, A4, A5, T>(ctor: IConstructorSignature5<A1, A2, A3, A4, A5, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T;\n  createInstance<A1, A2, A3, A4, A5, A6, T>(ctor: IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T;\n  createInstance<A1, A2, A3, A4, A5, A6, A7, T>(ctor: IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T;\n  createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T;\n}\n\nexport const ILogService = createDecorator<ILogService>('LogService');\nexport interface ILogService {\n  serviceBrand: any;\n\n  debug(message: any, ...optionalParams: any[]): void;\n  info(message: any, ...optionalParams: any[]): void;\n  warn(message: any, ...optionalParams: any[]): void;\n  error(message: any, ...optionalParams: any[]): void;\n}\n\nexport const IOptionsService = createDecorator<IOptionsService>('OptionsService');\nexport interface IOptionsService {\n  serviceBrand: any;\n\n  readonly options: ITerminalOptions;\n\n  readonly onOptionChange: IEvent<string>;\n\n  setOption<T>(key: string, value: T): void;\n  getOption<T>(key: string): T | undefined;\n}\n\nexport type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';\nexport type RendererType = 'dom' | 'canvas';\n\nexport interface IPartialTerminalOptions {\n  allowTransparency?: boolean;\n  bellSound?: string;\n  bellStyle?: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;\n  cols?: number;\n  cursorBlink?: boolean;\n  cursorStyle?: 'block' | 'underline' | 'bar';\n  disableStdin?: boolean;\n  drawBoldTextInBrightColors?: boolean;\n  fastScrollModifier?: 'alt' | 'ctrl' | 'shift';\n  fastScrollSensitivity?: number;\n  fontSize?: number;\n  fontFamily?: string;\n  fontWeight?: FontWeight;\n  fontWeightBold?: FontWeight;\n  letterSpacing?: number;\n  lineHeight?: number;\n  logLevel?: LogLevel;\n  macOptionIsMeta?: boolean;\n  macOptionClickForcesSelection?: boolean;\n  rendererType?: RendererType;\n  rightClickSelectsWord?: boolean;\n  rows?: number;\n  screenReaderMode?: boolean;\n  scrollback?: number;\n  scrollSensitivity?: number;\n  tabStopWidth?: number;\n  theme?: ITheme;\n  windowsMode?: boolean;\n  wordSeparator?: string;\n}\n\nexport interface ITerminalOptions {\n  allowTransparency: boolean;\n  bellSound: string;\n  bellStyle: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;\n  cols: number;\n  cursorBlink: boolean;\n  cursorStyle: 'block' | 'underline' | 'bar';\n  disableStdin: boolean;\n  drawBoldTextInBrightColors: boolean;\n  fastScrollModifier: 'alt' | 'ctrl' | 'shift' | undefined;\n  fastScrollSensitivity: number;\n  fontSize: number;\n  fontFamily: string;\n  fontWeight: FontWeight;\n  fontWeightBold: FontWeight;\n  letterSpacing: number;\n  lineHeight: number;\n  logLevel: LogLevel;\n  macOptionIsMeta: boolean;\n  macOptionClickForcesSelection: boolean;\n  rendererType: RendererType;\n  rightClickSelectsWord: boolean;\n  rows: number;\n  screenReaderMode: boolean;\n  scrollback: number;\n  scrollSensitivity: number;\n  tabStopWidth: number;\n  theme: ITheme;\n  windowsMode: boolean;\n  wordSeparator: string;\n\n  [key: string]: any;\n  cancelEvents: boolean;\n  convertEol: boolean;\n  screenKeys: boolean;\n  termName: string;\n  useFlowControl: boolean;\n}\n\nexport interface ITheme {\n  foreground?: string;\n  background?: string;\n  cursor?: string;\n  cursorAccent?: string;\n  selection?: string;\n  black?: string;\n  red?: string;\n  green?: string;\n  yellow?: string;\n  blue?: string;\n  magenta?: string;\n  cyan?: string;\n  white?: string;\n  brightBlack?: string;\n  brightRed?: string;\n  brightGreen?: string;\n  brightYellow?: string;\n  brightBlue?: string;\n  brightMagenta?: string;\n  brightCyan?: string;\n  brightWhite?: string;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\ninterface IListener<T> {\n  (e: T): void;\n}\n\nexport interface IEvent<T> {\n  (listener: (e: T) => any): IDisposable;\n}\n\nexport interface IEventEmitter<T> {\n  event: IEvent<T>;\n  fire(data: T): void;\n}\n\nexport class EventEmitter<T> implements IEventEmitter<T> {\n  private _listeners: IListener<T>[] = [];\n  private _event?: IEvent<T>;\n\n  public get event(): IEvent<T> {\n    if (!this._event) {\n      this._event = (listener: (e: T) => any) => {\n        this._listeners.push(listener);\n        const disposable = {\n          dispose: () => {\n            for (let i = 0; i < this._listeners.length; i++) {\n              if (this._listeners[i] === listener) {\n                this._listeners.splice(i, 1);\n                return;\n              }\n            }\n          }\n        };\n        return disposable;\n      };\n    }\n    return this._event;\n  }\n\n  public fire(data: T): void {\n    const queue: IListener<T>[] = [];\n    for (let i = 0; i < this._listeners.length; i++) {\n      queue.push(this._listeners[i]);\n    }\n    for (let i = 0; i < queue.length; i++) {\n      queue[i].call(undefined, data);\n    }\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\n/**\n * A base class that can be extended to provide convenience methods for managing the lifecycle of an\n * object and its components.\n */\nexport abstract class Disposable implements IDisposable {\n  protected _disposables: IDisposable[] = [];\n  protected _isDisposed: boolean = false;\n\n  constructor() {\n  }\n\n  /**\n   * Disposes the object, triggering the `dispose` method on all registered IDisposables.\n   */\n  public dispose(): void {\n    this._isDisposed = true;\n    this._disposables.forEach(d => d.dispose());\n    this._disposables.length = 0;\n  }\n\n  /**\n   * Registers a disposable object.\n   * @param d The disposable to register.\n   */\n  public register<T extends IDisposable>(d: T): void {\n    this._disposables.push(d);\n  }\n\n  /**\n   * Unregisters a disposable object if it has been registered, if not do\n   * nothing.\n   * @param d The disposable to unregister.\n   */\n  public unregister<T extends IDisposable>(d: T): void {\n    const index = this._disposables.indexOf(d);\n    if (index !== -1) {\n      this._disposables.splice(index, 1);\n    }\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport const DEFAULT_COLOR = 256;\nexport const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0);\n\nexport const CHAR_DATA_ATTR_INDEX = 0;\nexport const CHAR_DATA_CHAR_INDEX = 1;\nexport const CHAR_DATA_WIDTH_INDEX = 2;\nexport const CHAR_DATA_CODE_INDEX = 3;\n\n/**\n * Null cell - a real empty cell (containing nothing).\n * Note that code should always be 0 for a null cell as\n * several test condition of the buffer line rely on this.\n */\nexport const NULL_CELL_CHAR = '';\nexport const NULL_CELL_WIDTH = 1;\nexport const NULL_CELL_CODE = 0;\n\n/**\n * Whitespace cell.\n * This is meant as a replacement for empty cells when needed\n * during rendering lines to preserve correct aligment.\n */\nexport const WHITESPACE_CELL_CHAR = ' ';\nexport const WHITESPACE_CELL_WIDTH = 1;\nexport const WHITESPACE_CELL_CODE = 32;\n\n/**\n * Bitmasks for accessing data in `content`.\n */\nexport const enum Content {\n  /**\n   * bit 1..21    codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken)\n   *              read:   `codepoint = content & Content.codepointMask;`\n   *              write:  `content |= codepoint & Content.codepointMask;`\n   *                      shortcut if precondition `codepoint <= 0x10FFFF` is met:\n   *                      `content |= codepoint;`\n   */\n  CODEPOINT_MASK = 0x1FFFFF,\n\n  /**\n   * bit 22       flag indication whether a cell contains combined content\n   *              read:   `isCombined = content & Content.isCombined;`\n   *              set:    `content |= Content.isCombined;`\n   *              clear:  `content &= ~Content.isCombined;`\n   */\n  IS_COMBINED_MASK = 0x200000,  // 1 << 21\n\n  /**\n   * bit 1..22    mask to check whether a cell contains any string data\n   *              we need to check for codepoint and isCombined bits to see\n   *              whether a cell contains anything\n   *              read:   `isEmpty = !(content & Content.hasContent)`\n   */\n  HAS_CONTENT_MASK = 0x3FFFFF,\n\n  /**\n   * bit 23..24   wcwidth value of cell, takes 2 bits (ranges from 0..2)\n   *              read:   `width = (content & Content.widthMask) >> Content.widthShift;`\n   *                      `hasWidth = content & Content.widthMask;`\n   *                      as long as wcwidth is highest value in `content`:\n   *                      `width = content >> Content.widthShift;`\n   *              write:  `content |= (width << Content.widthShift) & Content.widthMask;`\n   *                      shortcut if precondition `0 <= width <= 3` is met:\n   *                      `content |= width << Content.widthShift;`\n   */\n  WIDTH_MASK = 0xC00000,   // 3 << 22\n  WIDTH_SHIFT = 22\n}\n\nexport const enum Attributes {\n  /**\n   * bit 1..8     blue in RGB, color in P256 and P16\n   */\n  BLUE_MASK = 0xFF,\n  BLUE_SHIFT = 0,\n  PCOLOR_MASK = 0xFF,\n  PCOLOR_SHIFT = 0,\n\n  /**\n   * bit 9..16    green in RGB\n   */\n  GREEN_MASK = 0xFF00,\n  GREEN_SHIFT = 8,\n\n  /**\n   * bit 17..24   red in RGB\n   */\n  RED_MASK = 0xFF0000,\n  RED_SHIFT = 16,\n\n  /**\n   * bit 25..26   color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3)\n   */\n  CM_MASK = 0x3000000,\n  CM_DEFAULT = 0,\n  CM_P16 = 0x1000000,\n  CM_P256 = 0x2000000,\n  CM_RGB = 0x3000000,\n\n  /**\n   * bit 1..24  RGB room\n   */\n  RGB_MASK = 0xFFFFFF\n}\n\nexport const enum FgFlags {\n  /**\n   * bit 27..31 (32th bit unused)\n   */\n  INVERSE = 0x4000000,\n  BOLD = 0x8000000,\n  UNDERLINE = 0x10000000,\n  BLINK = 0x20000000,\n  INVISIBLE = 0x40000000\n}\n\nexport const enum BgFlags {\n  /**\n   * bit 27..32 (upper 4 unused)\n   */\n  ITALIC = 0x4000000,\n  DIM = 0x8000000\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, ICellData } from 'common/Types';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\nimport { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants';\nimport { AttributeData } from 'common/buffer/AttributeData';\n\n/**\n * CellData - represents a single Cell in the terminal buffer.\n */\nexport class CellData extends AttributeData implements ICellData {\n  /** Helper to create CellData from CharData. */\n  public static fromCharData(value: CharData): CellData {\n    const obj = new CellData();\n    obj.setFromCharData(value);\n    return obj;\n  }\n  /** Primitives from terminal buffer. */\n  public content: number = 0;\n  public fg: number = 0;\n  public bg: number = 0;\n  public combinedData: string = '';\n  /** Whether cell contains a combined string. */\n  public isCombined(): number {\n    return this.content & Content.IS_COMBINED_MASK;\n  }\n  /** Width of the cell. */\n  public getWidth(): number {\n    return this.content >> Content.WIDTH_SHIFT;\n  }\n  /** JS string of the content. */\n  public getChars(): string {\n    if (this.content & Content.IS_COMBINED_MASK) {\n      return this.combinedData;\n    }\n    if (this.content & Content.CODEPOINT_MASK) {\n      return stringFromCodePoint(this.content & Content.CODEPOINT_MASK);\n    }\n    return '';\n  }\n  /**\n   * Codepoint of cell\n   * Note this returns the UTF32 codepoint of single chars,\n   * if content is a combined string it returns the codepoint\n   * of the last char in string to be in line with code in CharData.\n   * */\n  public getCode(): number {\n    return (this.isCombined())\n      ? this.combinedData.charCodeAt(this.combinedData.length - 1)\n      : this.content & Content.CODEPOINT_MASK;\n  }\n  /** Set data from CharData */\n  public setFromCharData(value: CharData): void {\n    this.fg = value[CHAR_DATA_ATTR_INDEX];\n    this.bg = 0;\n    let combined = false;\n    // surrogates and combined strings need special treatment\n    if (value[CHAR_DATA_CHAR_INDEX].length > 2) {\n      combined = true;\n    }\n    else if (value[CHAR_DATA_CHAR_INDEX].length === 2) {\n      const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0);\n      // if the 2-char string is a surrogate create single codepoint\n      // everything else is combined\n      if (0xD800 <= code && code <= 0xDBFF) {\n        const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1);\n        if (0xDC00 <= second && second <= 0xDFFF) {\n          this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n        }\n        else {\n          combined = true;\n        }\n      }\n      else {\n        combined = true;\n      }\n    }\n    else {\n      this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    }\n    if (combined) {\n      this.combinedData = value[CHAR_DATA_CHAR_INDEX];\n      this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    }\n  }\n  /** Get data as CharData. */\n  public getAsCharData(): CharData {\n    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IEvent } from 'common/EventEmitter';\nimport { IRenderDimensions, IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { IColorSet } from 'browser/Types';\nimport { ISelectionRedrawRequestEvent } from 'browser/selection/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\nimport { IDisposable } from 'common/Types';\n\nexport const ICharSizeService = createDecorator<ICharSizeService>('CharSizeService');\nexport interface ICharSizeService {\n  serviceBrand: any;\n\n  readonly width: number;\n  readonly height: number;\n  readonly hasValidSize: boolean;\n\n  readonly onCharSizeChange: IEvent<void>;\n\n  measure(): void;\n}\n\nexport const IMouseService = createDecorator<IMouseService>('MouseService');\nexport interface IMouseService {\n  serviceBrand: any;\n\n  getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined;\n  getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined;\n}\n\nexport const IRenderService = createDecorator<IRenderService>('RenderService');\nexport interface IRenderService extends IDisposable {\n  serviceBrand: any;\n\n  onDimensionsChange: IEvent<IRenderDimensions>;\n  onRender: IEvent<{ start: number, end: number }>;\n  onRefreshRequest: IEvent<{ start: number, end: number }>;\n\n  dimensions: IRenderDimensions;\n\n  refreshRows(start: number, end: number): void;\n  resize(cols: number, rows: number): void;\n  changeOptions(): void;\n  setRenderer(renderer: IRenderer): void;\n  setColors(colors: IColorSet): void;\n  onDevicePixelRatioChange(): void;\n  onResize(cols: number, rows: number): void;\n  // TODO: Is this useful when we have onResize?\n  onCharSizeChanged(): void;\n  onBlur(): void;\n  onFocus(): void;\n  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;\n  onCursorMove(): void;\n  clear(): void;\n  registerCharacterJoiner(handler: CharacterJoinerHandler): number;\n  deregisterCharacterJoiner(joinerId: number): boolean;\n}\n\nexport const ISelectionService = createDecorator<ISelectionService>('SelectionService');\nexport interface ISelectionService {\n  serviceBrand: any;\n\n  readonly selectionText: string;\n  readonly hasSelection: boolean;\n  readonly selectionStart: [number, number] | undefined;\n  readonly selectionEnd: [number, number] | undefined;\n\n  readonly onLinuxMouseSelection: IEvent<string>;\n  readonly onRedrawRequest: IEvent<ISelectionRedrawRequestEvent>;\n  readonly onSelectionChange: IEvent<void>;\n\n  disable(): void;\n  enable(): void;\n  reset(): void;\n  setSelection(row: number, col: number, length: number): void;\n  selectAll(): void;\n  selectLines(start: number, end: number): void;\n  clearSelection(): void;\n  isClickInSelection(event: MouseEvent): boolean;\n  selectWordAtCursor(event: MouseEvent): void;\n  shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean;\n  shouldForceSelection(event: MouseEvent): boolean;\n  refresh(isLinuxMouseSelection?: boolean): void;\n  onMouseDown(event: MouseEvent): void;\n}\n\nexport const ISoundService = createDecorator<ISoundService>('SoundService');\nexport interface ISoundService {\n  serviceBrand: any;\n\n  playBellSound(): void;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAttributeData, IColorRGB } from 'common/Types';\nimport { Attributes, FgFlags, BgFlags } from 'common/buffer/Constants';\n\nexport class AttributeData implements IAttributeData {\n  static toColorRGB(value: number): IColorRGB {\n    return [\n      value >>> Attributes.RED_SHIFT & 255,\n      value >>> Attributes.GREEN_SHIFT & 255,\n      value & 255\n    ];\n  }\n  static fromColorRGB(value: IColorRGB): number {\n    return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255;\n  }\n\n  public clone(): IAttributeData {\n    const newObj = new AttributeData();\n    newObj.fg = this.fg;\n    newObj.bg = this.bg;\n    return newObj;\n  }\n\n  // data\n  public fg: number = 0;\n  public bg: number = 0;\n\n  // flags\n  public isInverse(): number   { return this.fg & FgFlags.INVERSE; }\n  public isBold(): number      { return this.fg & FgFlags.BOLD; }\n  public isUnderline(): number { return this.fg & FgFlags.UNDERLINE; }\n  public isBlink(): number     { return this.fg & FgFlags.BLINK; }\n  public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; }\n  public isItalic(): number    { return this.bg & BgFlags.ITALIC; }\n  public isDim(): number       { return this.bg & BgFlags.DIM; }\n\n  // color modes\n  public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; }\n  public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; }\n  public isFgRGB(): boolean       { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n  public isBgRGB(): boolean       { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n  public isFgPalette(): boolean   { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; }\n  public isBgPalette(): boolean   { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; }\n  public isFgDefault(): boolean   { return (this.fg & Attributes.CM_MASK) === 0; }\n  public isBgDefault(): boolean   { return (this.bg & Attributes.CM_MASK) === 0; }\n\n  // colors\n  public getFgColor(): number {\n    switch (this.fg & Attributes.CM_MASK) {\n      case Attributes.CM_P16:\n      case Attributes.CM_P256:  return this.fg & Attributes.PCOLOR_MASK;\n      case Attributes.CM_RGB:   return this.fg & Attributes.RGB_MASK;\n      default:                  return -1;  // CM_DEFAULT defaults to -1\n    }\n  }\n  public getBgColor(): number {\n    switch (this.bg & Attributes.CM_MASK) {\n      case Attributes.CM_P16:\n      case Attributes.CM_P256:  return this.bg & Attributes.PCOLOR_MASK;\n      case Attributes.CM_RGB:   return this.bg & Attributes.RGB_MASK;\n      default:                  return -1;  // CM_DEFAULT defaults to -1\n    }\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\n/**\n * Adds a disposable listener to a node in the DOM, returning the disposable.\n * @param type The event type.\n * @param handler The handler for the listener.\n */\nexport function addDisposableDomListener(\n  node: Element | Window | Document,\n  type: string,\n  handler: (e: any) => void,\n  useCapture?: boolean\n): IDisposable {\n  node.addEventListener(type, handler, useCapture);\n  return {\n    dispose: () => {\n      if (!handler) {\n        // Already disposed\n        return;\n      }\n      node.removeEventListener(type, handler, useCapture);\n    }\n  };\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * Polyfill - Convert UTF32 codepoint into JS string.\n * Note: The built-in String.fromCodePoint happens to be much slower\n *       due to additional sanity checks. We can avoid them since\n *       we always operate on legal UTF32 (granted by the input decoders)\n *       and use this faster version instead.\n */\nexport function stringFromCodePoint(codePoint: number): string {\n  if (codePoint > 0xFFFF) {\n    codePoint -= 0x10000;\n    return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00);\n  }\n  return String.fromCharCode(codePoint);\n}\n\n/**\n * Convert UTF32 char codes into JS string.\n * Basically the same as `stringFromCodePoint` but for multiple codepoints\n * in a loop (which is a lot faster).\n */\nexport function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string {\n  let result = '';\n  for (let i = start; i < end; ++i) {\n    let codepoint = data[i];\n    if (codepoint > 0xFFFF) {\n      // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate pair\n      // conversion rules:\n      //  - subtract 0x10000 from code point, leaving a 20 bit number\n      //  - add high 10 bits to 0xD800  --> first surrogate\n      //  - add low 10 bits to 0xDC00   --> second surrogate\n      codepoint -= 0x10000;\n      result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00);\n    } else {\n      result += String.fromCharCode(codepoint);\n    }\n  }\n  return result;\n}\n\n/**\n * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints.\n * To keep the decoder in line with JS strings it handles single surrogates as UCS2.\n */\nexport class StringToUtf32 {\n  private _interim: number = 0;\n\n  /**\n   * Clears interim and resets decoder to clean state.\n   */\n  public clear(): void {\n    this._interim = 0;\n  }\n\n  /**\n   * Decode JS string to UTF32 codepoints.\n   * The methods assumes stream input and will store partly transmitted\n   * surrogate pairs and decode them with the next data chunk.\n   * Note: The method does no bound checks for target, therefore make sure\n   * the provided input data does not exceed the size of `target`.\n   * Returns the number of written codepoints in `target`.\n   */\n  decode(input: string, target: Uint32Array): number {\n    const length = input.length;\n\n    if (!length) {\n      return 0;\n    }\n\n    let size = 0;\n    let startPos = 0;\n\n    // handle leftover surrogate high\n    if (this._interim) {\n      const second = input.charCodeAt(startPos++);\n      if (0xDC00 <= second && second <= 0xDFFF) {\n        target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n      } else {\n        // illegal codepoint (USC2 handling)\n        target[size++] = this._interim;\n        target[size++] = second;\n      }\n      this._interim = 0;\n    }\n\n    for (let i = startPos; i < length; ++i) {\n      const code = input.charCodeAt(i);\n      // surrogate pair first\n      if (0xD800 <= code && code <= 0xDBFF) {\n        if (++i >= length) {\n          this._interim = code;\n          return size;\n        }\n        const second = input.charCodeAt(i);\n        if (0xDC00 <= second && second <= 0xDFFF) {\n          target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n        } else {\n          // illegal codepoint (USC2 handling)\n          target[size++] = code;\n          target[size++] = second;\n        }\n        continue;\n      }\n      target[size++] = code;\n    }\n    return size;\n  }\n}\n\n/**\n * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints.\n */\nexport class Utf8ToUtf32 {\n  public interim: Uint8Array = new Uint8Array(3);\n\n  /**\n   * Clears interim bytes and resets decoder to clean state.\n   */\n  public clear(): void {\n    this.interim.fill(0);\n  }\n\n  /**\n   * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`.\n   * The methods assumes stream input and will store partly transmitted bytes\n   * and decode them with the next data chunk.\n   * Note: The method does no bound checks for target, therefore make sure\n   * the provided data chunk does not exceed the size of `target`.\n   * Returns the number of written codepoints in `target`.\n   */\n  decode(input: Uint8Array, target: Uint32Array): number {\n    const length = input.length;\n\n    if (!length) {\n      return 0;\n    }\n\n    let size = 0;\n    let byte1: number;\n    let byte2: number;\n    let byte3: number;\n    let byte4: number;\n    let codepoint = 0;\n    let startPos = 0;\n\n    // handle leftover bytes\n    if (this.interim[0]) {\n      let discardInterim = false;\n      let cp = this.interim[0];\n      cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07);\n      let pos = 0;\n      let tmp: number;\n      while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) {\n        cp <<= 6;\n        cp |= tmp;\n      }\n      // missing bytes - read ahead from input\n      const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4;\n      const missing = type - pos;\n      while (startPos < missing) {\n        if (startPos >= length) {\n          return 0;\n        }\n        tmp = input[startPos++];\n        if ((tmp & 0xC0) !== 0x80) {\n          // wrong continuation, discard interim bytes completely\n          startPos--;\n          discardInterim = true;\n          break;\n        } else {\n          // need to save so we can continue short inputs in next call\n          this.interim[pos++] = tmp;\n          cp <<= 6;\n          cp |= tmp & 0x3F;\n        }\n      }\n      if (!discardInterim) {\n        // final test is type dependent\n        if (type === 2) {\n          if (cp < 0x80) {\n            // wrong starter byte\n            startPos--;\n          } else {\n            target[size++] = cp;\n          }\n        } else if (type === 3) {\n          if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF)) {\n            // illegal codepoint\n          } else {\n            target[size++] = cp;\n          }\n        } else {\n          if (cp < 0x010000 || cp > 0x10FFFF) {\n            // illegal codepoint\n          } else {\n            target[size++] = cp;\n          }\n        }\n      }\n      this.interim.fill(0);\n    }\n\n    // loop through input\n    const fourStop = length - 4;\n    let i = startPos;\n    while (i < length) {\n      /**\n       * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars.\n       * This is a compromise between speed gain for ASCII\n       * and penalty for non ASCII:\n       * For best ASCII performance the char should be stored directly into target,\n       * but even a single attempt to write to target and compare afterwards\n       * penalizes non ASCII really bad (-50%), thus we load the char into byteX first,\n       * which reduces ASCII performance by ~15%.\n       * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible\n       * compared to the gains.\n       * Note that this optimization only takes place for 4 consecutive ASCII chars,\n       * for any shorter it bails out. Worst case - all 4 bytes being read but\n       * thrown away due to the last being a non ASCII char (-10% performance).\n       */\n      while (i < fourStop\n        && !((byte1 = input[i]) & 0x80)\n        && !((byte2 = input[i + 1]) & 0x80)\n        && !((byte3 = input[i + 2]) & 0x80)\n        && !((byte4 = input[i + 3]) & 0x80))\n      {\n        target[size++] = byte1;\n        target[size++] = byte2;\n        target[size++] = byte3;\n        target[size++] = byte4;\n        i += 4;\n      }\n\n      // reread byte1\n      byte1 = input[i++];\n\n      // 1 byte\n      if (byte1 < 0x80) {\n        target[size++] = byte1;\n\n        // 2 bytes\n      } else if ((byte1 & 0xE0) === 0xC0) {\n        if (i >= length) {\n          this.interim[0] = byte1;\n          return size;\n        }\n        byte2 = input[i++];\n        if ((byte2 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F);\n        if (codepoint < 0x80) {\n          // wrong starter byte\n          i--;\n          continue;\n        }\n        target[size++] = codepoint;\n\n        // 3 bytes\n      } else if ((byte1 & 0xF0) === 0xE0) {\n        if (i >= length) {\n          this.interim[0] = byte1;\n          return size;\n        }\n        byte2 = input[i++];\n        if ((byte2 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        if (i >= length) {\n          this.interim[0] = byte1;\n          this.interim[1] = byte2;\n          return size;\n        }\n        byte3 = input[i++];\n        if ((byte3 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F);\n        if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {\n          // illegal codepoint, no i-- here\n          continue;\n        }\n        target[size++] = codepoint;\n\n        // 4 bytes\n      } else if ((byte1 & 0xF8) === 0xF0) {\n        if (i >= length) {\n          this.interim[0] = byte1;\n          return size;\n        }\n        byte2 = input[i++];\n        if ((byte2 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        if (i >= length) {\n          this.interim[0] = byte1;\n          this.interim[1] = byte2;\n          return size;\n        }\n        byte3 = input[i++];\n        if ((byte3 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        if (i >= length) {\n          this.interim[0] = byte1;\n          this.interim[1] = byte2;\n          this.interim[2] = byte3;\n          return size;\n        }\n        byte4 = input[i++];\n        if ((byte4 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F);\n        if (codepoint < 0x010000 || codepoint > 0x10FFFF) {\n          // illegal codepoint, no i-- here\n          continue;\n        }\n        target[size++] = codepoint;\n      } else {\n        // illegal byte, just skip\n      }\n    }\n    return size;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport const INVERTED_DEFAULT_COLOR = 257;\nexport const DIM_OPACITY = 0.5;\n\nexport const CHAR_ATLAS_CELL_SPACING = 1;\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ninterface INavigator {\n  userAgent: string;\n  language: string;\n  platform: string;\n}\n\n// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but\n// we want this module to live in common.\ndeclare const navigator: INavigator;\n\nconst isNode = (typeof navigator === 'undefined') ? true : false;\nconst userAgent = (isNode) ? 'node' : navigator.userAgent;\nconst platform = (isNode) ? 'node' : navigator.platform;\n\nexport const isFirefox = !!~userAgent.indexOf('Firefox');\nexport const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent);\n\n// Find the users platform. We use this to interpret the meta key\n// and ISO third level shifts.\n// http://stackoverflow.com/q/19877924/577598\nexport const isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform);\nexport const isIpad = platform === 'iPad';\nexport const isIphone = platform === 'iPhone';\nexport const isWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform);\nexport const isLinux = platform.indexOf('Linux') >= 0;\n\n/**\n * Return if the given array contains the given element\n * @param arr The array to search for the given element.\n * @param el The element to look for into the array\n */\nfunction contains(arr: any[], el: any): boolean {\n  return arr.indexOf(el) >= 0;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * C0 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C0 {\n  /** Null (Caret = ^@, C = \\0) */\n  export const NUL = '\\x00';\n  /** Start of Heading (Caret = ^A) */\n  export const SOH = '\\x01';\n  /** Start of Text (Caret = ^B) */\n  export const STX = '\\x02';\n  /** End of Text (Caret = ^C) */\n  export const ETX = '\\x03';\n  /** End of Transmission (Caret = ^D) */\n  export const EOT = '\\x04';\n  /** Enquiry (Caret = ^E) */\n  export const ENQ = '\\x05';\n  /** Acknowledge (Caret = ^F) */\n  export const ACK = '\\x06';\n  /** Bell (Caret = ^G, C = \\a) */\n  export const BEL = '\\x07';\n  /** Backspace (Caret = ^H, C = \\b) */\n  export const BS  = '\\x08';\n  /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \\t) */\n  export const HT  = '\\x09';\n  /** Line Feed (Caret = ^J, C = \\n) */\n  export const LF  = '\\x0a';\n  /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \\v) */\n  export const VT  = '\\x0b';\n  /** Form Feed (Caret = ^L, C = \\f) */\n  export const FF  = '\\x0c';\n  /** Carriage Return (Caret = ^M, C = \\r) */\n  export const CR  = '\\x0d';\n  /** Shift Out (Caret = ^N) */\n  export const SO  = '\\x0e';\n  /** Shift In (Caret = ^O) */\n  export const SI  = '\\x0f';\n  /** Data Link Escape (Caret = ^P) */\n  export const DLE = '\\x10';\n  /** Device Control One (XON) (Caret = ^Q) */\n  export const DC1 = '\\x11';\n  /** Device Control Two (Caret = ^R) */\n  export const DC2 = '\\x12';\n  /** Device Control Three (XOFF) (Caret = ^S) */\n  export const DC3 = '\\x13';\n  /** Device Control Four (Caret = ^T) */\n  export const DC4 = '\\x14';\n  /** Negative Acknowledge (Caret = ^U) */\n  export const NAK = '\\x15';\n  /** Synchronous Idle (Caret = ^V) */\n  export const SYN = '\\x16';\n  /** End of Transmission Block (Caret = ^W) */\n  export const ETB = '\\x17';\n  /** Cancel (Caret = ^X) */\n  export const CAN = '\\x18';\n  /** End of Medium (Caret = ^Y) */\n  export const EM  = '\\x19';\n  /** Substitute (Caret = ^Z) */\n  export const SUB = '\\x1a';\n  /** Escape (Caret = ^[, C = \\e) */\n  export const ESC = '\\x1b';\n  /** File Separator (Caret = ^\\) */\n  export const FS  = '\\x1c';\n  /** Group Separator (Caret = ^]) */\n  export const GS  = '\\x1d';\n  /** Record Separator (Caret = ^^) */\n  export const RS  = '\\x1e';\n  /** Unit Separator (Caret = ^_) */\n  export const US  = '\\x1f';\n  /** Space */\n  export const SP  = '\\x20';\n  /** Delete (Caret = ^?) */\n  export const DEL = '\\x7f';\n}\n\n/**\n * C1 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C1 {\n  /** padding character */\n  export const PAD = '\\x80';\n  /** High Octet Preset */\n  export const HOP = '\\x81';\n  /** Break Permitted Here */\n  export const BPH = '\\x82';\n  /** No Break Here */\n  export const NBH = '\\x83';\n  /** Index */\n  export const IND = '\\x84';\n  /** Next Line */\n  export const NEL = '\\x85';\n  /** Start of Selected Area */\n  export const SSA = '\\x86';\n  /** End of Selected Area */\n  export const ESA = '\\x87';\n  /** Horizontal Tabulation Set */\n  export const HTS = '\\x88';\n  /** Horizontal Tabulation With Justification */\n  export const HTJ = '\\x89';\n  /** Vertical Tabulation Set */\n  export const VTS = '\\x8a';\n  /** Partial Line Down */\n  export const PLD = '\\x8b';\n  /** Partial Line Up */\n  export const PLU = '\\x8c';\n  /** Reverse Index */\n  export const RI = '\\x8d';\n  /** Single-Shift 2 */\n  export const SS2 = '\\x8e';\n  /** Single-Shift 3 */\n  export const SS3 = '\\x8f';\n  /** Device Control String */\n  export const DCS = '\\x90';\n  /** Private Use 1 */\n  export const PU1 = '\\x91';\n  /** Private Use 2 */\n  export const PU2 = '\\x92';\n  /** Set Transmit State */\n  export const STS = '\\x93';\n  /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */\n  export const CCH = '\\x94';\n  /** Message Waiting */\n  export const MW = '\\x95';\n  /** Start of Protected Area */\n  export const SPA = '\\x96';\n  /** End of Protected Area */\n  export const EPA = '\\x97';\n  /** Start of String */\n  export const SOS = '\\x98';\n  /** Single Graphic Character Introducer */\n  export const SGCI = '\\x99';\n  /** Single Character Introducer */\n  export const SCI = '\\x9a';\n  /** Control Sequence Introducer */\n  export const CSI = '\\x9b';\n  /** String Terminator */\n  export const ST = '\\x9c';\n  /** Operating System Command */\n  export const OSC = '\\x9d';\n  /** Privacy Message */\n  export const PM = '\\x9e';\n  /** Application Program Command */\n  export const APC = '\\x9f';\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions, IRenderLayer } from 'browser/renderer/Types';\nimport { ICellData } from 'common/Types';\nimport { DEFAULT_COLOR, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';\nimport { IGlyphIdentifier } from 'browser/renderer/atlas/Types';\nimport { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';\nimport { acquireCharAtlas } from 'browser/renderer/atlas/CharAtlasCache';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { IColorSet } from 'browser/Types';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { throwIfFalsy } from 'browser/renderer/RendererUtils';\n\nexport abstract class BaseRenderLayer implements IRenderLayer {\n  private _canvas: HTMLCanvasElement;\n  protected _ctx!: CanvasRenderingContext2D;\n  private _scaledCharWidth: number = 0;\n  private _scaledCharHeight: number = 0;\n  private _scaledCellWidth: number = 0;\n  private _scaledCellHeight: number = 0;\n  private _scaledCharLeft: number = 0;\n  private _scaledCharTop: number = 0;\n\n  protected _charAtlas: BaseCharAtlas | undefined;\n\n  /**\n   * An object that's reused when drawing glyphs in order to reduce GC.\n   */\n  private _currentGlyphIdentifier: IGlyphIdentifier = {\n    chars: '',\n    code: 0,\n    bg: 0,\n    fg: 0,\n    bold: false,\n    dim: false,\n    italic: false\n  };\n\n  constructor(\n    private _container: HTMLElement,\n    id: string,\n    zIndex: number,\n    private _alpha: boolean,\n    protected _colors: IColorSet,\n    private _rendererId: number,\n    protected readonly _bufferService: IBufferService,\n    protected readonly _optionsService: IOptionsService\n  ) {\n    this._canvas = document.createElement('canvas');\n    this._canvas.classList.add(`xterm-${id}-layer`);\n    this._canvas.style.zIndex = zIndex.toString();\n    this._initCanvas();\n    this._container.appendChild(this._canvas);\n  }\n\n  public dispose(): void {\n    this._container.removeChild(this._canvas);\n    if (this._charAtlas) {\n      this._charAtlas.dispose();\n    }\n  }\n\n  private _initCanvas(): void {\n    this._ctx = throwIfFalsy(this._canvas.getContext('2d', {alpha: this._alpha}));\n    // Draw the background if this is an opaque layer\n    if (!this._alpha) {\n      this._clearAll();\n    }\n  }\n\n  public onOptionsChanged(): void {}\n  public onBlur(): void {}\n  public onFocus(): void {}\n  public onCursorMove(): void {}\n  public onGridChanged(startRow: number, endRow: number): void {}\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {}\n\n  public setColors(colorSet: IColorSet): void {\n    this._refreshCharAtlas(colorSet);\n  }\n\n  protected _setTransparency(alpha: boolean): void {\n    // Do nothing when alpha doesn't change\n    if (alpha === this._alpha) {\n      return;\n    }\n\n    // Create new canvas and replace old one\n    const oldCanvas = this._canvas;\n    this._alpha = alpha;\n    // Cloning preserves properties\n    this._canvas = <HTMLCanvasElement>this._canvas.cloneNode();\n    this._initCanvas();\n    this._container.replaceChild(this._canvas, oldCanvas);\n\n    // Regenerate char atlas and force a full redraw\n    this._refreshCharAtlas(this._colors);\n    this.onGridChanged(0, this._bufferService.rows - 1);\n  }\n\n  /**\n   * Refreshes the char atlas, aquiring a new one if necessary.\n   * @param colorSet The color set to use for the char atlas.\n   */\n  private _refreshCharAtlas(colorSet: IColorSet): void {\n    if (this._scaledCharWidth <= 0 && this._scaledCharHeight <= 0) {\n      return;\n    }\n    this._charAtlas = acquireCharAtlas(this._optionsService.options, this._rendererId, colorSet, this._scaledCharWidth, this._scaledCharHeight);\n    this._charAtlas.warmUp();\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    this._scaledCellWidth = dim.scaledCellWidth;\n    this._scaledCellHeight = dim.scaledCellHeight;\n    this._scaledCharWidth = dim.scaledCharWidth;\n    this._scaledCharHeight = dim.scaledCharHeight;\n    this._scaledCharLeft = dim.scaledCharLeft;\n    this._scaledCharTop = dim.scaledCharTop;\n    this._canvas.width = dim.scaledCanvasWidth;\n    this._canvas.height = dim.scaledCanvasHeight;\n    this._canvas.style.width = `${dim.canvasWidth}px`;\n    this._canvas.style.height = `${dim.canvasHeight}px`;\n\n    // Draw the background if this is an opaque layer\n    if (!this._alpha) {\n      this._clearAll();\n    }\n\n    this._refreshCharAtlas(this._colors);\n  }\n\n  public abstract reset(): void;\n\n  /**\n   * Fills 1+ cells completely. This uses the existing fillStyle on the context.\n   * @param x The column to start at.\n   * @param y The row to start at\n   * @param width The number of columns to fill.\n   * @param height The number of rows to fill.\n   */\n  protected _fillCells(x: number, y: number, width: number, height: number): void {\n    this._ctx.fillRect(\n        x * this._scaledCellWidth,\n        y * this._scaledCellHeight,\n        width * this._scaledCellWidth,\n        height * this._scaledCellHeight);\n  }\n\n  /**\n   * Fills a 1px line (2px on HDPI) at the bottom of the cell. This uses the\n   * existing fillStyle on the context.\n   * @param x The column to fill.\n   * @param y The row to fill.\n   */\n  protected _fillBottomLineAtCells(x: number, y: number, width: number = 1): void {\n    this._ctx.fillRect(\n        x * this._scaledCellWidth,\n        (y + 1) * this._scaledCellHeight - window.devicePixelRatio - 1 /* Ensure it's drawn within the cell */,\n        width * this._scaledCellWidth,\n        window.devicePixelRatio);\n  }\n\n  /**\n   * Fills a 1px line (2px on HDPI) at the left of the cell. This uses the\n   * existing fillStyle on the context.\n   * @param x The column to fill.\n   * @param y The row to fill.\n   */\n  protected _fillLeftLineAtCell(x: number, y: number): void {\n    this._ctx.fillRect(\n        x * this._scaledCellWidth,\n        y * this._scaledCellHeight,\n        window.devicePixelRatio,\n        this._scaledCellHeight);\n  }\n\n  /**\n   * Strokes a 1px rectangle (2px on HDPI) around a cell. This uses the existing\n   * strokeStyle on the context.\n   * @param x The column to fill.\n   * @param y The row to fill.\n   */\n  protected _strokeRectAtCell(x: number, y: number, width: number, height: number): void {\n    this._ctx.lineWidth = window.devicePixelRatio;\n    this._ctx.strokeRect(\n        x * this._scaledCellWidth + window.devicePixelRatio / 2,\n        y * this._scaledCellHeight + (window.devicePixelRatio / 2),\n        width * this._scaledCellWidth - window.devicePixelRatio,\n        (height * this._scaledCellHeight) - window.devicePixelRatio);\n  }\n\n  /**\n   * Clears the entire canvas.\n   */\n  protected _clearAll(): void {\n    if (this._alpha) {\n      this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);\n    } else {\n      this._ctx.fillStyle = this._colors.background.css;\n      this._ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);\n    }\n  }\n\n  /**\n   * Clears 1+ cells completely.\n   * @param x The column to start at.\n   * @param y The row to start at.\n   * @param width The number of columns to clear.\n   * @param height The number of rows to clear.\n   */\n  protected _clearCells(x: number, y: number, width: number, height: number): void {\n    if (this._alpha) {\n      this._ctx.clearRect(\n          x * this._scaledCellWidth,\n          y * this._scaledCellHeight,\n          width * this._scaledCellWidth,\n          height * this._scaledCellHeight);\n    } else {\n      this._ctx.fillStyle = this._colors.background.css;\n      this._ctx.fillRect(\n          x * this._scaledCellWidth,\n          y * this._scaledCellHeight,\n          width * this._scaledCellWidth,\n          height * this._scaledCellHeight);\n    }\n  }\n\n  /**\n   * Draws a truecolor character at the cell. The character will be clipped to\n   * ensure that it fits with the cell, including the cell to the right if it's\n   * a wide character. This uses the existing fillStyle on the context.\n   * @param cell The cell data for the character to draw.\n   * @param x The column to draw at.\n   * @param y The row to draw at.\n   * @param color The color of the character.\n   */\n  protected _fillCharTrueColor(cell: CellData, x: number, y: number): void {\n    this._ctx.font = this._getFont(false, false);\n    this._ctx.textBaseline = 'middle';\n    this._clipRow(y);\n    this._ctx.fillText(\n        cell.getChars(),\n        x * this._scaledCellWidth + this._scaledCharLeft,\n        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);\n  }\n\n  /**\n   * Draws one or more characters at a cell. If possible this will draw using\n   * the character atlas to reduce draw time.\n   * @param chars The character or characters.\n   * @param code The character code.\n   * @param width The width of the characters.\n   * @param x The column to draw at.\n   * @param y The row to draw at.\n   * @param fg The foreground color, in the format stored within the attributes.\n   * @param bg The background color, in the format stored within the attributes.\n   * This is used to validate whether a cached image can be used.\n   * @param bold Whether the text is bold.\n   */\n  protected _drawChars(cell: ICellData, x: number, y: number): void {\n\n    // skip cache right away if we draw in RGB\n    // Note: to avoid bad runtime JoinedCellData will be skipped\n    //       in the cache handler itself (atlasDidDraw == false) and\n    //       fall through to uncached later down below\n    if (cell.isFgRGB() || cell.isBgRGB()) {\n      this._drawUncachedChars(cell, x, y);\n      return;\n    }\n\n    let fg;\n    let bg;\n    if (cell.isInverse()) {\n      fg = (cell.isBgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getBgColor();\n      bg = (cell.isFgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getFgColor();\n    } else {\n      bg = (cell.isBgDefault()) ? DEFAULT_COLOR : cell.getBgColor();\n      fg = (cell.isFgDefault()) ? DEFAULT_COLOR : cell.getFgColor();\n    }\n\n    const drawInBrightColor = this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8 && fg !== INVERTED_DEFAULT_COLOR;\n\n    fg += drawInBrightColor ? 8 : 0;\n    this._currentGlyphIdentifier.chars = cell.getChars() || WHITESPACE_CELL_CHAR;\n    this._currentGlyphIdentifier.code = cell.getCode() || WHITESPACE_CELL_CODE;\n    this._currentGlyphIdentifier.bg = bg;\n    this._currentGlyphIdentifier.fg = fg;\n    this._currentGlyphIdentifier.bold = !!cell.isBold();\n    this._currentGlyphIdentifier.dim = !!cell.isDim();\n    this._currentGlyphIdentifier.italic = !!cell.isItalic();\n    const atlasDidDraw = this._charAtlas && this._charAtlas.draw(\n      this._ctx,\n      this._currentGlyphIdentifier,\n      x * this._scaledCellWidth + this._scaledCharLeft,\n      y * this._scaledCellHeight + this._scaledCharTop\n    );\n\n    if (!atlasDidDraw) {\n      this._drawUncachedChars(cell, x, y);\n    }\n  }\n\n  /**\n   * Draws one or more characters at one or more cells. The character(s) will be\n   * clipped to ensure that they fit with the cell(s), including the cell to the\n   * right if the last character is a wide character.\n   * @param chars The character.\n   * @param width The width of the character.\n   * @param fg The foreground color, in the format stored within the attributes.\n   * @param x The column to draw at.\n   * @param y The row to draw at.\n   */\n  private _drawUncachedChars(cell: ICellData, x: number, y: number): void {\n    this._ctx.save();\n    this._ctx.font = this._getFont(!!cell.isBold(), !!cell.isItalic());\n    this._ctx.textBaseline = 'middle';\n\n    if (cell.isInverse()) {\n      if (cell.isBgDefault()) {\n        this._ctx.fillStyle = this._colors.background.css;\n      } else if (cell.isBgRGB()) {\n        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;\n      } else {\n        this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;\n      }\n    } else {\n      if (cell.isFgDefault()) {\n        this._ctx.fillStyle = this._colors.foreground.css;\n      } else if (cell.isFgRGB()) {\n        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;\n      } else {\n        let fg = cell.getFgColor();\n        if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {\n          fg += 8;\n        }\n        this._ctx.fillStyle = this._colors.ansi[fg].css;\n      }\n    }\n\n    this._clipRow(y);\n\n    // Apply alpha to dim the character\n    if (cell.isDim()) {\n      this._ctx.globalAlpha = DIM_OPACITY;\n    }\n    // Draw the character\n    this._ctx.fillText(\n        cell.getChars(),\n        x * this._scaledCellWidth + this._scaledCharLeft,\n        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);\n    this._ctx.restore();\n  }\n\n  /**\n   * Clips a row to ensure no pixels will be drawn outside the cells in the row.\n   * @param y The row to clip.\n   */\n  private _clipRow(y: number): void {\n    this._ctx.beginPath();\n    this._ctx.rect(\n        0,\n        y * this._scaledCellHeight,\n        this._bufferService.cols * this._scaledCellWidth,\n        this._scaledCellHeight);\n    this._ctx.clip();\n  }\n\n  /**\n   * Gets the current font.\n   * @param isBold If we should use the bold fontWeight.\n   */\n  protected _getFont(isBold: boolean, isItalic: boolean): string {\n    const fontWeight = isBold ? this._optionsService.options.fontWeightBold : this._optionsService.options.fontWeight;\n    const fontStyle = isItalic ? 'italic' : '';\n\n    return `${fontStyle} ${fontWeight} ${this._optionsService.options.fontSize * window.devicePixelRatio}px ${this._optionsService.options.fontFamily}`;\n  }\n}\n\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IServiceIdentifier } from 'common/services/Services';\n\nconst DI_TARGET = 'di$target';\nconst DI_DEPENDENCIES = 'di$dependencies';\n\nexport const serviceRegistry: Map<string, IServiceIdentifier<any>> = new Map();\n\nexport function getServiceDependencies(ctor: any): { id: IServiceIdentifier<any>, index: number, optional: boolean }[] {\n  return ctor[DI_DEPENDENCIES] || [];\n}\n\nexport function createDecorator<T>(id: string): IServiceIdentifier<T> {\n  if (serviceRegistry.has(id)) {\n    return serviceRegistry.get(id)!;\n  }\n\n  const decorator = <any>function (target: Function, key: string, index: number): any {\n    if (arguments.length !== 3) {\n      throw new Error('@IServiceName-decorator can only be used to decorate a parameter');\n    }\n\n    storeServiceDependency(decorator, target, index);\n  };\n\n  decorator.toString = () => id;\n\n  serviceRegistry.set(id, decorator);\n  return decorator;\n}\n\nfunction storeServiceDependency(id: Function, target: Function, index: number): void {\n  if ((target as any)[DI_TARGET] === target) {\n    (target as any)[DI_DEPENDENCIES].push({ id, index });\n  } else {\n    (target as any)[DI_DEPENDENCIES] = [{ id, index }];\n    (target as any)[DI_TARGET] = target;\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport type TypedArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray\n  | Int8Array | Int16Array | Int32Array\n  | Float32Array | Float64Array;\n\n\n/**\n * polyfill for TypedArray.fill\n * This is needed to support .fill in all safari versions and IE 11.\n */\nexport function fill<T extends TypedArray>(array: T, value: number, start?: number, end?: number): T {\n  // all modern engines that support .fill\n  if (array.fill) {\n    return array.fill(value, start, end) as T;\n  }\n  return fillFallback(array, value, start, end);\n}\n\nexport function fillFallback<T extends TypedArray>(array: T, value: number, start: number = 0, end: number = array.length): T {\n  // safari and IE 11\n  // since IE 11 does not support Array.prototype.fill either\n  // we cannot use the suggested polyfill from MDN\n  // instead we simply fall back to looping\n  if (start >= array.length) {\n    return array;\n  }\n  start = (array.length + start) % array.length;\n  if (end >= array.length) {\n    end = array.length;\n  } else {\n    end = (array.length + end) % array.length;\n  }\n  for (let i = start; i < end; ++i) {\n    array[i] = value;\n  }\n  return array;\n}\n\n/**\n * Concat two typed arrays `a` and `b`.\n * Returns a new typed array.\n */\nexport function concat<T extends TypedArray>(a: T, b: T): T {\n  const result = new (a.constructor as any)(a.length + b.length);\n  result.set(a);\n  result.set(b, a.length);\n  return result;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, IBufferLine, ICellData } from 'common/Types';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\nimport { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { AttributeData } from 'common/buffer/AttributeData';\n\n/**\n * buffer memory layout:\n *\n *   |             uint32_t             |        uint32_t         |        uint32_t         |\n *   |             `content`            |          `FG`           |          `BG`           |\n *   | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) |\n */\n\n\n/** typed array slots taken by one cell */\nconst CELL_SIZE = 3;\n\n/**\n * Cell member indices.\n *\n * Direct access:\n *    `content = data[column * CELL_SIZE + Cell.CONTENT];`\n *    `fg = data[column * CELL_SIZE + Cell.FG];`\n *    `bg = data[column * CELL_SIZE + Cell.BG];`\n */\nconst enum Cell {\n  CONTENT = 0,\n  FG = 1, // currently simply holds all known attrs\n  BG = 2  // currently unused\n}\n\nexport const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData());\n\n/**\n * Typed array based bufferline implementation.\n *\n * There are 2 ways to insert data into the cell buffer:\n * - `setCellFromCodepoint` + `addCodepointToCell`\n *   Use these for data that is already UTF32.\n *   Used during normal input in `InputHandler` for faster buffer access.\n * - `setCell`\n *   This method takes a CellData object and stores the data in the buffer.\n *   Use `CellData.fromCharData` to create the CellData object (e.g. from JS string).\n *\n * To retrieve data from the buffer use either one of the primitive methods\n * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop\n * memory allocs / GC pressure can be greatly reduced by reusing the CellData object.\n */\nexport class BufferLine implements IBufferLine {\n  protected _data: Uint32Array;\n  protected _combined: {[index: number]: string} = {};\n  public length: number;\n\n  constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) {\n    this._data = new Uint32Array(cols * CELL_SIZE);\n    const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n    for (let i = 0; i < cols; ++i) {\n      this.setCell(i, cell);\n    }\n    this.length = cols;\n  }\n\n  /**\n   * Get cell data CharData.\n   * @deprecated\n   */\n  public get(index: number): CharData {\n    const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    const cp = content & Content.CODEPOINT_MASK;\n    return [\n      this._data[index * CELL_SIZE + Cell.FG],\n      (content & Content.IS_COMBINED_MASK)\n        ? this._combined[index]\n        : (cp) ? stringFromCodePoint(cp) : '',\n      content >> Content.WIDTH_SHIFT,\n      (content & Content.IS_COMBINED_MASK)\n        ? this._combined[index].charCodeAt(this._combined[index].length - 1)\n        : cp\n    ];\n  }\n\n  /**\n   * Set cell data from CharData.\n   * @deprecated\n   */\n  public set(index: number, value: CharData): void {\n    this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX];\n    if (value[CHAR_DATA_CHAR_INDEX].length > 1) {\n      this._combined[index] = value[1];\n      this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    } else {\n      this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    }\n  }\n\n  /**\n   * primitive getters\n   * use these when only one value is needed, otherwise use `loadCell`\n   */\n  public getWidth(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT;\n  }\n\n  /** Test whether content has width. */\n  public hasWidth(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK;\n  }\n\n  /** Get FG cell component. */\n  public getFg(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.FG];\n  }\n\n  /** Get BG cell component. */\n  public getBg(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.BG];\n  }\n\n  /**\n   * Test whether contains any chars.\n   * Basically an empty has no content, but other cells might differ in FG/BG\n   * from real empty cells.\n   * */\n  public hasContent(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK;\n  }\n\n  /**\n   * Get codepoint of the cell.\n   * To be in line with `code` in CharData this either returns\n   * a single UTF32 codepoint or the last codepoint of a combined string.\n   */\n  public getCodePoint(index: number): number {\n    const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    if (content & Content.IS_COMBINED_MASK) {\n      return this._combined[index].charCodeAt(this._combined[index].length - 1);\n    }\n    return content & Content.CODEPOINT_MASK;\n  }\n\n  /** Test whether the cell contains a combined string. */\n  public isCombined(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK;\n  }\n\n  /** Returns the string content of the cell. */\n  public getString(index: number): string {\n    const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    if (content & Content.IS_COMBINED_MASK) {\n      return this._combined[index];\n    }\n    if (content & Content.CODEPOINT_MASK) {\n      return stringFromCodePoint(content & Content.CODEPOINT_MASK);\n    }\n    // return empty string for empty cells\n    return '';\n  }\n\n  /**\n   * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly\n   * to GC as it significantly reduced the amount of new objects/references needed.\n   */\n  public loadCell(index: number, cell: ICellData): ICellData {\n    const startIndex = index * CELL_SIZE;\n    cell.content = this._data[startIndex + Cell.CONTENT];\n    cell.fg = this._data[startIndex + Cell.FG];\n    cell.bg = this._data[startIndex + Cell.BG];\n    if (cell.content & Content.IS_COMBINED_MASK) {\n      cell.combinedData = this._combined[index];\n    }\n    return cell;\n  }\n\n  /**\n   * Set data at `index` to `cell`.\n   */\n  public setCell(index: number, cell: ICellData): void {\n    if (cell.content & Content.IS_COMBINED_MASK) {\n      this._combined[index] = cell.combinedData;\n    }\n    this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content;\n    this._data[index * CELL_SIZE + Cell.FG] = cell.fg;\n    this._data[index * CELL_SIZE + Cell.BG] = cell.bg;\n  }\n\n  /**\n   * Set cell data from input handler.\n   * Since the input handler see the incoming chars as UTF32 codepoints,\n   * it gets an optimized access method.\n   */\n  public setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number): void {\n    this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT);\n    this._data[index * CELL_SIZE + Cell.FG] = fg;\n    this._data[index * CELL_SIZE + Cell.BG] = bg;\n  }\n\n  /**\n   * Add a codepoint to a cell from input handler.\n   * During input stage combining chars with a width of 0 follow and stack\n   * onto a leading char. Since we already set the attrs\n   * by the previous `setDataFromCodePoint` call, we can omit it here.\n   */\n  public addCodepointToCell(index: number, codePoint: number): void {\n    let content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    if (content & Content.IS_COMBINED_MASK) {\n      // we already have a combined string, simply add\n      this._combined[index] += stringFromCodePoint(codePoint);\n    } else {\n      if (content & Content.CODEPOINT_MASK) {\n        // normal case for combining chars:\n        //  - move current leading char + new one into combined string\n        //  - set combined flag\n        this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint);\n        content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0\n        content |= Content.IS_COMBINED_MASK;\n      } else {\n        // should not happen - we actually have no data in the cell yet\n        // simply set the data in the cell buffer with a width of 1\n        content = codePoint | (1 << Content.WIDTH_SHIFT);\n      }\n      this._data[index * CELL_SIZE + Cell.CONTENT] = content;\n    }\n  }\n\n  public insertCells(pos: number, n: number, fillCellData: ICellData): void {\n    pos %= this.length;\n    if (n < this.length - pos) {\n      const cell = new CellData();\n      for (let i = this.length - pos - n - 1; i >= 0; --i) {\n        this.setCell(pos + n + i, this.loadCell(pos + i, cell));\n      }\n      for (let i = 0; i < n; ++i) {\n        this.setCell(pos + i, fillCellData);\n      }\n    } else {\n      for (let i = pos; i < this.length; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    }\n  }\n\n  public deleteCells(pos: number, n: number, fillCellData: ICellData): void {\n    pos %= this.length;\n    if (n < this.length - pos) {\n      const cell = new CellData();\n      for (let i = 0; i < this.length - pos - n; ++i) {\n        this.setCell(pos + i, this.loadCell(pos + n + i, cell));\n      }\n      for (let i = this.length - n; i < this.length; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    } else {\n      for (let i = pos; i < this.length; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    }\n  }\n\n  public replaceCells(start: number, end: number, fillCellData: ICellData): void {\n    while (start < end  && start < this.length) {\n      this.setCell(start++, fillCellData);\n    }\n  }\n\n  public resize(cols: number, fillCellData: ICellData): void {\n    if (cols === this.length) {\n      return;\n    }\n    if (cols > this.length) {\n      const data = new Uint32Array(cols * CELL_SIZE);\n      if (this.length) {\n        if (cols * CELL_SIZE < this._data.length) {\n          data.set(this._data.subarray(0, cols * CELL_SIZE));\n        } else {\n          data.set(this._data);\n        }\n      }\n      this._data = data;\n      for (let i = this.length; i < cols; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    } else {\n      if (cols) {\n        const data = new Uint32Array(cols * CELL_SIZE);\n        data.set(this._data.subarray(0, cols * CELL_SIZE));\n        this._data = data;\n        // Remove any cut off combined data\n        const keys = Object.keys(this._combined);\n        for (let i = 0; i < keys.length; i++) {\n          const key = parseInt(keys[i], 10);\n          if (key >= cols) {\n            delete this._combined[key];\n          }\n        }\n      } else {\n        this._data = new Uint32Array(0);\n        this._combined = {};\n      }\n    }\n    this.length = cols;\n  }\n\n  /** fill a line with fillCharData */\n  public fill(fillCellData: ICellData): void {\n    this._combined = {};\n    for (let i = 0; i < this.length; ++i) {\n      this.setCell(i, fillCellData);\n    }\n  }\n\n  /** alter to a full copy of line  */\n  public copyFrom(line: BufferLine): void {\n    if (this.length !== line.length) {\n      this._data = new Uint32Array(line._data);\n    } else {\n      // use high speed copy if lengths are equal\n      this._data.set(line._data);\n    }\n    this.length = line.length;\n    this._combined = {};\n    for (const el in line._combined) {\n      this._combined[el] = line._combined[el];\n    }\n    this.isWrapped = line.isWrapped;\n  }\n\n  /** create a new clone */\n  public clone(): IBufferLine {\n    const newLine = new BufferLine(0);\n    newLine._data = new Uint32Array(this._data);\n    newLine.length = this.length;\n    for (const el in this._combined) {\n      newLine._combined[el] = this._combined[el];\n    }\n    newLine.isWrapped = this.isWrapped;\n    return newLine;\n  }\n\n  public getTrimmedLength(): number {\n    for (let i = this.length - 1; i >= 0; --i) {\n      if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) {\n        return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);\n      }\n    }\n    return 0;\n  }\n\n  public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void {\n    const srcData = src._data;\n    if (applyInReverse) {\n      for (let cell = length - 1; cell >= 0; cell--) {\n        for (let i = 0; i < CELL_SIZE; i++) {\n          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n        }\n      }\n    } else {\n      for (let cell = 0; cell < length; cell++) {\n        for (let i = 0; i < CELL_SIZE; i++) {\n          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n        }\n      }\n    }\n\n    // Move any combined data over as needed\n    const srcCombinedKeys = Object.keys(src._combined);\n    for (let i = 0; i < srcCombinedKeys.length; i++) {\n      const key = parseInt(srcCombinedKeys[i], 10);\n      if (key >= srcCol) {\n        this._combined[key - srcCol + destCol] = src._combined[key];\n      }\n    }\n  }\n\n  public translateToString(trimRight: boolean = false, startCol: number = 0, endCol: number = this.length): string {\n    if (trimRight) {\n      endCol = Math.min(endCol, this.getTrimmedLength());\n    }\n    let result = '';\n    while (startCol < endCol) {\n      const content = this._data[startCol * CELL_SIZE + Cell.CONTENT];\n      const cp = content & Content.CODEPOINT_MASK;\n      result += (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR;\n      startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by 1\n    }\n    return result;\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport let promptLabel = 'Terminal input';\nexport let tooMuchOutput = 'Too much output to announce, navigate to rows manually to read';\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharset } from 'common/Types';\n\n/**\n * The character sets supported by the terminal. These enable several languages\n * to be represented within the terminal with only 8-bit encoding. See ISO 2022\n * for a discussion on character sets. Only VT100 character sets are supported.\n */\nexport const CHARSETS: { [key: string]: ICharset | null } = {};\n\n/**\n * The default character set, US.\n */\nexport const DEFAULT_CHARSET: ICharset | null = CHARSETS['B'];\n\n/**\n * DEC Special Character and Line Drawing Set.\n * Reference: http://vt100.net/docs/vt102-ug/table5-13.html\n * A lot of curses apps use this if they see TERM=xterm.\n * testing: echo -e '\\e(0a\\e(B'\n * The xterm output sometimes seems to conflict with the\n * reference above. xterm seems in line with the reference\n * when running vttest however.\n * The table below now uses xterm's output from vttest.\n */\nCHARSETS['0'] = {\n  '`': '\\u25c6', // '◆'\n  'a': '\\u2592', // '▒'\n  'b': '\\u0009', // '\\t'\n  'c': '\\u000c', // '\\f'\n  'd': '\\u000d', // '\\r'\n  'e': '\\u000a', // '\\n'\n  'f': '\\u00b0', // '°'\n  'g': '\\u00b1', // '±'\n  'h': '\\u2424', // '\\u2424' (NL)\n  'i': '\\u000b', // '\\v'\n  'j': '\\u2518', // '┘'\n  'k': '\\u2510', // '┐'\n  'l': '\\u250c', // '┌'\n  'm': '\\u2514', // '└'\n  'n': '\\u253c', // '┼'\n  'o': '\\u23ba', // '⎺'\n  'p': '\\u23bb', // '⎻'\n  'q': '\\u2500', // '─'\n  'r': '\\u23bc', // '⎼'\n  's': '\\u23bd', // '⎽'\n  't': '\\u251c', // '├'\n  'u': '\\u2524', // '┤'\n  'v': '\\u2534', // '┴'\n  'w': '\\u252c', // '┬'\n  'x': '\\u2502', // '│'\n  'y': '\\u2264', // '≤'\n  'z': '\\u2265', // '≥'\n  '{': '\\u03c0', // 'π'\n  '|': '\\u2260', // '≠'\n  '}': '\\u00a3', // '£'\n  '~': '\\u00b7'  // '·'\n};\n\n/**\n * British character set\n * ESC (A\n * Reference: http://vt100.net/docs/vt220-rm/table2-5.html\n */\nCHARSETS['A'] = {\n  '#': '£'\n};\n\n/**\n * United States character set\n * ESC (B\n */\nCHARSETS['B'] = null;\n\n/**\n * Dutch character set\n * ESC (4\n * Reference: http://vt100.net/docs/vt220-rm/table2-6.html\n */\nCHARSETS['4'] = {\n  '#': '£',\n  '@': '¾',\n  '[': 'ij',\n  '\\\\': '½',\n  ']': '|',\n  '{': '¨',\n  '|': 'f',\n  '}': '¼',\n  '~': '´'\n};\n\n/**\n * Finnish character set\n * ESC (C or ESC (5\n * Reference: http://vt100.net/docs/vt220-rm/table2-7.html\n */\nCHARSETS['C'] =\nCHARSETS['5'] = {\n  '[': 'Ä',\n  '\\\\': 'Ö',\n  ']': 'Å',\n  '^': 'Ü',\n  '`': 'é',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'å',\n  '~': 'ü'\n};\n\n/**\n * French character set\n * ESC (R\n * Reference: http://vt100.net/docs/vt220-rm/table2-8.html\n */\nCHARSETS['R'] = {\n  '#': '£',\n  '@': 'à',\n  '[': '°',\n  '\\\\': 'ç',\n  ']': '§',\n  '{': 'é',\n  '|': 'ù',\n  '}': 'è',\n  '~': '¨'\n};\n\n/**\n * French Canadian character set\n * ESC (Q\n * Reference: http://vt100.net/docs/vt220-rm/table2-9.html\n */\nCHARSETS['Q'] = {\n  '@': 'à',\n  '[': 'â',\n  '\\\\': 'ç',\n  ']': 'ê',\n  '^': 'î',\n  '`': 'ô',\n  '{': 'é',\n  '|': 'ù',\n  '}': 'è',\n  '~': 'û'\n};\n\n/**\n * German character set\n * ESC (K\n * Reference: http://vt100.net/docs/vt220-rm/table2-10.html\n */\nCHARSETS['K'] = {\n  '@': '§',\n  '[': 'Ä',\n  '\\\\': 'Ö',\n  ']': 'Ü',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'ü',\n  '~': 'ß'\n};\n\n/**\n * Italian character set\n * ESC (Y\n * Reference: http://vt100.net/docs/vt220-rm/table2-11.html\n */\nCHARSETS['Y'] = {\n  '#': '£',\n  '@': '§',\n  '[': '°',\n  '\\\\': 'ç',\n  ']': 'é',\n  '`': 'ù',\n  '{': 'à',\n  '|': 'ò',\n  '}': 'è',\n  '~': 'ì'\n};\n\n/**\n * Norwegian/Danish character set\n * ESC (E or ESC (6\n * Reference: http://vt100.net/docs/vt220-rm/table2-12.html\n */\nCHARSETS['E'] =\nCHARSETS['6'] = {\n  '@': 'Ä',\n  '[': 'Æ',\n  '\\\\': 'Ø',\n  ']': 'Å',\n  '^': 'Ü',\n  '`': 'ä',\n  '{': 'æ',\n  '|': 'ø',\n  '}': 'å',\n  '~': 'ü'\n};\n\n/**\n * Spanish character set\n * ESC (Z\n * Reference: http://vt100.net/docs/vt220-rm/table2-13.html\n */\nCHARSETS['Z'] = {\n  '#': '£',\n  '@': '§',\n  '[': '¡',\n  '\\\\': 'Ñ',\n  ']': '¿',\n  '{': '°',\n  '|': 'ñ',\n  '}': 'ç'\n};\n\n/**\n * Swedish character set\n * ESC (H or ESC (7\n * Reference: http://vt100.net/docs/vt220-rm/table2-14.html\n */\nCHARSETS['H'] =\nCHARSETS['7'] = {\n  '@': 'É',\n  '[': 'Ä',\n  '\\\\': 'Ö',\n  ']': 'Å',\n  '^': 'Ü',\n  '`': 'é',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'å',\n  '~': 'ü'\n};\n\n/**\n * Swiss character set\n * ESC (=\n * Reference: http://vt100.net/docs/vt220-rm/table2-15.html\n */\nCHARSETS['='] = {\n  '#': 'ù',\n  '@': 'à',\n  '[': 'é',\n  '\\\\': 'ç',\n  ']': 'ê',\n  '^': 'î',\n  '_': 'è',\n  '`': 'ô',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'ü',\n  '~': 'û'\n};\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { fill } from 'common/TypedArrayUtils';\n\nexport const wcwidth = (function(opts: {nul: number, control: number}): (ucs: number) => number {\n  // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c\n  // combining characters\n  const COMBINING_BMP = [\n    [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],\n    [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],\n    [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],\n    [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],\n    [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],\n    [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],\n    [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],\n    [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],\n    [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],\n    [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],\n    [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],\n    [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],\n    [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],\n    [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],\n    [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],\n    [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],\n    [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],\n    [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],\n    [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],\n    [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],\n    [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],\n    [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],\n    [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],\n    [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],\n    [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],\n    [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],\n    [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],\n    [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],\n    [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],\n    [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],\n    [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],\n    [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],\n    [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],\n    [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],\n    [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],\n    [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],\n    [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],\n    [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],\n    [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],\n    [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],\n    [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],\n    [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],\n    [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB]\n  ];\n  const COMBINING_HIGH = [\n    [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],\n    [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],\n    [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],\n    [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],\n    [0xE0100, 0xE01EF]\n  ];\n  // binary search\n  function bisearch(ucs: number, data: number[][]): boolean {\n    let min = 0;\n    let max = data.length - 1;\n    let mid;\n    if (ucs < data[0][0] || ucs > data[max][1]) {\n      return false;\n    }\n    while (max >= min) {\n      mid = (min + max) >> 1;\n      if (ucs > data[mid][1]) {\n        min = mid + 1;\n      } else if (ucs < data[mid][0]) {\n        max = mid - 1;\n      } else {\n        return true;\n      }\n    }\n    return false;\n  }\n  function wcwidthHigh(ucs: number): 0 | 1 | 2 {\n    if (bisearch(ucs, COMBINING_HIGH)) {\n      return 0;\n    }\n    if ((ucs >= 0x20000 && ucs <= 0x2fffd) || (ucs >= 0x30000 && ucs <= 0x3fffd)) {\n      return 2;\n    }\n    return 1;\n  }\n  const control = opts.control | 0;\n\n  // create lookup table for BMP plane\n  const table = new Uint8Array(65536);\n  fill(table, 1);\n  table[0] = opts.nul;\n  // control chars\n  fill(table, opts.control, 1, 32);\n  fill(table, opts.control, 0x7f, 0xa0);\n\n  // apply wide char rules first\n  // wide chars\n  fill(table, 2, 0x1100, 0x1160);\n  table[0x2329] = 2;\n  table[0x232a] = 2;\n  fill(table, 2, 0x2e80, 0xa4d0);\n  table[0x303f] = 1;  // wrongly in last line\n\n  fill(table, 2, 0xac00, 0xd7a4);\n  fill(table, 2, 0xf900, 0xfb00);\n  fill(table, 2, 0xfe10, 0xfe1a);\n  fill(table, 2, 0xfe30, 0xfe70);\n  fill(table, 2, 0xff00, 0xff61);\n  fill(table, 2, 0xffe0, 0xffe7);\n\n  // apply combining last to ensure we overwrite\n  // wrongly wide set chars:\n  //    the original algo evals combining first and falls\n  //    through to wide check so we simply do here the opposite\n  // combining 0\n  for (let r = 0; r < COMBINING_BMP.length; ++r) {\n    fill(table, 0, COMBINING_BMP[r][0], COMBINING_BMP[r][1] + 1);\n  }\n\n  return function (num: number): number {\n    if (num < 32) {\n      return control | 0;\n    }\n    if (num < 127) {\n      return 1;\n    }\n    if (num < 65536) {\n      return table[num];\n    }\n    // do a full search for high codepoints\n    return wcwidthHigh(num);\n  };\n})({nul: 0, control: 0});  // configurable options\n\n/**\n * Get the terminal cell width for a string.\n */\nexport function getStringCellWidth(s: string): number {\n  let result = 0;\n  const length = s.length;\n  for (let i = 0; i < length; ++i) {\n    let code = s.charCodeAt(i);\n    // surrogate pair first\n    if (0xD800 <= code && code <= 0xDBFF) {\n      if (++i >= length) {\n        // this should not happen with strings retrieved from\n        // Buffer.translateToString as it converts from UTF-32\n        // and therefore always should contain the second part\n        // for any other string we still have to handle it somehow:\n        // simply treat the lonely surrogate first as a single char (UCS-2 behavior)\n        return result + wcwidth(code);\n      }\n      const second = s.charCodeAt(i);\n      // convert surrogate pair to high codepoint only for valid second part (UTF-16)\n      // otherwise treat them independently (UCS-2 behavior)\n      if (0xDC00 <= second && second <= 0xDFFF) {\n        code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n      } else {\n        result += wcwidth(second);\n      }\n    }\n    result += wcwidth(code);\n  }\n  return result;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IParams, ParamsArray } from 'common/parser/Types';\n\n// max value supported for a single param/subparam (clamped to positive int32 range)\nconst MAX_VALUE = 0x7FFFFFFF;\n// max allowed subparams for a single sequence (hardcoded limitation)\nconst MAX_SUBPARAMS = 256;\n\n/**\n * Params storage class.\n * This type is used by the parser to accumulate sequence parameters and sub parameters\n * and transmit them to the input handler actions.\n *\n * NOTES:\n *  - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy\n *  - never read beyond `params.length - 1` (likely to contain arbitrary data)\n *  - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params\n *  - hardcoded limitations:\n *    - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that)\n *    - max. 256 sub params possible\n *    - negative values are not allowed beside -1 (placeholder for default value)\n *\n * About ZDM (Zero Default Mode):\n * ZDM is not orchestrated by this class. If the parser is in ZDM,\n * it should add 0 for empty params, otherwise -1. This does not apply\n * to subparams, empty subparams should always be added with -1.\n */\nexport class Params implements IParams {\n  // params store and length\n  public params: Int32Array;\n  public length: number;\n\n  // sub params store and length\n  protected _subParams: Int32Array;\n  protected _subParamsLength: number;\n\n  // sub params offsets from param: param idx --> [start, end] offset\n  private _subParamsIdx: Uint16Array;\n  private _rejectDigits: boolean;\n  private _rejectSubDigits: boolean;\n  private _digitIsSub: boolean;\n\n  /**\n   * Create a `Params` type from JS array representation.\n   */\n  public static fromArray(values: ParamsArray): Params {\n    const params = new Params();\n    if (!values.length) {\n      return params;\n    }\n    // skip leading sub params\n    for (let i = (values[0] instanceof Array) ? 1 : 0; i < values.length; ++i) {\n      const value = values[i];\n      if (value instanceof Array) {\n        for (let k = 0; k < value.length; ++k) {\n          params.addSubParam(value[k]);\n        }\n      } else {\n        params.addParam(value);\n      }\n    }\n    return params;\n  }\n\n  /**\n   * @param maxLength max length of storable parameters\n   * @param maxSubParamsLength max length of storable sub parameters\n   */\n  constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) {\n    if (maxSubParamsLength > MAX_SUBPARAMS) {\n      throw new Error('maxSubParamsLength must not be greater than 256');\n    }\n    this.params = new Int32Array(maxLength);\n    this.length = 0;\n    this._subParams = new Int32Array(maxSubParamsLength);\n    this._subParamsLength = 0;\n    this._subParamsIdx = new Uint16Array(maxLength);\n    this._rejectDigits = false;\n    this._rejectSubDigits = false;\n    this._digitIsSub = false;\n  }\n\n  /**\n   * Clone object.\n   */\n  public clone(): Params {\n    const newParams = new Params(this.maxLength, this.maxSubParamsLength);\n    newParams.params.set(this.params);\n    newParams.length = this.length;\n    newParams._subParams.set(this._subParams);\n    newParams._subParamsLength = this._subParamsLength;\n    newParams._subParamsIdx.set(this._subParamsIdx);\n    newParams._rejectDigits = this._rejectDigits;\n    newParams._rejectSubDigits = this._rejectSubDigits;\n    newParams._digitIsSub = this._digitIsSub;\n    return newParams;\n  }\n\n  /**\n   * Get a JS array representation of the current parameters and sub parameters.\n   * The array is structured as follows:\n   *    sequence: \"1;2:3:4;5::6\"\n   *    array   : [1, 2, [3, 4], 5, [-1, 6]]\n   */\n  public toArray(): ParamsArray {\n    const res: ParamsArray = [];\n    for (let i = 0; i < this.length; ++i) {\n      res.push(this.params[i]);\n      const start = this._subParamsIdx[i] >> 8;\n      const end = this._subParamsIdx[i] & 0xFF;\n      if (end - start > 0) {\n        res.push(Array.prototype.slice.call(this._subParams, start, end));\n      }\n    }\n    return res;\n  }\n\n  /**\n   * Reset to initial empty state.\n   */\n  public reset(): void {\n    this.length = 0;\n    this._subParamsLength = 0;\n    this._rejectDigits = false;\n    this._rejectSubDigits = false;\n    this._digitIsSub = false;\n  }\n\n  /**\n   * Add a parameter value.\n   * `Params` only stores up to `maxLength` parameters, any later\n   * parameter will be ignored.\n   * Note: VT devices only stored up to 16 values, xterm seems to\n   * store up to 30.\n   */\n  public addParam(value: number): void {\n    this._digitIsSub = false;\n    if (this.length >= this.maxLength) {\n      this._rejectDigits = true;\n      return;\n    }\n    if (value < -1) {\n      throw new Error('values lesser than -1 are not allowed');\n    }\n    this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength;\n    this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value;\n  }\n\n  /**\n   * Add a sub parameter value.\n   * The sub parameter is automatically associated with the last parameter value.\n   * Thus it is not possible to add a subparameter without any parameter added yet.\n   * `Params` only stores up to `subParamsLength` sub parameters, any later\n   * sub parameter will be ignored.\n   */\n  public addSubParam(value: number): void {\n    this._digitIsSub = true;\n    if (!this.length) {\n      return;\n    }\n    if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) {\n      this._rejectSubDigits = true;\n      return;\n    }\n    if (value < -1) {\n      throw new Error('values lesser than -1 are not allowed');\n    }\n    this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value;\n    this._subParamsIdx[this.length - 1]++;\n  }\n\n  /**\n   * Whether parameter at index `idx` has sub parameters.\n   */\n  public hasSubParams(idx: number): boolean {\n    return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0);\n  }\n\n  /**\n   * Return sub parameters for parameter at index `idx`.\n   * Note: The values are borrowed, thus you need to copy\n   * the values if you need to hold them in nonlocal scope.\n   */\n  public getSubParams(idx: number): Int32Array | null {\n    const start = this._subParamsIdx[idx] >> 8;\n    const end = this._subParamsIdx[idx] & 0xFF;\n    if (end - start > 0) {\n      return this._subParams.subarray(start, end);\n    }\n    return null;\n  }\n\n  /**\n   * Return all sub parameters as {idx: subparams} mapping.\n   * Note: The values are not borrowed.\n   */\n  public getSubParamsAll(): {[idx: number]: Int32Array} {\n    const result: {[idx: number]: Int32Array} = {};\n    for (let i = 0; i < this.length; ++i) {\n      const start = this._subParamsIdx[i] >> 8;\n      const end = this._subParamsIdx[i] & 0xFF;\n      if (end - start > 0) {\n        result[i] = this._subParams.slice(start, end);\n      }\n    }\n    return result;\n  }\n\n  /**\n   * Add a single digit value to current parameter.\n   * This is used by the parser to account digits on a char by char basis.\n   */\n  public addDigit(value: number): void {\n    let length;\n    if (this._rejectDigits\n      || !(length = this._digitIsSub ? this._subParamsLength : this.length)\n      || (this._digitIsSub && this._rejectSubDigits)\n    ) {\n      return;\n    }\n\n    const store = this._digitIsSub ? this._subParams : this.params;\n    const cur = store[length - 1];\n    store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value;\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser } from 'common/parser/Types';\nimport { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { IDisposable } from 'common/Types';\n\n\nexport class OscParser implements IOscParser {\n  private _state = OscState.START;\n  private _id = -1;\n  private _handlers: IHandlerCollection<IOscHandler> = Object.create(null);\n  private _handlerFb: OscFallbackHandlerType = () => { };\n\n  public addHandler(ident: number, handler: IOscHandler): IDisposable {\n    if (this._handlers[ident] === undefined) {\n      this._handlers[ident] = [];\n    }\n    const handlerList = this._handlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n  public setHandler(ident: number, handler: IOscHandler): void {\n    this._handlers[ident] = [handler];\n  }\n  public clearHandler(ident: number): void {\n    if (this._handlers[ident]) delete this._handlers[ident];\n  }\n  public setHandlerFallback(handler: OscFallbackHandlerType): void {\n    this._handlerFb = handler;\n  }\n\n  public dispose(): void {\n    this._handlers = Object.create(null);\n    this._handlerFb = () => {};\n  }\n\n  public reset(): void {\n    // cleanup handlers if payload was already sent\n    if (this._state === OscState.PAYLOAD) {\n      this.end(false);\n    }\n    this._id = -1;\n    this._state = OscState.START;\n  }\n\n  private _start(): void {\n    const handlers = this._handlers[this._id];\n    if (!handlers) {\n      this._handlerFb(this._id, 'START');\n    } else {\n      for (let j = handlers.length - 1; j >= 0; j--) {\n        handlers[j].start();\n      }\n    }\n  }\n\n  private _put(data: Uint32Array, start: number, end: number): void {\n    const handlers = this._handlers[this._id];\n    if (!handlers) {\n      this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end));\n    } else {\n      for (let j = handlers.length - 1; j >= 0; j--) {\n        handlers[j].put(data, start, end);\n      }\n    }\n  }\n\n  private _end(success: boolean): void {\n    // other than the old code we always have to call .end\n    // to keep the bubbling we use `success` to indicate\n    // whether a handler should execute\n    const handlers = this._handlers[this._id];\n    if (!handlers) {\n      this._handlerFb(this._id, 'END', success);\n    } else {\n      let j = handlers.length - 1;\n      for (; j >= 0; j--) {\n        if (handlers[j].end(success) !== false) {\n          break;\n        }\n      }\n      j--;\n      // cleanup left over handlers\n      for (; j >= 0; j--) {\n        handlers[j].end(false);\n      }\n    }\n  }\n\n  public start(): void {\n    // always reset leftover handlers\n    this.reset();\n    this._id = -1;\n    this._state = OscState.ID;\n  }\n\n  /**\n   * Put data to current OSC command.\n   * Expects the identifier of the OSC command in the form\n   * OSC id ; payload ST/BEL\n   * Payload chunks are not further processed and get\n   * directly passed to the handlers.\n   */\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (this._state === OscState.ABORT) {\n      return;\n    }\n    if (this._state === OscState.ID) {\n      while (start < end) {\n        const code = data[start++];\n        if (code === 0x3b) {\n          this._state = OscState.PAYLOAD;\n          this._start();\n          break;\n        }\n        if (code < 0x30 || 0x39 < code) {\n          this._state = OscState.ABORT;\n          return;\n        }\n        if (this._id === -1) {\n          this._id = 0;\n        }\n        this._id = this._id * 10 + code - 48;\n      }\n    }\n    if (this._state === OscState.PAYLOAD && end - start > 0) {\n      this._put(data, start, end);\n    }\n  }\n\n  /**\n   * Indicates end of an OSC command.\n   * Whether the OSC got aborted or finished normally\n   * is indicated by `success`.\n   */\n  public end(success: boolean): void {\n    if (this._state === OscState.START) {\n      return;\n    }\n    // do nothing if command was faulty\n    if (this._state !== OscState.ABORT) {\n      // if we are still in ID state and get an early end\n      // means that the command has no payload thus we still have\n      // to announce START and send END right after\n      if (this._state === OscState.ID) {\n        this._start();\n      }\n      this._end(success);\n    }\n    this._id = -1;\n    this._state = OscState.START;\n  }\n}\n\n/**\n * Convenient class to allow attaching string based handler functions\n * as OSC handlers.\n */\nexport class OscHandler implements IOscHandler {\n  private _data = '';\n  private _hitLimit: boolean = false;\n\n  constructor(private _handler: (data: string) => any) {}\n\n  public start(): void {\n    this._data = '';\n    this._hitLimit = false;\n  }\n\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (this._hitLimit) {\n      return;\n    }\n    this._data += utf32ToString(data, start, end);\n    if (this._data.length > PAYLOAD_LIMIT) {\n      this._data = '';\n      this._hitLimit = true;\n    }\n  }\n\n  public end(success: boolean): any {\n    let ret;\n    if (this._hitLimit) {\n      ret = false;\n    } else if (success) {\n      ret = this._handler(this._data);\n    }\n    this._data = '';\n    this._hitLimit = false;\n    return ret;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * Internal states of EscapeSequenceParser.\n */\nexport const enum ParserState {\n  GROUND = 0,\n  ESCAPE = 1,\n  ESCAPE_INTERMEDIATE = 2,\n  CSI_ENTRY = 3,\n  CSI_PARAM = 4,\n  CSI_INTERMEDIATE = 5,\n  CSI_IGNORE = 6,\n  SOS_PM_APC_STRING = 7,\n  OSC_STRING = 8,\n  DCS_ENTRY = 9,\n  DCS_PARAM = 10,\n  DCS_IGNORE = 11,\n  DCS_INTERMEDIATE = 12,\n  DCS_PASSTHROUGH = 13\n}\n\n/**\n* Internal actions of EscapeSequenceParser.\n*/\nexport const enum ParserAction {\n  IGNORE = 0,\n  ERROR = 1,\n  PRINT = 2,\n  EXECUTE = 3,\n  OSC_START = 4,\n  OSC_PUT = 5,\n  OSC_END = 6,\n  CSI_DISPATCH = 7,\n  PARAM = 8,\n  COLLECT = 9,\n  ESC_DISPATCH = 10,\n  CLEAR = 11,\n  DCS_HOOK = 12,\n  DCS_PUT = 13,\n  DCS_UNHOOK = 14\n}\n\n/**\n * Internal states of OscParser.\n */\nexport const enum OscState {\n  START = 0,\n  ID = 1,\n  PAYLOAD = 2,\n  ABORT = 3\n}\n\n// payload limit for OSC and DCS\nexport const PAYLOAD_LIMIT = 10000000;\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\nimport { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType } from 'common/parser/Types';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { Params } from 'common/parser/Params';\nimport { PAYLOAD_LIMIT } from 'common/parser/Constants';\n\nconst EMPTY_HANDLERS: IDcsHandler[] = [];\n\nexport class DcsParser implements IDcsParser {\n  private _handlers: IHandlerCollection<IDcsHandler> = Object.create(null);\n  private _active: IDcsHandler[] = EMPTY_HANDLERS;\n  private _ident: number = 0;\n  private _handlerFb: DcsFallbackHandlerType = () => {};\n\n  public dispose(): void {\n    this._handlers = Object.create(null);\n    this._handlerFb = () => {};\n  }\n\n  public addHandler(ident: number, handler: IDcsHandler): IDisposable {\n    if (this._handlers[ident] === undefined) {\n      this._handlers[ident] = [];\n    }\n    const handlerList = this._handlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n\n  public setHandler(ident: number, handler: IDcsHandler): void {\n    this._handlers[ident] = [handler];\n  }\n\n  public clearHandler(ident: number): void {\n    if (this._handlers[ident]) delete this._handlers[ident];\n  }\n\n  public setHandlerFallback(handler: DcsFallbackHandlerType): void {\n    this._handlerFb = handler;\n  }\n\n  public reset(): void {\n    if (this._active.length) {\n      this.unhook(false);\n    }\n    this._active = EMPTY_HANDLERS;\n    this._ident = 0;\n  }\n\n  public hook(ident: number, params: IParams): void {\n    // always reset leftover handlers\n    this.reset();\n    this._ident = ident;\n    this._active = this._handlers[ident] || EMPTY_HANDLERS;\n    if (!this._active.length) {\n      this._handlerFb(this._ident, 'HOOK', params);\n    } else {\n      for (let j = this._active.length - 1; j >= 0; j--) {\n        this._active[j].hook(params);\n      }\n    }\n  }\n\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (!this._active.length) {\n      this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end));\n    } else {\n      for (let j = this._active.length - 1; j >= 0; j--) {\n        this._active[j].put(data, start, end);\n      }\n    }\n  }\n\n  public unhook(success: boolean): void {\n    if (!this._active.length) {\n      this._handlerFb(this._ident, 'UNHOOK', success);\n    } else {\n      let j = this._active.length - 1;\n      for (; j >= 0; j--) {\n        if (this._active[j].unhook(success) !== false) {\n          break;\n        }\n      }\n      j--;\n      // cleanup left over handlers\n      for (; j >= 0; j--) {\n        this._active[j].unhook(false);\n      }\n    }\n    this._active = EMPTY_HANDLERS;\n    this._ident = 0;\n  }\n}\n\n/**\n * Convenient class to create a DCS handler from a single callback function.\n * Note: The payload is currently limited to 50 MB (hardcoded).\n */\nexport class DcsHandler implements IDcsHandler {\n  private _data = '';\n  private _params: IParams | undefined;\n  private _hitLimit: boolean = false;\n\n  constructor(private _handler: (data: string, params: IParams) => any) {}\n\n  public hook(params: IParams): void {\n    this._params = params.clone();\n    this._data = '';\n    this._hitLimit = false;\n  }\n\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (this._hitLimit) {\n      return;\n    }\n    this._data += utf32ToString(data, start, end);\n    if (this._data.length > PAYLOAD_LIMIT) {\n      this._data = '';\n      this._hitLimit = true;\n    }\n  }\n\n  public unhook(success: boolean): any {\n    let ret;\n    if (this._hitLimit) {\n      ret = false;\n    } else if (success) {\n      ret = this._handler(this._data, this._params ? this._params : new Params());\n    }\n    this._params = undefined;\n    this._data = '';\n    this._hitLimit = false;\n    return ret;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { generateConfig, configEquals } from 'browser/renderer/atlas/CharAtlasUtils';\nimport { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';\nimport { DynamicCharAtlas } from 'browser/renderer/atlas/DynamicCharAtlas';\nimport { ICharAtlasConfig } from 'browser/renderer/atlas/Types';\nimport { IColorSet } from 'browser/Types';\nimport { ITerminalOptions } from 'common/services/Services';\n\ninterface ICharAtlasCacheEntry {\n  atlas: BaseCharAtlas;\n  config: ICharAtlasConfig;\n  // N.B. This implementation potentially holds onto copies of the terminal forever, so\n  // this may cause memory leaks.\n  ownedBy: number[];\n}\n\nconst charAtlasCache: ICharAtlasCacheEntry[] = [];\n\n/**\n * Acquires a char atlas, either generating a new one or returning an existing\n * one that is in use by another terminal.\n */\nexport function acquireCharAtlas(\n  options: ITerminalOptions,\n  rendererId: number,\n  colors: IColorSet,\n  scaledCharWidth: number,\n  scaledCharHeight: number\n): BaseCharAtlas {\n  const newConfig = generateConfig(scaledCharWidth, scaledCharHeight, options, colors);\n\n  // Check to see if the renderer already owns this config\n  for (let i = 0; i < charAtlasCache.length; i++) {\n    const entry = charAtlasCache[i];\n    const ownedByIndex = entry.ownedBy.indexOf(rendererId);\n    if (ownedByIndex >= 0) {\n      if (configEquals(entry.config, newConfig)) {\n        return entry.atlas;\n      }\n      // The configs differ, release the renderer from the entry\n      if (entry.ownedBy.length === 1) {\n        entry.atlas.dispose();\n        charAtlasCache.splice(i, 1);\n      } else {\n        entry.ownedBy.splice(ownedByIndex, 1);\n      }\n      break;\n    }\n  }\n\n  // Try match a char atlas from the cache\n  for (let i = 0; i < charAtlasCache.length; i++) {\n    const entry = charAtlasCache[i];\n    if (configEquals(entry.config, newConfig)) {\n      // Add the renderer to the cache entry and return\n      entry.ownedBy.push(rendererId);\n      return entry.atlas;\n    }\n  }\n\n  const newEntry: ICharAtlasCacheEntry = {\n    atlas: new DynamicCharAtlas(\n      document,\n      newConfig\n    ),\n    config: newConfig,\n    ownedBy: [rendererId]\n  };\n  charAtlasCache.push(newEntry);\n  return newEntry.atlas;\n}\n\n/**\n * Removes a terminal reference from the cache, allowing its memory to be freed.\n */\nexport function removeTerminalFromCache(rendererId: number): void {\n  for (let i = 0; i < charAtlasCache.length; i++) {\n    const index = charAtlasCache[i].ownedBy.indexOf(rendererId);\n    if (index !== -1) {\n      if (charAtlasCache[i].ownedBy.length === 1) {\n        // Remove the cache entry if it's the only renderer\n        charAtlasCache[i].atlas.dispose();\n        charAtlasCache.splice(i, 1);\n      } else {\n        // Remove the reference from the cache entry\n        charAtlasCache[i].ownedBy.splice(index, 1);\n      }\n      break;\n    }\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharAtlasConfig } from 'browser/renderer/atlas/Types';\nimport { DEFAULT_COLOR } from 'common/buffer/Constants';\nimport { IColorSet, IPartialColorSet } from 'browser/Types';\nimport { ITerminalOptions } from 'common/services/Services';\n\nexport function generateConfig(scaledCharWidth: number, scaledCharHeight: number, options: ITerminalOptions, colors: IColorSet): ICharAtlasConfig {\n  // null out some fields that don't matter\n  const clonedColors = <IPartialColorSet>{\n    foreground: colors.foreground,\n    background: colors.background,\n    cursor: undefined,\n    cursorAccent: undefined,\n    selection: undefined,\n    // For the static char atlas, we only use the first 16 colors, but we need all 256 for the\n    // dynamic character atlas.\n    ansi: colors.ansi.slice(0, 16)\n  };\n  return {\n    devicePixelRatio: window.devicePixelRatio,\n    scaledCharWidth,\n    scaledCharHeight,\n    fontFamily: options.fontFamily,\n    fontSize: options.fontSize,\n    fontWeight: options.fontWeight,\n    fontWeightBold: options.fontWeightBold,\n    allowTransparency: options.allowTransparency,\n    colors: clonedColors\n  };\n}\n\nexport function configEquals(a: ICharAtlasConfig, b: ICharAtlasConfig): boolean {\n  for (let i = 0; i < a.colors.ansi.length; i++) {\n    if (a.colors.ansi[i].rgba !== b.colors.ansi[i].rgba) {\n      return false;\n    }\n  }\n  return a.devicePixelRatio === b.devicePixelRatio &&\n      a.fontFamily === b.fontFamily &&\n      a.fontSize === b.fontSize &&\n      a.fontWeight === b.fontWeight &&\n      a.fontWeightBold === b.fontWeightBold &&\n      a.allowTransparency === b.allowTransparency &&\n      a.scaledCharWidth === b.scaledCharWidth &&\n      a.scaledCharHeight === b.scaledCharHeight &&\n      a.colors.foreground === b.colors.foreground &&\n      a.colors.background === b.colors.background;\n}\n\nexport function is256Color(colorCode: number): boolean {\n  return colorCode < DEFAULT_COLOR;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IColorManager, IColor, IColorSet } from 'browser/Types';\nimport { ITheme } from 'common/services/Services';\n\nconst DEFAULT_FOREGROUND = fromHex('#ffffff');\nconst DEFAULT_BACKGROUND = fromHex('#000000');\nconst DEFAULT_CURSOR = fromHex('#ffffff');\nconst DEFAULT_CURSOR_ACCENT = fromHex('#000000');\nconst DEFAULT_SELECTION = {\n  css: 'rgba(255, 255, 255, 0.3)',\n  rgba: 0xFFFFFF77\n};\n\n// An IIFE to generate DEFAULT_ANSI_COLORS. Do not mutate DEFAULT_ANSI_COLORS, instead make a copy\n// and mutate that.\nexport const DEFAULT_ANSI_COLORS = (() => {\n  const colors = [\n    // dark:\n    fromHex('#2e3436'),\n    fromHex('#cc0000'),\n    fromHex('#4e9a06'),\n    fromHex('#c4a000'),\n    fromHex('#3465a4'),\n    fromHex('#75507b'),\n    fromHex('#06989a'),\n    fromHex('#d3d7cf'),\n    // bright:\n    fromHex('#555753'),\n    fromHex('#ef2929'),\n    fromHex('#8ae234'),\n    fromHex('#fce94f'),\n    fromHex('#729fcf'),\n    fromHex('#ad7fa8'),\n    fromHex('#34e2e2'),\n    fromHex('#eeeeec')\n  ];\n\n  // Fill in the remaining 240 ANSI colors.\n  // Generate colors (16-231)\n  const v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];\n  for (let i = 0; i < 216; i++) {\n    const r = v[(i / 36) % 6 | 0];\n    const g = v[(i / 6) % 6 | 0];\n    const b = v[i % 6];\n    colors.push({\n      css: `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`,\n      // Use >>> 0 to force a conversion to an unsigned int\n      rgba: ((r << 24) | (g << 16) | (b << 8) | 0xFF) >>> 0\n    });\n  }\n\n  // Generate greys (232-255)\n  for (let i = 0; i < 24; i++) {\n    const c = 8 + i * 10;\n    const ch = toPaddedHex(c);\n    colors.push({\n      css: `#${ch}${ch}${ch}`,\n      rgba: ((c << 24) | (c << 16) | (c << 8) | 0xFF) >>> 0\n    });\n  }\n\n  return colors;\n})();\n\nfunction fromHex(css: string): IColor {\n  return {\n    css,\n    rgba: parseInt(css.slice(1), 16) << 8 | 0xFF\n  };\n}\n\nfunction toPaddedHex(c: number): string {\n  const s = c.toString(16);\n  return s.length < 2 ? '0' + s : s;\n}\n\n/**\n * Manages the source of truth for a terminal's colors.\n */\nexport class ColorManager implements IColorManager {\n  public colors: IColorSet;\n  private _ctx: CanvasRenderingContext2D;\n  private _litmusColor: CanvasGradient;\n\n  constructor(document: Document, public allowTransparency: boolean) {\n    const canvas = document.createElement('canvas');\n    canvas.width = 1;\n    canvas.height = 1;\n    const ctx = canvas.getContext('2d');\n    if (!ctx) {\n      throw new Error('Could not get rendering context');\n    }\n    this._ctx = ctx;\n    this._ctx.globalCompositeOperation = 'copy';\n    this._litmusColor = this._ctx.createLinearGradient(0, 0, 1, 1);\n    this.colors = {\n      foreground: DEFAULT_FOREGROUND,\n      background: DEFAULT_BACKGROUND,\n      cursor: DEFAULT_CURSOR,\n      cursorAccent: DEFAULT_CURSOR_ACCENT,\n      selection: DEFAULT_SELECTION,\n      ansi: DEFAULT_ANSI_COLORS.slice()\n    };\n  }\n\n  /**\n   * Sets the terminal's theme.\n   * @param theme The  theme to use. If a partial theme is provided then default\n   * colors will be used where colors are not defined.\n   */\n  public setTheme(theme: ITheme = {}): void {\n    this.colors.foreground = this._parseColor(theme.foreground, DEFAULT_FOREGROUND);\n    this.colors.background = this._parseColor(theme.background, DEFAULT_BACKGROUND);\n    this.colors.cursor = this._parseColor(theme.cursor, DEFAULT_CURSOR, true);\n    this.colors.cursorAccent = this._parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT, true);\n    this.colors.selection = this._parseColor(theme.selection, DEFAULT_SELECTION, true);\n    this.colors.ansi[0] = this._parseColor(theme.black, DEFAULT_ANSI_COLORS[0]);\n    this.colors.ansi[1] = this._parseColor(theme.red, DEFAULT_ANSI_COLORS[1]);\n    this.colors.ansi[2] = this._parseColor(theme.green, DEFAULT_ANSI_COLORS[2]);\n    this.colors.ansi[3] = this._parseColor(theme.yellow, DEFAULT_ANSI_COLORS[3]);\n    this.colors.ansi[4] = this._parseColor(theme.blue, DEFAULT_ANSI_COLORS[4]);\n    this.colors.ansi[5] = this._parseColor(theme.magenta, DEFAULT_ANSI_COLORS[5]);\n    this.colors.ansi[6] = this._parseColor(theme.cyan, DEFAULT_ANSI_COLORS[6]);\n    this.colors.ansi[7] = this._parseColor(theme.white, DEFAULT_ANSI_COLORS[7]);\n    this.colors.ansi[8] = this._parseColor(theme.brightBlack, DEFAULT_ANSI_COLORS[8]);\n    this.colors.ansi[9] = this._parseColor(theme.brightRed, DEFAULT_ANSI_COLORS[9]);\n    this.colors.ansi[10] = this._parseColor(theme.brightGreen, DEFAULT_ANSI_COLORS[10]);\n    this.colors.ansi[11] = this._parseColor(theme.brightYellow, DEFAULT_ANSI_COLORS[11]);\n    this.colors.ansi[12] = this._parseColor(theme.brightBlue, DEFAULT_ANSI_COLORS[12]);\n    this.colors.ansi[13] = this._parseColor(theme.brightMagenta, DEFAULT_ANSI_COLORS[13]);\n    this.colors.ansi[14] = this._parseColor(theme.brightCyan, DEFAULT_ANSI_COLORS[14]);\n    this.colors.ansi[15] = this._parseColor(theme.brightWhite, DEFAULT_ANSI_COLORS[15]);\n  }\n\n  private _parseColor(\n    css: string | undefined,\n    fallback: IColor,\n    allowTransparency: boolean = this.allowTransparency\n  ): IColor {\n    if (css === undefined) {\n      return fallback;\n    }\n\n    // If parsing the value results in failure, then it must be ignored, and the attribute must\n    // retain its previous value.\n    // -- https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles\n    this._ctx.fillStyle = this._litmusColor;\n    this._ctx.fillStyle = css;\n    if (typeof this._ctx.fillStyle !== 'string') {\n      console.warn(`Color: ${css} is invalid using fallback ${fallback.css}`);\n      return fallback;\n    }\n\n    this._ctx.fillRect(0, 0, 1, 1);\n    const data = this._ctx.getImageData(0, 0, 1, 1).data;\n\n    if (!allowTransparency && data[3] !== 0xFF) {\n      // Ideally we'd just ignore the alpha channel, but...\n      //\n      // Browsers may not give back exactly the same RGB values we put in, because most/all\n      // convert the color to a pre-multiplied representation. getImageData converts that back to\n      // a un-premultipled representation, but the precision loss may make the RGB channels unuable\n      // on their own.\n      //\n      // E.g. In Chrome #12345610 turns into #10305010, and in the extreme case, 0xFFFFFF00 turns\n      // into 0x00000000.\n      //\n      // \"Note: Due to the lossy nature of converting to and from premultiplied alpha color values,\n      // pixels that have just been set using putImageData() might be returned to an equivalent\n      // getImageData() as different values.\"\n      // -- https://html.spec.whatwg.org/multipage/canvas.html#pixel-manipulation\n      //\n      // So let's just use the fallback color in this case instead.\n      console.warn(\n        `Color: ${css} is using transparency, but allowTransparency is false. ` +\n        `Using fallback ${fallback.css}.`\n      );\n      return fallback;\n    }\n\n    return {\n      css,\n      rgba: (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0\n    };\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport function throwIfFalsy<T>(value: T | undefined | null): T {\n  if (!value) {\n    throw new Error('value must not be falsy');\n  }\n  return value;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine, ICellData, CharData } from 'common/Types';\nimport { ICharacterJoinerRegistry, ICharacterJoiner } from 'browser/renderer/Types';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService } from 'common/services/Services';\n\nexport class JoinedCellData extends AttributeData implements ICellData {\n  private _width: number;\n  // .content carries no meaning for joined CellData, simply nullify it\n  // thus we have to overload all other .content accessors\n  public content: number = 0;\n  public fg: number;\n  public bg: number;\n  public combinedData: string = '';\n\n  constructor(firstCell: ICellData, chars: string, width: number) {\n    super();\n    this.fg = firstCell.fg;\n    this.bg = firstCell.bg;\n    this.combinedData = chars;\n    this._width = width;\n  }\n\n  public isCombined(): number {\n    // always mark joined cell data as combined\n    return Content.IS_COMBINED_MASK;\n  }\n\n  public getWidth(): number {\n    return this._width;\n  }\n\n  public getChars(): string {\n    return this.combinedData;\n  }\n\n  public getCode(): number {\n    // code always gets the highest possible fake codepoint (read as -1)\n    // this is needed as code is used by caches as identifier\n    return 0x1FFFFF;\n  }\n\n  public setFromCharData(value: CharData): void {\n    throw new Error('not implemented');\n  }\n\n  public getAsCharData(): CharData {\n    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n  }\n}\n\nexport class CharacterJoinerRegistry implements ICharacterJoinerRegistry {\n\n  private _characterJoiners: ICharacterJoiner[] = [];\n  private _nextCharacterJoinerId: number = 0;\n  private _workCell: CellData = new CellData();\n\n  constructor(private _bufferService: IBufferService) { }\n\n  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {\n    const joiner: ICharacterJoiner = {\n      id: this._nextCharacterJoinerId++,\n      handler\n    };\n\n    this._characterJoiners.push(joiner);\n    return joiner.id;\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): boolean {\n    for (let i = 0; i < this._characterJoiners.length; i++) {\n      if (this._characterJoiners[i].id === joinerId) {\n        this._characterJoiners.splice(i, 1);\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  public getJoinedCharacters(row: number): [number, number][] {\n    if (this._characterJoiners.length === 0) {\n      return [];\n    }\n\n    const line = this._bufferService.buffer.lines.get(row);\n    if (!line || line.length === 0) {\n      return [];\n    }\n\n    const ranges: [number, number][] = [];\n    const lineStr = line.translateToString(true);\n\n    // Because some cells can be represented by multiple javascript characters,\n    // we track the cell and the string indexes separately. This allows us to\n    // translate the string ranges we get from the joiners back into cell ranges\n    // for use when rendering\n    let rangeStartColumn = 0;\n    let currentStringIndex = 0;\n    let rangeStartStringIndex = 0;\n    let rangeAttrFG = line.getFg(0);\n    let rangeAttrBG = line.getBg(0);\n\n    for (let x = 0; x < line.getTrimmedLength(); x++) {\n      line.loadCell(x, this._workCell);\n\n      if (this._workCell.getWidth() === 0) {\n        // If this character is of width 0, skip it.\n        continue;\n      }\n\n      // End of range\n      if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) {\n        // If we ended up with a sequence of more than one character,\n        // look for ranges to join.\n        if (x - rangeStartColumn > 1) {\n          const joinedRanges = this._getJoinedRanges(\n            lineStr,\n            rangeStartStringIndex,\n            currentStringIndex,\n            line,\n            rangeStartColumn\n          );\n          for (let i = 0; i < joinedRanges.length; i++) {\n            ranges.push(joinedRanges[i]);\n          }\n        }\n\n        // Reset our markers for a new range.\n        rangeStartColumn = x;\n        rangeStartStringIndex = currentStringIndex;\n        rangeAttrFG = this._workCell.fg;\n        rangeAttrBG = this._workCell.bg;\n      }\n\n      currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length;\n    }\n\n    // Process any trailing ranges.\n    if (this._bufferService.cols - rangeStartColumn > 1) {\n      const joinedRanges = this._getJoinedRanges(\n        lineStr,\n        rangeStartStringIndex,\n        currentStringIndex,\n        line,\n        rangeStartColumn\n      );\n      for (let i = 0; i < joinedRanges.length; i++) {\n        ranges.push(joinedRanges[i]);\n      }\n    }\n\n    return ranges;\n  }\n\n  /**\n   * Given a segment of a line of text, find all ranges of text that should be\n   * joined in a single rendering unit. Ranges are internally converted to\n   * column ranges, rather than string ranges.\n   * @param line String representation of the full line of text\n   * @param startIndex Start position of the range to search in the string (inclusive)\n   * @param endIndex End position of the range to search in the string (exclusive)\n   */\n  private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] {\n    const text = line.substring(startIndex, endIndex);\n    // At this point we already know that there is at least one joiner so\n    // we can just pull its value and assign it directly rather than\n    // merging it into an empty array, which incurs unnecessary writes.\n    const joinedRanges: [number, number][] = this._characterJoiners[0].handler(text);\n    for (let i = 1; i < this._characterJoiners.length; i++) {\n      // We merge any overlapping ranges across the different joiners\n      const joinerRanges = this._characterJoiners[i].handler(text);\n      for (let j = 0; j < joinerRanges.length; j++) {\n        CharacterJoinerRegistry._mergeRanges(joinedRanges, joinerRanges[j]);\n      }\n    }\n    this._stringRangesToCellRanges(joinedRanges, lineData, startCol);\n    return joinedRanges;\n  }\n\n  /**\n   * Modifies the provided ranges in-place to adjust for variations between\n   * string length and cell width so that the range represents a cell range,\n   * rather than the string range the joiner provides.\n   * @param ranges String ranges containing start (inclusive) and end (exclusive) index\n   * @param line Cell data for the relevant line in the terminal\n   * @param startCol Offset within the line to start from\n   */\n  private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void {\n    let currentRangeIndex = 0;\n    let currentRangeStarted = false;\n    let currentStringIndex = 0;\n    let currentRange = ranges[currentRangeIndex];\n\n    // If we got through all of the ranges, stop searching\n    if (!currentRange) {\n      return;\n    }\n\n    for (let x = startCol; x < this._bufferService.cols; x++) {\n      const width = line.getWidth(x);\n      const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length;\n\n      // We skip zero-width characters when creating the string to join the text\n      // so we do the same here\n      if (width === 0) {\n        continue;\n      }\n\n      // Adjust the start of the range\n      if (!currentRangeStarted && currentRange[0] <= currentStringIndex) {\n        currentRange[0] = x;\n        currentRangeStarted = true;\n      }\n\n      // Adjust the end of the range\n      if (currentRange[1] <= currentStringIndex) {\n        currentRange[1] = x;\n\n        // We're finished with this range, so we move to the next one\n        currentRange = ranges[++currentRangeIndex];\n\n        // If there are no more ranges left, stop searching\n        if (!currentRange) {\n          break;\n        }\n\n        // Ranges can be on adjacent characters. Because the end index of the\n        // ranges are exclusive, this means that the index for the start of a\n        // range can be the same as the end index of the previous range. To\n        // account for the start of the next range, we check here just in case.\n        if (currentRange[0] <= currentStringIndex) {\n          currentRange[0] = x;\n          currentRangeStarted = true;\n        } else {\n          currentRangeStarted = false;\n        }\n      }\n\n      // Adjust the string index based on the character length to line up with\n      // the column adjustment\n      currentStringIndex += length;\n    }\n\n    // If there is still a range left at the end, it must extend all the way to\n    // the end of the line.\n    if (currentRange) {\n      currentRange[1] = this._bufferService.cols;\n    }\n  }\n\n  /**\n   * Merges the range defined by the provided start and end into the list of\n   * existing ranges. The merge is done in place on the existing range for\n   * performance and is also returned.\n   * @param ranges Existing range list\n   * @param newRange Tuple of two numbers representing the new range to merge in.\n   * @returns The ranges input with the new range merged in place\n   */\n  private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] {\n    let inRange = false;\n    for (let i = 0; i < ranges.length; i++) {\n      const range = ranges[i];\n      if (!inRange) {\n        if (newRange[1] <= range[0]) {\n          // Case 1: New range is before the search range\n          ranges.splice(i, 0, newRange);\n          return ranges;\n        }\n\n        if (newRange[1] <= range[1]) {\n          // Case 2: New range is either wholly contained within the\n          // search range or overlaps with the front of it\n          range[0] = Math.min(newRange[0], range[0]);\n          return ranges;\n        }\n\n        if (newRange[0] < range[1]) {\n          // Case 3: New range either wholly contains the search range\n          // or overlaps with the end of it\n          range[0] = Math.min(newRange[0], range[0]);\n          inRange = true;\n        }\n\n        // Case 4: New range starts after the search range\n        continue;\n      } else {\n        if (newRange[1] <= range[0]) {\n          // Case 5: New range extends from previous range but doesn't\n          // reach the current one\n          ranges[i - 1][1] = newRange[1];\n          return ranges;\n        }\n\n        if (newRange[1] <= range[1]) {\n          // Case 6: New range extends from prvious range into the\n          // current range\n          ranges[i - 1][1] = Math.max(newRange[1], range[1]);\n          ranges.splice(i, 1);\n          return ranges;\n        }\n\n        // Case 7: New range extends from previous range past the\n        // end of the current range\n        ranges.splice(i, 1);\n        i--;\n      }\n    }\n\n    if (inRange) {\n      // Case 8: New range extends past the last existing range\n      ranges[ranges.length - 1][1] = newRange[1];\n    } else {\n      // Case 9: New range starts after the last existing range\n      ranges.push(newRange);\n    }\n\n    return ranges;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport function getCoordsRelativeToElement(event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] {\n  const rect = element.getBoundingClientRect();\n  return [event.clientX - rect.left, event.clientY - rect.top];\n}\n\n/**\n * Gets coordinates within the terminal for a particular mouse event. The result\n * is returned as an array in the form [x, y] instead of an object as it's a\n * little faster and this function is used in some low level code.\n * @param event The mouse event.\n * @param element The terminal's container element.\n * @param colCount The number of columns in the terminal.\n * @param rowCount The number of rows n the terminal.\n * @param isSelection Whether the request is for the selection or not. This will\n * apply an offset to the x value such that the left half of the cell will\n * select that cell and the right half will select the next cell.\n */\nexport function getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, actualCellWidth: number, actualCellHeight: number, isSelection?: boolean): [number, number] | undefined {\n  // Coordinates cannot be measured if there are no valid\n  if (!hasValidCharSize) {\n    return undefined;\n  }\n\n  const coords = getCoordsRelativeToElement(event, element);\n  if (!coords) {\n    return undefined;\n  }\n\n  coords[0] = Math.ceil((coords[0] + (isSelection ? actualCellWidth / 2 : 0)) / actualCellWidth);\n  coords[1] = Math.ceil(coords[1] / actualCellHeight);\n\n  // Ensure coordinates are within the terminal viewport. Note that selections\n  // need an addition point of precision to cover the end point (as characters\n  // cover half of one char and half of the next).\n  coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));\n  coords[1] = Math.min(Math.max(coords[1], 1), rowCount);\n\n  return coords;\n}\n\n/**\n * Gets coordinates within the terminal for a particular mouse event, wrapping\n * them to the bounds of the terminal and adding 32 to both the x and y values\n * as expected by xterm.\n */\nexport function getRawByteCoords(coords: [number, number] | undefined): { x: number, y: number } | undefined {\n  if (!coords) {\n    return undefined;\n  }\n\n  // xterm sends raw bytes and starts at 32 (SP) for each.\n  return { x: coords[0] + 32, y: coords[1] + 32 };\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\n/**\n * Debounces calls to render terminal rows using animation frames.\n */\nexport class RenderDebouncer implements IDisposable {\n  private _rowStart: number | undefined;\n  private _rowEnd: number | undefined;\n  private _rowCount: number | undefined;\n  private _animationFrame: number | undefined;\n\n  constructor(\n    private _renderCallback: (start: number, end: number) => void\n  ) {\n  }\n\n  public dispose(): void {\n    if (this._animationFrame) {\n      window.cancelAnimationFrame(this._animationFrame);\n      this._animationFrame = undefined;\n    }\n  }\n\n  public refresh(rowStart: number, rowEnd: number, rowCount: number): void {\n    this._rowCount = rowCount;\n    // Get the min/max row start/end for the arg values\n    rowStart = rowStart !== undefined ? rowStart : 0;\n    rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;\n    // Set the properties to the updated values\n    this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;\n    this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;\n\n    if (this._animationFrame) {\n      return;\n    }\n\n    this._animationFrame = window.requestAnimationFrame(() => this._innerRefresh());\n  }\n\n  private _innerRefresh(): void {\n    // Make sure values are set\n    if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {\n      return;\n    }\n\n    // Clamp values\n    this._rowStart = Math.max(this._rowStart, 0);\n    this._rowEnd = Math.min(this._rowEnd, this._rowCount - 1);\n\n    // Run render callback\n    this._renderCallback(this._rowStart, this._rowEnd);\n\n    // Reset debouncer\n    this._rowStart = undefined;\n    this._rowEnd = undefined;\n    this._animationFrame = undefined;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'common/Lifecycle';\n\nexport type ScreenDprListener = (newDevicePixelRatio?: number, oldDevicePixelRatio?: number) => void;\n\n/**\n * The screen device pixel ratio monitor allows listening for when the\n * window.devicePixelRatio value changes. This is done not with polling but with\n * the use of window.matchMedia to watch media queries. When the event fires,\n * the listener will be reattached using a different media query to ensure that\n * any further changes will register.\n *\n * The listener should fire on both window zoom changes and switching to a\n * monitor with a different DPI.\n */\nexport class ScreenDprMonitor extends Disposable {\n  private _currentDevicePixelRatio: number = window.devicePixelRatio;\n  private _outerListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | undefined;\n  private _listener: ScreenDprListener | undefined;\n  private _resolutionMediaMatchList: MediaQueryList | undefined;\n\n  public setListener(listener: ScreenDprListener): void {\n    if (this._listener) {\n      this.clearListener();\n    }\n    this._listener = listener;\n    this._outerListener = () => {\n      if (!this._listener) {\n        return;\n      }\n      this._listener(window.devicePixelRatio, this._currentDevicePixelRatio);\n      this._updateDpr();\n    };\n    this._updateDpr();\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this.clearListener();\n  }\n\n  private _updateDpr(): void {\n    if (!this._resolutionMediaMatchList || !this._outerListener) {\n      return;\n    }\n\n    // Clear listeners for old DPR\n    this._resolutionMediaMatchList.removeListener(this._outerListener);\n\n    // Add listeners for new DPR\n    this._currentDevicePixelRatio = window.devicePixelRatio;\n    this._resolutionMediaMatchList = window.matchMedia(`screen and (resolution: ${window.devicePixelRatio}dppx)`);\n    this._resolutionMediaMatchList.addListener(this._outerListener);\n  }\n\n  public clearListener(): void {\n    if (!this._resolutionMediaMatchList || !this._listener || !this._outerListener) {\n      return;\n    }\n    this._resolutionMediaMatchList.removeListener(this._outerListener);\n    this._resolutionMediaMatchList = undefined;\n    this._listener = undefined;\n    this._outerListener = undefined;\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/*\n * A simple utility for cloning values\n */\nexport function clone<T>(val: T, depth: number = 5): T {\n  if (typeof val !== 'object') {\n    return val;\n  }\n\n  // If we're cloning an array, use an array as the base, otherwise use an object\n  const clonedObject: any = Array.isArray(val) ? [] : {};\n\n  for (const key in val) {\n    // Recursively clone eack item unless we're at the maximum depth\n    clonedObject[key] = depth <= 1 ? val[key] : (val[key] ? clone(val[key], depth - 1) : val[key]);\n  }\n\n  return clonedObject as T;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Terminal as ITerminalApi, ITerminalOptions, IMarker, IDisposable, ILinkMatcherOptions, ITheme, ILocalizableStrings, ITerminalAddon, ISelectionPosition, IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi, IParser, IFunctionIdentifier } from 'xterm';\nimport { ITerminal } from '../Types';\nimport { IBufferLine } from 'common/Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { Terminal as TerminalCore } from '../Terminal';\nimport * as Strings from '../browser/LocalizableStrings';\nimport { IEvent } from 'common/EventEmitter';\nimport { AddonManager } from './AddonManager';\nimport { IParams } from 'common/parser/Types';\n\nexport class Terminal implements ITerminalApi {\n  private _core: ITerminal;\n  private _addonManager: AddonManager;\n  private _parser: IParser;\n\n  constructor(options?: ITerminalOptions) {\n    this._core = new TerminalCore(options);\n    this._addonManager = new AddonManager();\n  }\n\n  public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }\n  public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }\n  public get onSelectionChange(): IEvent<void> { return this._core.onSelectionChange; }\n  public get onData(): IEvent<string> { return this._core.onData; }\n  public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }\n  public get onScroll(): IEvent<number> { return this._core.onScroll; }\n  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }\n  public get onRender(): IEvent<{ start: number, end: number }> { return this._core.onRender; }\n  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._core.onResize; }\n\n  public get element(): HTMLElement | undefined { return this._core.element; }\n  public get parser(): IParser {\n    if (!this._parser) {\n      this._parser = new ParserApi(this._core);\n    }\n    return this._parser;\n  }\n  public get textarea(): HTMLTextAreaElement | undefined { return this._core.textarea; }\n  public get rows(): number { return this._core.rows; }\n  public get cols(): number { return this._core.cols; }\n  public get buffer(): IBufferApi { return new BufferApiView(this._core.buffer); }\n  public get markers(): ReadonlyArray<IMarker> { return this._core.markers; }\n  public blur(): void {\n    this._core.blur();\n  }\n  public focus(): void {\n    this._core.focus();\n  }\n  public resize(columns: number, rows: number): void {\n    this._verifyIntegers(columns, rows);\n    this._core.resize(columns, rows);\n  }\n  public open(parent: HTMLElement): void {\n    this._core.open(parent);\n  }\n  public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void {\n    this._core.attachCustomKeyEventHandler(customKeyEventHandler);\n  }\n  public registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number {\n    return this._core.registerLinkMatcher(regex, handler, options);\n  }\n  public deregisterLinkMatcher(matcherId: number): void {\n    this._core.deregisterLinkMatcher(matcherId);\n  }\n  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {\n    return this._core.registerCharacterJoiner(handler);\n  }\n  public deregisterCharacterJoiner(joinerId: number): void {\n    this._core.deregisterCharacterJoiner(joinerId);\n  }\n  public addMarker(cursorYOffset: number): IMarker {\n    this._verifyIntegers(cursorYOffset);\n    return this._core.addMarker(cursorYOffset);\n  }\n  public hasSelection(): boolean {\n    return this._core.hasSelection();\n  }\n  public select(column: number, row: number, length: number): void {\n    this._verifyIntegers(column, row, length);\n    this._core.select(column, row, length);\n  }\n  public getSelection(): string {\n    return this._core.getSelection();\n  }\n  public getSelectionPosition(): ISelectionPosition | undefined {\n    return this._core.getSelectionPosition();\n  }\n  public clearSelection(): void {\n    this._core.clearSelection();\n  }\n  public selectAll(): void {\n    this._core.selectAll();\n  }\n  public selectLines(start: number, end: number): void {\n    this._verifyIntegers(start, end);\n    this._core.selectLines(start, end);\n  }\n  public dispose(): void {\n    this._addonManager.dispose();\n    this._core.dispose();\n  }\n  public scrollLines(amount: number): void {\n    this._verifyIntegers(amount);\n    this._core.scrollLines(amount);\n  }\n  public scrollPages(pageCount: number): void {\n    this._verifyIntegers(pageCount);\n    this._core.scrollPages(pageCount);\n  }\n  public scrollToTop(): void {\n    this._core.scrollToTop();\n  }\n  public scrollToBottom(): void {\n    this._core.scrollToBottom();\n  }\n  public scrollToLine(line: number): void {\n    this._verifyIntegers(line);\n    this._core.scrollToLine(line);\n  }\n  public clear(): void {\n    this._core.clear();\n  }\n  public write(data: string | Uint8Array, callback?: () => void): void {\n    this._core.write(data, callback);\n  }\n  public writeUtf8(data: Uint8Array, callback?: () => void): void {\n    this._core.write(data, callback);\n  }\n  public writeln(data: string | Uint8Array, callback?: () => void): void {\n    this._core.write(data);\n    this._core.write('\\r\\n', callback);\n  }\n  public paste(data: string): void {\n    this._core.paste(data);\n  }\n  public getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'fontWeight' | 'fontWeightBold' | 'logLevel' | 'rendererType' | 'termName' | 'wordSeparator'): string;\n  public getOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell'): boolean;\n  public getOption(key: 'colors'): string[];\n  public getOption(key: 'cols' | 'fontSize' | 'letterSpacing' | 'lineHeight' | 'rows' | 'tabStopWidth' | 'scrollback'): number;\n  public getOption(key: 'handler'): (data: string) => void;\n  public getOption(key: string): any;\n  public getOption(key: any): any {\n    return this._core.optionsService.getOption(key);\n  }\n  public setOption(key: 'bellSound' | 'fontFamily' | 'termName' | 'wordSeparator', value: string): void;\n  public setOption(key: 'fontWeight' | 'fontWeightBold', value: 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'): void;\n  public setOption(key: 'logLevel', value: 'debug' | 'info' | 'warn' | 'error' | 'off'): void;\n  public setOption(key: 'bellStyle', value: 'none' | 'visual' | 'sound' | 'both'): void;\n  public setOption(key: 'cursorStyle', value: 'block' | 'underline' | 'bar'): void;\n  public setOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell', value: boolean): void;\n  public setOption(key: 'colors', value: string[]): void;\n  public setOption(key: 'fontSize' | 'letterSpacing' | 'lineHeight' | 'tabStopWidth' | 'scrollback', value: number): void;\n  public setOption(key: 'handler', value: (data: string) => void): void;\n  public setOption(key: 'theme', value: ITheme): void;\n  public setOption(key: 'cols' | 'rows', value: number): void;\n  public setOption(key: string, value: any): void;\n  public setOption(key: any, value: any): void {\n    this._core.optionsService.setOption(key, value);\n  }\n  public refresh(start: number, end: number): void {\n    this._verifyIntegers(start, end);\n    this._core.refresh(start, end);\n  }\n  public reset(): void {\n    this._core.reset();\n  }\n  public loadAddon(addon: ITerminalAddon): void {\n    return this._addonManager.loadAddon(this, addon);\n  }\n  public static get strings(): ILocalizableStrings {\n    return Strings;\n  }\n\n  private _verifyIntegers(...values: number[]): void {\n    values.forEach(value => {\n      if (value === Infinity || isNaN(value) || value % 1 !== 0) {\n        throw new Error('This API only accepts integers');\n      }\n    });\n  }\n}\n\nclass BufferApiView implements IBufferApi {\n  constructor(private _buffer: IBuffer) {}\n\n  public get cursorY(): number { return this._buffer.y; }\n  public get cursorX(): number { return this._buffer.x; }\n  public get viewportY(): number { return this._buffer.ydisp; }\n  public get baseY(): number { return this._buffer.ybase; }\n  public get length(): number { return this._buffer.lines.length; }\n  public getLine(y: number): IBufferLineApi | undefined {\n    const line = this._buffer.lines.get(y);\n    if (!line) {\n      return undefined;\n    }\n    return new BufferLineApiView(line);\n  }\n}\n\nclass BufferLineApiView implements IBufferLineApi {\n  constructor(private _line: IBufferLine) {}\n\n  public get isWrapped(): boolean { return this._line.isWrapped; }\n  public getCell(x: number): IBufferCellApi | undefined {\n    if (x < 0 || x >= this._line.length) {\n      return undefined;\n    }\n    return new BufferCellApiView(this._line, x);\n  }\n  public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string {\n    return this._line.translateToString(trimRight, startColumn, endColumn);\n  }\n}\n\nclass BufferCellApiView implements IBufferCellApi {\n  constructor(private _line: IBufferLine, private _x: number) {}\n  public get char(): string { return this._line.getString(this._x); }\n  public get width(): number { return this._line.getWidth(this._x); }\n}\n\nclass ParserApi implements IParser {\n  constructor(private _core: ITerminal) {}\n\n  public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable {\n    return this._core.addCsiHandler(id, (params: IParams) => callback(params.toArray()));\n  }\n  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable {\n    return this._core.addDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray()));\n  }\n  public addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable {\n    return this._core.addEscHandler(id, handler);\n  }\n  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {\n    return this._core.addOscHandler(ident, callback);\n  }\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n *\n * Originally forked from (with the author's permission):\n *   Fabrice Bellard's javascript vt100 for jslinux:\n *   http://bellard.org/jslinux/\n *   Copyright (c) 2011 Fabrice Bellard\n *   The original design remains. The terminal itself\n *   has been extended to include xterm CSI codes, among\n *   other features.\n *\n * Terminal Emulation References:\n *   http://vt100.net/\n *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt\n *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.html\n *   http://invisible-island.net/vttest/\n *   http://www.inwap.com/pdp10/ansicode.txt\n *   http://linux.die.net/man/4/console_codes\n *   http://linux.die.net/man/7/urxvt\n */\n\nimport { IInputHandlingTerminal, ICompositionHelper, ITerminalOptions, ITerminal, IBrowser, CustomKeyEventHandler } from './Types';\nimport { IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { CompositionHelper } from 'browser/input/CompositionHelper';\nimport { Viewport } from 'browser/Viewport';\nimport { rightClickHandler, moveTextAreaUnderMouseCursor, handlePasteEvent, copyHandler, paste } from 'browser/Clipboard';\nimport { C0 } from 'common/data/EscapeSequences';\nimport { InputHandler } from './InputHandler';\nimport { Renderer } from './renderer/Renderer';\nimport { Linkifier } from 'browser/Linkifier';\nimport { SelectionService } from 'browser/services/SelectionService';\nimport * as Browser from 'common/Platform';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport * as Strings from 'browser/LocalizableStrings';\nimport { SoundService } from 'browser/services/SoundService';\nimport { MouseZoneManager } from 'browser/MouseZoneManager';\nimport { AccessibilityManager } from './AccessibilityManager';\nimport { ITheme, IMarker, IDisposable, ISelectionPosition } from 'xterm';\nimport { DomRenderer } from './renderer/dom/DomRenderer';\nimport { IKeyboardEvent, KeyboardResultType, ICharset, IBufferLine, IAttributeData, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';\nimport { evaluateKeyboardEvent } from 'common/input/Keyboard';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { applyWindowsMode } from './WindowsMode';\nimport { ColorManager } from 'browser/ColorManager';\nimport { RenderService } from 'browser/services/RenderService';\nimport { IOptionsService, IBufferService, ICoreMouseService, ICoreService, ILogService, IDirtyRowService, IInstantiationService } from 'common/services/Services';\nimport { OptionsService } from 'common/services/OptionsService';\nimport { ICharSizeService, IRenderService, IMouseService, ISelectionService, ISoundService } from 'browser/services/Services';\nimport { CharSizeService } from 'browser/services/CharSizeService';\nimport { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService';\nimport { Disposable } from 'common/Lifecycle';\nimport { IBufferSet, IBuffer } from 'common/buffer/Types';\nimport { Attributes } from 'common/buffer/Constants';\nimport { MouseService } from 'browser/services/MouseService';\nimport { IParams, IFunctionIdentifier } from 'common/parser/Types';\nimport { CoreService } from 'common/services/CoreService';\nimport { LogService } from 'common/services/LogService';\nimport { ILinkifier, IMouseZoneManager, LinkMatcherHandler, ILinkMatcherOptions, IViewport } from 'browser/Types';\nimport { DirtyRowService } from 'common/services/DirtyRowService';\nimport { InstantiationService } from 'common/services/InstantiationService';\nimport { CoreMouseService } from 'common/services/CoreMouseService';\nimport { WriteBuffer } from 'common/input/WriteBuffer';\n\n// Let it work inside Node.js for automated testing purposes.\nconst document = (typeof window !== 'undefined') ? window.document : null;\n\n\nexport class Terminal extends Disposable implements ITerminal, IDisposable, IInputHandlingTerminal {\n  public textarea: HTMLTextAreaElement;\n  public element: HTMLElement;\n  public screenElement: HTMLElement;\n\n  /**\n   * The HTMLElement that the terminal is created in, set by Terminal.open.\n   */\n  private _parent: HTMLElement | null;\n  private _document: Document;\n  private _viewportScrollArea: HTMLElement;\n  private _viewportElement: HTMLElement;\n  private _helperContainer: HTMLElement;\n  private _compositionView: HTMLElement;\n\n  private _visualBellTimer: number;\n\n  public browser: IBrowser = <any>Browser;\n\n  // TODO: We should remove options once components adopt optionsService\n  public get options(): ITerminalOptions { return this.optionsService.options; }\n\n  // TODO: This can be changed to an enum or boolean, 0 and 1 seem to be the only options\n  public cursorState: number;\n  public cursorHidden: boolean;\n\n  private _customKeyEventHandler: CustomKeyEventHandler;\n\n  // common services\n  private _bufferService: IBufferService;\n  private _coreService: ICoreService;\n  private _coreMouseService: ICoreMouseService;\n  private _dirtyRowService: IDirtyRowService;\n  private _instantiationService: IInstantiationService;\n  private _logService: ILogService;\n  public optionsService: IOptionsService;\n\n  // browser services\n  private _charSizeService: ICharSizeService;\n  private _mouseService: IMouseService;\n  private _renderService: IRenderService;\n  private _selectionService: ISelectionService;\n  private _soundService: ISoundService;\n\n  // modes\n  public applicationKeypad: boolean;\n  public originMode: boolean;\n  public insertMode: boolean;\n  public wraparoundMode: boolean; // defaults: xterm - true, vt100 - false\n  public bracketedPasteMode: boolean;\n\n  // charset\n  // The current charset\n  public charset: ICharset;\n  public gcharset: number;\n  public glevel: number;\n  public charsets: ICharset[];\n\n  // mouse properties\n  public mouseEvents: CoreMouseEventType = CoreMouseEventType.NONE;\n  public sendFocus: boolean;\n\n  // misc\n  public savedCols: number;\n\n  public curAttrData: IAttributeData;\n  private _eraseAttrData: IAttributeData;\n\n  public params: (string | number)[];\n  public currentParam: string | number;\n\n  // write buffer\n  private _writeBuffer: WriteBuffer;\n\n  // Store if user went browsing history in scrollback\n  private _userScrolling: boolean;\n\n  /**\n   * Records whether the keydown event has already been handled and triggered a data event, if so\n   * the keypress event should not trigger a data event but should still print to the textarea so\n   * screen readers will announce it.\n   */\n  private _keyDownHandled: boolean = false;\n\n  private _inputHandler: InputHandler;\n  public linkifier: ILinkifier;\n  public viewport: IViewport;\n  private _compositionHelper: ICompositionHelper;\n  private _mouseZoneManager: IMouseZoneManager;\n  private _accessibilityManager: AccessibilityManager;\n  private _colorManager: ColorManager;\n  private _theme: ITheme;\n  private _windowsMode: IDisposable | undefined;\n\n  // bufferline to clone/copy from for new blank lines\n  private _blankLine: IBufferLine = null;\n\n  public get cols(): number { return this._bufferService.cols; }\n  public get rows(): number { return this._bufferService.rows; }\n\n  private _onCursorMove = new EventEmitter<void>();\n  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }\n  private _onData = new EventEmitter<string>();\n  public get onData(): IEvent<string> { return this._onData.event; }\n  private _onKey = new EventEmitter<{ key: string, domEvent: KeyboardEvent }>();\n  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._onKey.event; }\n  private _onLineFeed = new EventEmitter<void>();\n  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }\n  private _onRender = new EventEmitter<{ start: number, end: number }>();\n  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }\n  private _onResize = new EventEmitter<{ cols: number, rows: number }>();\n  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._onResize.event; }\n  private _onScroll = new EventEmitter<number>();\n  public get onScroll(): IEvent<number> { return this._onScroll.event; }\n  private _onSelectionChange = new EventEmitter<void>();\n  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }\n  private _onTitleChange = new EventEmitter<string>();\n  public get onTitleChange(): IEvent<string> { return this._onTitleChange.event; }\n\n  private _onFocus = new EventEmitter<void>();\n  public get onFocus(): IEvent<void> { return this._onFocus.event; }\n  private _onBlur = new EventEmitter<void>();\n  public get onBlur(): IEvent<void> { return this._onBlur.event; }\n  public onA11yCharEmitter = new EventEmitter<string>();\n  public get onA11yChar(): IEvent<string> { return this.onA11yCharEmitter.event; }\n  public onA11yTabEmitter = new EventEmitter<number>();\n  public get onA11yTab(): IEvent<number> { return this.onA11yTabEmitter.event; }\n\n  /**\n   * Creates a new `Terminal` object.\n   *\n   * @param options An object containing a set of options, the available options are:\n   *   - `cursorBlink` (boolean): Whether the terminal cursor blinks\n   *   - `cols` (number): The number of columns of the terminal (horizontal size)\n   *   - `rows` (number): The number of rows of the terminal (vertical size)\n   *\n   * @public\n   * @class Xterm Xterm\n   * @alias module:xterm/src/xterm\n   */\n  constructor(\n    options: ITerminalOptions = {}\n  ) {\n    super();\n\n    // Setup and initialize common services\n    this._instantiationService = new InstantiationService();\n    this.optionsService = new OptionsService(options);\n    this._instantiationService.setService(IOptionsService, this.optionsService);\n    this._bufferService = this._instantiationService.createInstance(BufferService);\n    this._instantiationService.setService(IBufferService, this._bufferService);\n    this._logService = this._instantiationService.createInstance(LogService);\n    this._instantiationService.setService(ILogService, this._logService);\n    this._coreService = this._instantiationService.createInstance(CoreService, () => this.scrollToBottom());\n    this._instantiationService.setService(ICoreService, this._coreService);\n    this._coreService.onData(e => this._onData.fire(e));\n    this._coreMouseService = this._instantiationService.createInstance(CoreMouseService);\n    this._instantiationService.setService(ICoreMouseService, this._coreMouseService);\n    this._dirtyRowService = this._instantiationService.createInstance(DirtyRowService);\n    this._instantiationService.setService(IDirtyRowService, this._dirtyRowService);\n\n    this._setupOptionsListeners();\n    this._setup();\n\n    this._writeBuffer = new WriteBuffer(data => this._inputHandler.parse(data));\n  }\n\n  public dispose(): void {\n    if (this._isDisposed) {\n      return;\n    }\n    super.dispose();\n    if (this._windowsMode) {\n      this._windowsMode.dispose();\n      this._windowsMode = undefined;\n    }\n    if (this._renderService) {\n      this._renderService.dispose();\n    }\n    this._customKeyEventHandler = null;\n    this.write = () => {};\n    if (this.element && this.element.parentNode) {\n      this.element.parentNode.removeChild(this.element);\n    }\n  }\n\n  private _setup(): void {\n    this._parent = document ? document.body : null;\n\n    this.cursorState = 0;\n    this.cursorHidden = false;\n    this._customKeyEventHandler = null;\n\n    // modes\n    this.applicationKeypad = false;\n    this.originMode = false;\n    this.insertMode = false;\n    this.wraparoundMode = true; // defaults: xterm - true, vt100 - false\n    this.bracketedPasteMode = false;\n\n    // charset\n    this.charset = null;\n    this.gcharset = null;\n    this.glevel = 0;\n    // TODO: Can this be just []?\n    this.charsets = [null];\n\n    this.curAttrData = DEFAULT_ATTR_DATA.clone();\n    this._eraseAttrData = DEFAULT_ATTR_DATA.clone();\n\n    this.params = [];\n    this.currentParam = 0;\n\n    this._userScrolling = false;\n\n    // Register input handler and refire/handle events\n    this._inputHandler = new InputHandler(this, this._bufferService, this._coreService, this._dirtyRowService, this._logService, this.optionsService, this._coreMouseService);\n    this._inputHandler.onCursorMove(() => this._onCursorMove.fire());\n    this._inputHandler.onLineFeed(() => this._onLineFeed.fire());\n    this.register(this._inputHandler);\n\n    this.linkifier = this.linkifier || new Linkifier(this._bufferService, this._logService);\n\n    if (this.options.windowsMode) {\n      this._windowsMode = applyWindowsMode(this);\n    }\n  }\n\n  /**\n   * Convenience property to active buffer.\n   */\n  public get buffer(): IBuffer {\n    return this.buffers.active;\n  }\n\n  public get buffers(): IBufferSet {\n    return this._bufferService.buffers;\n  }\n\n  /**\n   * back_color_erase feature for xterm.\n   */\n  public eraseAttrData(): IAttributeData {\n    this._eraseAttrData.bg &= ~(Attributes.CM_MASK | 0xFFFFFF);\n    this._eraseAttrData.bg |= this.curAttrData.bg & ~0xFC000000;\n    return this._eraseAttrData;\n  }\n\n  /**\n   * Focus the terminal. Delegates focus handling to the terminal's DOM element.\n   */\n  public focus(): void {\n    if (this.textarea) {\n      this.textarea.focus({ preventScroll: true });\n    }\n  }\n\n  public get isFocused(): boolean {\n    return document.activeElement === this.textarea && document.hasFocus();\n  }\n\n  private _setupOptionsListeners(): void {\n    // TODO: These listeners should be owned by individual components\n    this.optionsService.onOptionChange(key => {\n      switch (key) {\n        case 'fontFamily':\n        case 'fontSize':\n          // When the font changes the size of the cells may change which requires a renderer clear\n          if (this._renderService) {\n            this._renderService.clear();\n          }\n          if (this._charSizeService) {\n            this._charSizeService.measure();\n          }\n          break;\n        case 'drawBoldTextInBrightColors':\n        case 'letterSpacing':\n        case 'lineHeight':\n        case 'fontWeight':\n        case 'fontWeightBold':\n          // When the font changes the size of the cells may change which requires a renderer clear\n          if (this._renderService) {\n            this._renderService.clear();\n            this._renderService.onResize(this.cols, this.rows);\n            this.refresh(0, this.rows - 1);\n          }\n          break;\n        case 'rendererType':\n          if (this._renderService) {\n            this._renderService.setRenderer(this._createRenderer());\n            this._renderService.onResize(this.cols, this.rows);\n          }\n          break;\n        case 'scrollback':\n          this.buffers.resize(this.cols, this.rows);\n          if (this.viewport) {\n            this.viewport.syncScrollArea();\n          }\n          break;\n        case 'screenReaderMode':\n          if (this.optionsService.options.screenReaderMode) {\n            if (!this._accessibilityManager && this._renderService) {\n              this._accessibilityManager = new AccessibilityManager(this, this._renderService);\n            }\n          } else {\n            if (this._accessibilityManager) {\n              this._accessibilityManager.dispose();\n              this._accessibilityManager = null;\n            }\n          }\n          break;\n        case 'tabStopWidth': this.buffers.setupTabStops(); break;\n        case 'theme':\n          this._setTheme(this.optionsService.options.theme);\n          break;\n        case 'windowsMode':\n          if (this.optionsService.options.windowsMode) {\n            if (!this._windowsMode) {\n              this._windowsMode = applyWindowsMode(this);\n            }\n          } else {\n            if (this._windowsMode) {\n              this._windowsMode.dispose();\n              this._windowsMode = undefined;\n            }\n          }\n          break;\n      }\n    });\n  }\n\n  /**\n   * Binds the desired focus behavior on a given terminal object.\n   */\n  private _onTextAreaFocus(ev: KeyboardEvent): void {\n    if (this.sendFocus) {\n      this._coreService.triggerDataEvent(C0.ESC + '[I');\n    }\n    this.updateCursorStyle(ev);\n    this.element.classList.add('focus');\n    this.showCursor();\n    this._onFocus.fire();\n  }\n\n  /**\n   * Blur the terminal, calling the blur function on the terminal's underlying\n   * textarea.\n   */\n  public blur(): void {\n    return this.textarea.blur();\n  }\n\n  /**\n   * Binds the desired blur behavior on a given terminal object.\n   */\n  private _onTextAreaBlur(): void {\n    // Text can safely be removed on blur. Doing it earlier could interfere with\n    // screen readers reading it out.\n    this.textarea.value = '';\n    this.refresh(this.buffer.y, this.buffer.y);\n    if (this.sendFocus) {\n      this._coreService.triggerDataEvent(C0.ESC + '[O');\n    }\n    this.element.classList.remove('focus');\n    this._onBlur.fire();\n  }\n\n  /**\n   * Initialize default behavior\n   */\n  private _initGlobal(): void {\n    this._bindKeys();\n\n    // Bind clipboard functionality\n    this.register(addDisposableDomListener(this.element, 'copy', (event: ClipboardEvent) => {\n      // If mouse events are active it means the selection manager is disabled and\n      // copy should be handled by the host program.\n      if (!this.hasSelection()) {\n        return;\n      }\n      copyHandler(event, this._selectionService);\n    }));\n    const pasteHandlerWrapper = (event: ClipboardEvent) => handlePasteEvent(event, this.textarea, this.bracketedPasteMode, this._coreService);\n    this.register(addDisposableDomListener(this.textarea, 'paste', pasteHandlerWrapper));\n    this.register(addDisposableDomListener(this.element, 'paste', pasteHandlerWrapper));\n\n    // Handle right click context menus\n    if (Browser.isFirefox) {\n      // Firefox doesn't appear to fire the contextmenu event on right click\n      this.register(addDisposableDomListener(this.element, 'mousedown', (event: MouseEvent) => {\n        if (event.button === 2) {\n          rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);\n        }\n      }));\n    } else {\n      this.register(addDisposableDomListener(this.element, 'contextmenu', (event: MouseEvent) => {\n        rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);\n      }));\n    }\n\n    // Move the textarea under the cursor when middle clicking on Linux to ensure\n    // middle click to paste selection works. This only appears to work in Chrome\n    // at the time is writing.\n    if (Browser.isLinux) {\n      // Use auxclick event over mousedown the latter doesn't seem to work. Note\n      // that the regular click event doesn't fire for the middle mouse button.\n      this.register(addDisposableDomListener(this.element, 'auxclick', (event: MouseEvent) => {\n        if (event.button === 1) {\n          moveTextAreaUnderMouseCursor(event, this.textarea, this.screenElement);\n        }\n      }));\n    }\n  }\n\n  /**\n   * Apply key handling to the terminal\n   */\n  private _bindKeys(): void {\n    this.register(addDisposableDomListener(this.textarea, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true));\n    this.register(addDisposableDomListener(this.textarea, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true));\n    this.register(addDisposableDomListener(this.textarea, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true));\n    this.register(addDisposableDomListener(this.textarea, 'compositionstart', () => this._compositionHelper.compositionstart()));\n    this.register(addDisposableDomListener(this.textarea, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper.compositionupdate(e)));\n    this.register(addDisposableDomListener(this.textarea, 'compositionend', () => this._compositionHelper.compositionend()));\n    this.register(this.onRender(() => this._compositionHelper.updateCompositionElements()));\n    this.register(this.onRender(e => this._queueLinkification(e.start, e.end)));\n  }\n\n  /**\n   * Opens the terminal within an element.\n   *\n   * @param parent The element to create the terminal within.\n   */\n  public open(parent: HTMLElement): void {\n    this._parent = parent || this._parent;\n\n    if (!this._parent) {\n      throw new Error('Terminal requires a parent element.');\n    }\n\n    if (!document.body.contains(parent)) {\n      this._logService.warn('Terminal.open was called on an element that was not attached to the DOM');\n    }\n\n    this._document = this._parent.ownerDocument;\n\n    // Create main element container\n    this.element = this._document.createElement('div');\n    this.element.dir = 'ltr';   // xterm.css assumes LTR\n    this.element.classList.add('terminal');\n    this.element.classList.add('xterm');\n    this.element.setAttribute('tabindex', '0');\n    this._parent.appendChild(this.element);\n\n    // Performance: Use a document fragment to build the terminal\n    // viewport and helper elements detached from the DOM\n    const fragment = document.createDocumentFragment();\n    this._viewportElement = document.createElement('div');\n    this._viewportElement.classList.add('xterm-viewport');\n    fragment.appendChild(this._viewportElement);\n    this._viewportScrollArea = document.createElement('div');\n    this._viewportScrollArea.classList.add('xterm-scroll-area');\n    this._viewportElement.appendChild(this._viewportScrollArea);\n\n    this.screenElement = document.createElement('div');\n    this.screenElement.classList.add('xterm-screen');\n    // Create the container that will hold helpers like the textarea for\n    // capturing DOM Events. Then produce the helpers.\n    this._helperContainer = document.createElement('div');\n    this._helperContainer.classList.add('xterm-helpers');\n    this.screenElement.appendChild(this._helperContainer);\n    fragment.appendChild(this.screenElement);\n\n    this.textarea = document.createElement('textarea');\n    this.textarea.classList.add('xterm-helper-textarea');\n    this.textarea.setAttribute('aria-label', Strings.promptLabel);\n    this.textarea.setAttribute('aria-multiline', 'false');\n    this.textarea.setAttribute('autocorrect', 'off');\n    this.textarea.setAttribute('autocapitalize', 'off');\n    this.textarea.setAttribute('spellcheck', 'false');\n    this.textarea.tabIndex = 0;\n    this.register(addDisposableDomListener(this.textarea, 'focus', (ev: KeyboardEvent) => this._onTextAreaFocus(ev)));\n    this.register(addDisposableDomListener(this.textarea, 'blur', () => this._onTextAreaBlur()));\n    this._helperContainer.appendChild(this.textarea);\n\n    this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer);\n    this._instantiationService.setService(ICharSizeService, this._charSizeService);\n\n    this._compositionView = document.createElement('div');\n    this._compositionView.classList.add('composition-view');\n    this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView);\n    this._helperContainer.appendChild(this._compositionView);\n\n    // Performance: Add viewport and helper elements from the fragment\n    this.element.appendChild(fragment);\n\n    this._theme = this.options.theme || this._theme;\n    this.options.theme = undefined;\n    this._colorManager = new ColorManager(document, this.options.allowTransparency);\n    this._colorManager.setTheme(this._theme);\n\n    const renderer = this._createRenderer();\n    this._renderService = this._instantiationService.createInstance(RenderService, renderer, this.rows, this.screenElement);\n    this._instantiationService.setService(IRenderService, this._renderService);\n    this._renderService.onRender(e => this._onRender.fire(e));\n    this.onResize(e => this._renderService.resize(e.cols, e.rows));\n\n    this._soundService = this._instantiationService.createInstance(SoundService);\n    this._instantiationService.setService(ISoundService, this._soundService);\n    this._mouseService = this._instantiationService.createInstance(MouseService);\n    this._instantiationService.setService(IMouseService, this._mouseService);\n\n    this.viewport = this._instantiationService.createInstance(Viewport,\n      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),\n      this._viewportElement,\n      this._viewportScrollArea\n    );\n    this.viewport.onThemeChange(this._colorManager.colors);\n    this.register(this.viewport);\n\n    this.register(this.onCursorMove(() => this._renderService.onCursorMove()));\n    this.register(this.onResize(() => this._renderService.onResize(this.cols, this.rows)));\n    this.register(this.onBlur(() => this._renderService.onBlur()));\n    this.register(this.onFocus(() => this._renderService.onFocus()));\n    this.register(this._renderService.onDimensionsChange(() => this.viewport.syncScrollArea()));\n\n    this._selectionService = this._instantiationService.createInstance(SelectionService,\n      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),\n      this.element,\n      this.screenElement);\n    this._instantiationService.setService(ISelectionService, this._selectionService);\n    this.register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire()));\n    this.register(this._selectionService.onRedrawRequest(e => this._renderService.onSelectionChanged(e.start, e.end, e.columnSelectMode)));\n    this.register(this._selectionService.onLinuxMouseSelection(text => {\n      // If there's a new selection, put it into the textarea, focus and select it\n      // in order to register it as a selection on the OS. This event is fired\n      // only on Linux to enable middle click to paste selection.\n      this.textarea.value = text;\n      this.textarea.focus();\n      this.textarea.select();\n    }));\n    this.register(this.onScroll(() => {\n      this.viewport.syncScrollArea();\n      this._selectionService.refresh();\n    }));\n    this.register(addDisposableDomListener(this._viewportElement, 'scroll', () => this._selectionService.refresh()));\n\n    this._mouseZoneManager = this._instantiationService.createInstance(MouseZoneManager, this.element, this.screenElement);\n    this.register(this._mouseZoneManager);\n    this.register(this.onScroll(() => this._mouseZoneManager.clearAll()));\n    this.linkifier.attachToDom(this.element, this._mouseZoneManager);\n\n    // This event listener must be registered aftre MouseZoneManager is created\n    this.register(addDisposableDomListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService.onMouseDown(e)));\n\n    // apply mouse event classes set by escape codes before terminal was attached\n    if (this.mouseEvents) {\n      this._selectionService.disable();\n      this.element.classList.add('enable-mouse-events');\n    } else {\n      this._selectionService.enable();\n    }\n\n    if (this.options.screenReaderMode) {\n      // Note that this must be done *after* the renderer is created in order to\n      // ensure the correct order of the dprchange event\n      this._accessibilityManager = new AccessibilityManager(this, this._renderService);\n    }\n\n    // Measure the character size\n    this._charSizeService.measure();\n\n    // Setup loop that draws to screen\n    this.refresh(0, this.rows - 1);\n\n    // Initialize global actions that need to be taken on the document.\n    this._initGlobal();\n\n    // Listen for mouse events and translate\n    // them into terminal mouse protocols.\n    this.bindMouse();\n  }\n\n  private _createRenderer(): IRenderer {\n    switch (this.options.rendererType) {\n      case 'canvas': return new Renderer(this._colorManager.colors, this, this._bufferService, this._charSizeService, this.optionsService);\n      case 'dom': return new DomRenderer(this, this._colorManager.colors, this._charSizeService, this.optionsService);\n      default: throw new Error(`Unrecognized rendererType \"${this.options.rendererType}\"`);\n    }\n  }\n\n  /**\n   * Sets the theme on the renderer. The renderer must have been initialized.\n   * @param theme The theme to set.\n   */\n  private _setTheme(theme: ITheme): void {\n    this._theme = theme;\n    if (this._colorManager) {\n      this._colorManager.setTheme(theme);\n    }\n    if (this._renderService) {\n      this._renderService.setColors(this._colorManager.colors);\n    }\n    if (this.viewport) {\n      this.viewport.onThemeChange(this._colorManager.colors);\n    }\n  }\n\n  /**\n   * Bind certain mouse events to the terminal.\n   * By default only 3 button + wheel up/down is ativated. For higher buttons\n   * no mouse report will be created. Typically the standard actions will be active.\n   *\n   * There are several reasons not to enable support for higher buttons/wheel:\n   * - Button 4 and 5 are typically used for history back and forward navigation,\n   *   there is no straight forward way to supress/intercept those standard actions.\n   * - Support for higher buttons does not work in some platform/browser combinations.\n   * - Left/right wheel was not tested.\n   * - Emulators vary in mouse button support, typically only 3 buttons and\n   *   wheel up/down work reliable.\n   *\n   * TODO: Move mouse event code into its own file.\n   */\n  public bindMouse(): void {\n    const self = this;\n    const el = this.element;\n\n    // send event to CoreMouseService\n    function sendEvent(ev: MouseEvent | WheelEvent): boolean {\n      let pos;\n\n      // get mouse coordinates\n      pos = self._mouseService.getRawByteCoords(ev, self.screenElement, self.cols, self.rows);\n      if (!pos) {\n        return false;\n      }\n\n      let but: CoreMouseButton;\n      let action: CoreMouseAction;\n      switch ((<any>ev).overrideType || ev.type) {\n        case 'mousemove':\n          action = CoreMouseAction.MOVE;\n          if (ev.buttons === undefined) {\n            // buttons is not supported on macOS, try to get a value from button instead\n            but = CoreMouseButton.NONE;\n            if (ev.button !== undefined) {\n              but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n            }\n          } else {\n            // according to MDN buttons only reports up to button 5 (AUX2)\n            but = ev.buttons & 1 ? CoreMouseButton.LEFT :\n                  ev.buttons & 4 ? CoreMouseButton.MIDDLE :\n                  ev.buttons & 2 ? CoreMouseButton.RIGHT :\n                  CoreMouseButton.NONE; // fallback to NONE\n          }\n          break;\n        case 'mouseup':\n          action = CoreMouseAction.UP;\n          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n          break;\n        case 'mousedown':\n          action = CoreMouseAction.DOWN;\n          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n          break;\n        case 'wheel':\n          // only UP/DOWN wheel events are respected\n          if ((ev as WheelEvent).deltaY !== 0) {\n            action = (ev as WheelEvent).deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN;\n          }\n          but = CoreMouseButton.WHEEL;\n          break;\n        default:\n          // dont handle other event types by accident\n          return false;\n      }\n\n      // exit if we cannot determine valid button/action values\n      // do nothing for higher buttons than wheel\n      if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) {\n        return false;\n      }\n\n      return self._coreMouseService.triggerMouseEvent({\n        col: pos.x - 33, // FIXME: why -33 here?\n        row: pos.y - 33,\n        button: but,\n        action,\n        ctrl: ev.ctrlKey,\n        alt: ev.altKey,\n        shift: ev.shiftKey\n      });\n    }\n\n    /**\n     * Event listener state handling.\n     * We listen to the onProtocolChange event of CoreMouseService and put\n     * requested listeners in `requestedEvents`. With this the listeners\n     * have all bits to do the event listener juggling.\n     * Note: 'mousedown' currently is \"always on\" and not managed\n     * by onProtocolChange.\n     */\n    const requestedEvents: {[key: string]: ((ev: Event) => void) | null} = {\n      mouseup: null,\n      wheel: null,\n      mousedrag: null,\n      mousemove: null\n    };\n    const eventListeners: {[key: string]: (ev: Event) => void} = {\n      mouseup: (ev: MouseEvent) => {\n        sendEvent(ev);\n        if (!ev.buttons) {\n          // if no other button is held remove global handlers\n          this._document.removeEventListener('mouseup', requestedEvents.mouseup);\n          if (requestedEvents.mousedrag) {\n            this._document.removeEventListener('mousemove', requestedEvents.mousedrag);\n          }\n        }\n        return this.cancel(ev);\n      },\n      wheel: (ev: WheelEvent) => {\n        sendEvent(ev);\n        ev.preventDefault();\n        return this.cancel(ev);\n      },\n      mousedrag: (ev: MouseEvent) => {\n        // deal only with move while a button is held\n        if (ev.buttons) {\n          sendEvent(ev);\n        }\n      },\n      mousemove: (ev: MouseEvent) => {\n        // deal only with move without any button\n        if (!ev.buttons) {\n          sendEvent(ev);\n        }\n      }\n    };\n    this._coreMouseService.onProtocolChange(events => {\n      // apply global changes on events\n      this.mouseEvents = events;\n      if (events) {\n        if (this.optionsService.options.logLevel === 'debug') {\n          this._logService.debug('Binding to mouse events:', this._coreMouseService.explainEvents(events));\n        }\n        this.element.classList.add('enable-mouse-events');\n        this._selectionService.disable();\n      } else {\n        this._logService.debug('Unbinding from mouse events.');\n        this.element.classList.remove('enable-mouse-events');\n        this._selectionService.enable();\n      }\n\n      // add/remove handlers from requestedEvents\n\n      if (!(events & CoreMouseEventType.MOVE)) {\n        el.removeEventListener('mousemove', requestedEvents.mousemove);\n        requestedEvents.mousemove = null;\n      } else if (!requestedEvents.mousemove) {\n        el.addEventListener('mousemove', eventListeners.mousemove);\n        requestedEvents.mousemove = eventListeners.mousemove;\n      }\n\n      if (!(events & CoreMouseEventType.WHEEL)) {\n        el.removeEventListener('wheel', requestedEvents.wheel);\n        requestedEvents.wheel = null;\n      } else if (!requestedEvents.wheel) {\n        el.addEventListener('wheel', eventListeners.wheel);\n        requestedEvents.wheel = eventListeners.wheel;\n      }\n\n      if (!(events & CoreMouseEventType.UP)) {\n        this._document.removeEventListener('mouseup', requestedEvents.mouseup);\n        requestedEvents.mouseup = null;\n      } else if (!requestedEvents.mouseup) {\n        requestedEvents.mouseup = eventListeners.mouseup;\n      }\n\n      if (!(events & CoreMouseEventType.DRAG)) {\n        this._document.removeEventListener('mousemove', requestedEvents.mousedrag);\n        requestedEvents.mousedrag = null;\n      } else if (!requestedEvents.mousedrag) {\n        requestedEvents.mousedrag = eventListeners.mousedrag;\n      }\n    });\n    // force initial onProtocolChange so we dont miss early mouse requests\n    this._coreMouseService.activeProtocol = this._coreMouseService.activeProtocol;\n\n    /**\n     * \"Always on\" event listeners.\n     */\n    this.register(addDisposableDomListener(el, 'mousedown', (ev: MouseEvent) => {\n      ev.preventDefault();\n      this.focus();\n\n      // Don't send the mouse button to the pty if mouse events are disabled or\n      // if the selection manager is having selection forced (ie. a modifier is\n      // held).\n      if (!this.mouseEvents || this._selectionService.shouldForceSelection(ev)) {\n        return;\n      }\n\n      sendEvent(ev);\n\n      // Register additional global handlers which should keep reporting outside\n      // of the terminal element.\n      // Note: Other emulators also do this for 'mousedown' while a button\n      // is held, we currently limit 'mousedown' to the terminal only.\n      if (requestedEvents.mouseup) {\n        this._document.addEventListener('mouseup', requestedEvents.mouseup);\n      }\n      if (requestedEvents.mousedrag) {\n        this._document.addEventListener('mousemove', requestedEvents.mousedrag);\n      }\n\n      return this.cancel(ev);\n    }));\n\n    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {\n      if (!requestedEvents.wheel) {\n        // Convert wheel events into up/down events when the buffer does not have scrollback, this\n        // enables scrolling in apps hosted in the alt buffer such as vim or tmux.\n        if (!this.buffer.hasScrollback) {\n          const amount = this.viewport.getLinesScrolled(ev);\n\n          // Do nothing if there's no vertical scroll\n          if (amount === 0) {\n            return;\n          }\n\n          // Construct and send sequences\n          const sequence = C0.ESC + (this._coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + ( ev.deltaY < 0 ? 'A' : 'B');\n          let data = '';\n          for (let i = 0; i < Math.abs(amount); i++) {\n            data += sequence;\n          }\n          this._coreService.triggerDataEvent(data, true);\n        }\n        return;\n      }\n    }));\n\n    // allow wheel scrolling in\n    // the shell for example\n    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {\n      if (requestedEvents.wheel) return;\n      if (!this.viewport.onWheel(ev)) {\n        return this.cancel(ev);\n      }\n    }));\n\n    this.register(addDisposableDomListener(el, 'touchstart', (ev: TouchEvent) => {\n      if (this.mouseEvents) return;\n      this.viewport.onTouchStart(ev);\n      return this.cancel(ev);\n    }));\n\n    this.register(addDisposableDomListener(el, 'touchmove', (ev: TouchEvent) => {\n      if (this.mouseEvents) return;\n      if (!this.viewport.onTouchMove(ev)) {\n        return this.cancel(ev);\n      }\n    }));\n  }\n\n\n  /**\n   * Tells the renderer to refresh terminal content between two rows (inclusive) at the next\n   * opportunity.\n   * @param start The row to start from (between 0 and this.rows - 1).\n   * @param end The row to end at (between start and this.rows - 1).\n   */\n  public refresh(start: number, end: number): void {\n    if (this._renderService) {\n      this._renderService.refreshRows(start, end);\n    }\n  }\n\n  /**\n   * Queues linkification for the specified rows.\n   * @param start The row to start from (between 0 and this.rows - 1).\n   * @param end The row to end at (between start and this.rows - 1).\n   */\n  private _queueLinkification(start: number, end: number): void {\n    if (this.linkifier) {\n      this.linkifier.linkifyRows(start, end);\n    }\n  }\n\n  /**\n   * Change the cursor style for different selection modes\n   */\n  public updateCursorStyle(ev: KeyboardEvent): void {\n    if (this._selectionService && this._selectionService.shouldColumnSelect(ev)) {\n      this.element.classList.add('column-select');\n    } else {\n      this.element.classList.remove('column-select');\n    }\n  }\n\n  /**\n   * Display the cursor element\n   */\n  public showCursor(): void {\n    if (!this.cursorState) {\n      this.cursorState = 1;\n      this.refresh(this.buffer.y, this.buffer.y);\n    }\n  }\n\n  /**\n   * Scroll the terminal down 1 row, creating a blank line.\n   * @param isWrapped Whether the new line is wrapped from the previous line.\n   */\n  public scroll(isWrapped: boolean = false): void {\n    let newLine: IBufferLine;\n    newLine = this._blankLine;\n    const eraseAttr = this.eraseAttrData();\n    if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) {\n      newLine = this.buffer.getBlankLine(eraseAttr, isWrapped);\n      this._blankLine = newLine;\n    }\n    newLine.isWrapped = isWrapped;\n\n    const topRow = this.buffer.ybase + this.buffer.scrollTop;\n    const bottomRow = this.buffer.ybase + this.buffer.scrollBottom;\n\n    if (this.buffer.scrollTop === 0) {\n      // Determine whether the buffer is going to be trimmed after insertion.\n      const willBufferBeTrimmed = this.buffer.lines.isFull;\n\n      // Insert the line using the fastest method\n      if (bottomRow === this.buffer.lines.length - 1) {\n        if (willBufferBeTrimmed) {\n          this.buffer.lines.recycle().copyFrom(newLine);\n        } else {\n          this.buffer.lines.push(newLine.clone());\n        }\n      } else {\n        this.buffer.lines.splice(bottomRow + 1, 0, newLine.clone());\n      }\n\n      // Only adjust ybase and ydisp when the buffer is not trimmed\n      if (!willBufferBeTrimmed) {\n        this.buffer.ybase++;\n        // Only scroll the ydisp with ybase if the user has not scrolled up\n        if (!this._userScrolling) {\n          this.buffer.ydisp++;\n        }\n      } else {\n        // When the buffer is full and the user has scrolled up, keep the text\n        // stable unless ydisp is right at the top\n        if (this._userScrolling) {\n          this.buffer.ydisp = Math.max(this.buffer.ydisp - 1, 0);\n        }\n      }\n    } else {\n      // scrollTop is non-zero which means no line will be going to the\n      // scrollback, instead we can just shift them in-place.\n      const scrollRegionHeight = bottomRow - topRow + 1/*as it's zero-based*/;\n      this.buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1);\n      this.buffer.lines.set(bottomRow, newLine.clone());\n    }\n\n    // Move the viewport to the bottom of the buffer unless the user is\n    // scrolling.\n    if (!this._userScrolling) {\n      this.buffer.ydisp = this.buffer.ybase;\n    }\n\n    // Flag rows that need updating\n    this._dirtyRowService.markRangeDirty(this.buffer.scrollTop, this.buffer.scrollBottom);\n\n    this._onScroll.fire(this.buffer.ydisp);\n  }\n\n  /**\n   * Scroll the display of the terminal\n   * @param disp The number of lines to scroll down (negative scroll up).\n   * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used\n   * to avoid unwanted events being handled by the viewport when the event was triggered from the\n   * viewport originally.\n   */\n  public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n    if (disp < 0) {\n      if (this.buffer.ydisp === 0) {\n        return;\n      }\n      this._userScrolling = true;\n    } else if (disp + this.buffer.ydisp >= this.buffer.ybase) {\n      this._userScrolling = false;\n    }\n\n    const oldYdisp = this.buffer.ydisp;\n    this.buffer.ydisp = Math.max(Math.min(this.buffer.ydisp + disp, this.buffer.ybase), 0);\n\n    // No change occurred, don't trigger scroll/refresh\n    if (oldYdisp === this.buffer.ydisp) {\n      return;\n    }\n\n    if (!suppressScrollEvent) {\n      this._onScroll.fire(this.buffer.ydisp);\n    }\n\n    this.refresh(0, this.rows - 1);\n  }\n\n  /**\n   * Scroll the display of the terminal by a number of pages.\n   * @param pageCount The number of pages to scroll (negative scrolls up).\n   */\n  public scrollPages(pageCount: number): void {\n    this.scrollLines(pageCount * (this.rows - 1));\n  }\n\n  /**\n   * Scrolls the display of the terminal to the top.\n   */\n  public scrollToTop(): void {\n    this.scrollLines(-this.buffer.ydisp);\n  }\n\n  /**\n   * Scrolls the display of the terminal to the bottom.\n   */\n  public scrollToBottom(): void {\n    this.scrollLines(this.buffer.ybase - this.buffer.ydisp);\n  }\n\n  public scrollToLine(line: number): void {\n    const scrollAmount = line - this.buffer.ydisp;\n    if (scrollAmount !== 0) {\n      this.scrollLines(scrollAmount);\n    }\n  }\n\n  public paste(data: string): void {\n    paste(data, this.textarea, this.bracketedPasteMode, this._coreService);\n  }\n\n  /**\n   * Attaches a custom key event handler which is run before keys are processed,\n   * giving consumers of xterm.js ultimate control as to what keys should be\n   * processed by the terminal and what keys should not.\n   * @param customKeyEventHandler The custom KeyboardEvent handler to attach.\n   * This is a function that takes a KeyboardEvent, allowing consumers to stop\n   * propagation and/or prevent the default action. The function returns whether\n   * the event should be processed by xterm.js.\n   */\n  public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void {\n    this._customKeyEventHandler = customKeyEventHandler;\n  }\n\n  /** Add handler for ESC escape sequence. See xterm.d.ts for details. */\n  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {\n    return this._inputHandler.addEscHandler(id, callback);\n  }\n\n  /** Add handler for DCS escape sequence. See xterm.d.ts for details. */\n  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {\n    return this._inputHandler.addDcsHandler(id, callback);\n  }\n\n  /** Add handler for CSI escape sequence. See xterm.d.ts for details. */\n  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {\n    return this._inputHandler.addCsiHandler(id, callback);\n  }\n  /** Add handler for OSC escape sequence. See xterm.d.ts for details. */\n  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {\n    return this._inputHandler.addOscHandler(ident, callback);\n  }\n\n  /**\n   * Registers a link matcher, allowing custom link patterns to be matched and\n   * handled.\n   * @param regex The regular expression to search for, specifically\n   * this searches the textContent of the rows. You will want to use \\s to match\n   * a space ' ' character for example.\n   * @param handler The callback when the link is called.\n   * @param options Options for the link matcher.\n   * @return The ID of the new matcher, this can be used to deregister.\n   */\n  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?: ILinkMatcherOptions): number {\n    const matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);\n    this.refresh(0, this.rows - 1);\n    return matcherId;\n  }\n\n  /**\n   * Deregisters a link matcher if it has been registered.\n   * @param matcherId The link matcher's ID (returned after register)\n   */\n  public deregisterLinkMatcher(matcherId: number): void {\n    if (this.linkifier.deregisterLinkMatcher(matcherId)) {\n      this.refresh(0, this.rows - 1);\n    }\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n    const joinerId = this._renderService.registerCharacterJoiner(handler);\n    this.refresh(0, this.rows - 1);\n    return joinerId;\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): void {\n    if (this._renderService.deregisterCharacterJoiner(joinerId)) {\n      this.refresh(0, this.rows - 1);\n    }\n  }\n\n  public get markers(): IMarker[] {\n    return this.buffer.markers;\n  }\n\n  public addMarker(cursorYOffset: number): IMarker {\n    // Disallow markers on the alt buffer\n    if (this.buffer !== this.buffers.normal) {\n      return;\n    }\n\n    return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);\n  }\n\n  /**\n   * Gets whether the terminal has an active selection.\n   */\n  public hasSelection(): boolean {\n    return this._selectionService ? this._selectionService.hasSelection : false;\n  }\n\n  /**\n   * Selects text within the terminal.\n   * @param column The column the selection starts at..\n   * @param row The row the selection starts at.\n   * @param length The length of the selection.\n   */\n  public select(column: number, row: number, length: number): void {\n    this._selectionService.setSelection(column, row, length);\n  }\n\n  /**\n   * Gets the terminal's current selection, this is useful for implementing copy\n   * behavior outside of xterm.js.\n   */\n  public getSelection(): string {\n    return this._selectionService ? this._selectionService.selectionText : '';\n  }\n\n  public getSelectionPosition(): ISelectionPosition | undefined {\n    if (!this._selectionService.hasSelection) {\n      return undefined;\n    }\n\n    return {\n      startColumn: this._selectionService.selectionStart[0],\n      startRow: this._selectionService.selectionStart[1],\n      endColumn: this._selectionService.selectionEnd[0],\n      endRow: this._selectionService.selectionEnd[1]\n    };\n  }\n\n  /**\n   * Clears the current terminal selection.\n   */\n  public clearSelection(): void {\n    if (this._selectionService) {\n      this._selectionService.clearSelection();\n    }\n  }\n\n  /**\n   * Selects all text within the terminal.\n   */\n  public selectAll(): void {\n    if (this._selectionService) {\n      this._selectionService.selectAll();\n    }\n  }\n\n  public selectLines(start: number, end: number): void {\n    if (this._selectionService) {\n      this._selectionService.selectLines(start, end);\n    }\n  }\n\n  /**\n   * Handle a keydown event\n   * Key Resources:\n   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n   * @param ev The keydown event to be handled.\n   */\n  protected _keyDown(event: KeyboardEvent): boolean {\n    this._keyDownHandled = false;\n\n    if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {\n      return false;\n    }\n\n    if (!this._compositionHelper.keydown(event)) {\n      if (this.buffer.ybase !== this.buffer.ydisp) {\n        this.scrollToBottom();\n      }\n      return false;\n    }\n\n    const result = evaluateKeyboardEvent(event, this._coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);\n\n    this.updateCursorStyle(event);\n\n    if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {\n      const scrollCount = this.rows - 1;\n      this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);\n      return this.cancel(event, true);\n    }\n\n    if (result.type === KeyboardResultType.SELECT_ALL) {\n      this.selectAll();\n    }\n\n    if (this._isThirdLevelShift(this.browser, event)) {\n      return true;\n    }\n\n    if (result.cancel) {\n      // The event is canceled at the end already, is this necessary?\n      this.cancel(event, true);\n    }\n\n    if (!result.key) {\n      return true;\n    }\n\n    // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers\n    // will announce deleted characters. This will not work 100% of the time but it should cover\n    // most scenarios.\n    if (result.key === C0.ETX || result.key === C0.CR) {\n      this.textarea.value = '';\n    }\n\n    this._onKey.fire({ key: result.key, domEvent: event });\n    this.showCursor();\n    this._coreService.triggerDataEvent(result.key, true);\n\n    // Cancel events when not in screen reader mode so events don't get bubbled up and handled by\n    // other listeners. When screen reader mode is enabled, this could cause issues if the event\n    // is handled at a higher level, this is a compromise in order to echo keys to the screen\n    // reader.\n    if (!this.optionsService.options.screenReaderMode) {\n      return this.cancel(event, true);\n    }\n\n    this._keyDownHandled = true;\n  }\n\n  private _isThirdLevelShift(browser: IBrowser, ev: IKeyboardEvent): boolean {\n    const thirdLevelKey =\n        (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||\n        (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);\n\n    if (ev.type === 'keypress') {\n      return thirdLevelKey;\n    }\n\n    // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)\n    return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);\n  }\n\n  /**\n   * Set the G level of the terminal\n   * @param g\n   */\n  public setgLevel(g: number): void {\n    this.glevel = g;\n    this.charset = this.charsets[g];\n  }\n\n  /**\n   * Set the charset for the given G level of the terminal\n   * @param g\n   * @param charset\n   */\n  public setgCharset(g: number, charset: ICharset): void {\n    this.charsets[g] = charset;\n    if (this.glevel === g) {\n      this.charset = charset;\n    }\n  }\n\n  protected _keyUp(ev: KeyboardEvent): void {\n    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n      return;\n    }\n\n    if (!wasModifierKeyOnlyEvent(ev)) {\n      this.focus();\n    }\n\n    this.updateCursorStyle(ev);\n  }\n\n  /**\n   * Handle a keypress event.\n   * Key Resources:\n   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n   * @param ev The keypress event to be handled.\n   */\n  protected _keyPress(ev: KeyboardEvent): boolean {\n    let key;\n\n    if (this._keyDownHandled) {\n      return false;\n    }\n\n    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n      return false;\n    }\n\n    this.cancel(ev);\n\n    if (ev.charCode) {\n      key = ev.charCode;\n    } else if (ev.which === null || ev.which === undefined) {\n      key = ev.keyCode;\n    } else if (ev.which !== 0 && ev.charCode !== 0) {\n      key = ev.which;\n    } else {\n      return false;\n    }\n\n    if (!key || (\n      (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev)\n    )) {\n      return false;\n    }\n\n    key = String.fromCharCode(key);\n\n    this._onKey.fire({ key, domEvent: ev });\n    this.showCursor();\n    this._coreService.triggerDataEvent(key, true);\n\n    return true;\n  }\n\n  /**\n   * Ring the bell.\n   * Note: We could do sweet things with webaudio here\n   */\n  public bell(): void {\n    if (this._soundBell()) {\n      this._soundService.playBellSound();\n    }\n\n    if (this._visualBell()) {\n      this.element.classList.add('visual-bell-active');\n      clearTimeout(this._visualBellTimer);\n      this._visualBellTimer = window.setTimeout(() => {\n        this.element.classList.remove('visual-bell-active');\n      }, 200);\n    }\n  }\n\n  /**\n   * Resizes the terminal.\n   *\n   * @param x The number of columns to resize to.\n   * @param y The number of rows to resize to.\n   */\n  public resize(x: number, y: number): void {\n    if (isNaN(x) || isNaN(y)) {\n      return;\n    }\n\n    if (x === this.cols && y === this.rows) {\n      // Check if we still need to measure the char size (fixes #785).\n      if (this._charSizeService && !this._charSizeService.hasValidSize) {\n        this._charSizeService.measure();\n      }\n      return;\n    }\n\n    if (x < MINIMUM_COLS) x = MINIMUM_COLS;\n    if (y < MINIMUM_ROWS) y = MINIMUM_ROWS;\n\n    this.buffers.resize(x, y);\n\n    this._bufferService.resize(x, y);\n    this.buffers.setupTabStops(this.cols);\n\n    if (this._charSizeService) {\n      this._charSizeService.measure();\n    }\n\n    // Sync the scroll area to make sure scroll events don't fire and scroll the viewport to an\n    // invalid location\n    this.viewport.syncScrollArea(true);\n\n    this.refresh(0, this.rows - 1);\n    this._onResize.fire({ cols: x, rows: y });\n  }\n\n  /**\n   * Clear the entire buffer, making the prompt line the new first line.\n   */\n  public clear(): void {\n    if (this.buffer.ybase === 0 && this.buffer.y === 0) {\n      // Don't clear if it's already clear\n      return;\n    }\n    this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y));\n    this.buffer.lines.length = 1;\n    this.buffer.ydisp = 0;\n    this.buffer.ybase = 0;\n    this.buffer.y = 0;\n    for (let i = 1; i < this.rows; i++) {\n      this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));\n    }\n    this.refresh(0, this.rows - 1);\n    this._onScroll.fire(this.buffer.ydisp);\n  }\n\n  /**\n   * Evaluate if the current terminal is the given argument.\n   * @param term The terminal name to evaluate\n   */\n  public is(term: string): boolean {\n    return (this.options.termName + '').indexOf(term) === 0;\n  }\n\n  /**\n   * Emit the data event and populate the given data.\n   * @param data The data to populate in the event.\n   */\n  // public handler(data: string): void {\n  //   // Prevents all events to pty process if stdin is disabled\n  //   if (this.options.disableStdin) {\n  //     return;\n  //   }\n\n  //   // Clear the selection if the selection manager is available and has an active selection\n  //   if (this.selectionService && this.selectionService.hasSelection) {\n  //     this.selectionService.clearSelection();\n  //   }\n\n  //   // Input is being sent to the terminal, the terminal should focus the prompt.\n  //   if (this.buffer.ybase !== this.buffer.ydisp) {\n  //     this.scrollToBottom();\n  //   }\n  //   this._onData.fire(data);\n  // }\n\n  /**\n   * Emit the 'title' event and populate the given title.\n   * @param title The title to populate in the event.\n   */\n  public handleTitle(title: string): void {\n    this._onTitleChange.fire(title);\n  }\n\n  /**\n   * Reset terminal.\n   * Note: Calling this directly from JS is synchronous but does not clear\n   * input buffers and does not reset the parser, thus the terminal will\n   * continue to apply pending input data.\n   * If you need in band reset (synchronous with input data) consider\n   * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).\n   */\n  public reset(): void {\n    /**\n     * Since _setup handles a full terminal creation, we have to carry forward\n     * a few things that should not reset.\n     */\n    this.options.rows = this.rows;\n    this.options.cols = this.cols;\n    const customKeyEventHandler = this._customKeyEventHandler;\n    const inputHandler = this._inputHandler;\n    const cursorState = this.cursorState;\n    const userScrolling = this._userScrolling;\n\n    this._setup();\n    this._bufferService.reset();\n    this._coreService.reset();\n    this._coreMouseService.reset();\n    if (this._selectionService) {\n      this._selectionService.reset();\n    }\n\n    // reattach\n    this._customKeyEventHandler = customKeyEventHandler;\n    this._inputHandler = inputHandler;\n    this.cursorState = cursorState;\n    this._userScrolling = userScrolling;\n\n    // do a full screen refresh\n    this.refresh(0, this.rows - 1);\n    if (this.viewport) {\n      this.viewport.syncScrollArea();\n    }\n  }\n\n  // TODO: Remove cancel function and cancelEvents option\n  public cancel(ev: Event, force?: boolean): boolean {\n    if (!this.options.cancelEvents && !force) {\n      return;\n    }\n    ev.preventDefault();\n    ev.stopPropagation();\n    return false;\n  }\n\n  private _visualBell(): boolean {\n    return false;\n    // return this.options.bellStyle === 'visual' ||\n    //     this.options.bellStyle === 'both';\n  }\n\n  private _soundBell(): boolean {\n    return this.options.bellStyle === 'sound';\n    // return this.options.bellStyle === 'sound' ||\n    //     this.options.bellStyle === 'both';\n  }\n\n  public write(data: string | Uint8Array, callback?: () => void): void {\n    this._writeBuffer.write(data, callback);\n  }\n\n  public writeSync(data: string | Uint8Array): void {\n    this._writeBuffer.writeSync(data);\n  }\n}\n\n/**\n * Helpers\n */\n\nfunction wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {\n  return ev.keyCode === 16 || // Shift\n    ev.keyCode === 17 || // Ctrl\n    ev.keyCode === 18; // Alt\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharSizeService } from 'browser/services/Services';\nimport { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';\n\ninterface IPosition {\n  start: number;\n  end: number;\n}\n\n/**\n * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend\n * events, displaying the in-progress composition to the UI and forwarding the final composition\n * to the handler.\n */\nexport class CompositionHelper {\n  /**\n   * Whether input composition is currently happening, eg. via a mobile keyboard, speech input or\n   * IME. This variable determines whether the compositionText should be displayed on the UI.\n   */\n  private _isComposing: boolean;\n\n  /**\n   * The position within the input textarea's value of the current composition.\n   */\n  private _compositionPosition: IPosition;\n\n  /**\n   * Whether a composition is in the process of being sent, setting this to false will cancel any\n   * in-progress composition.\n   */\n  private _isSendingComposition: boolean;\n\n  constructor(\n    private readonly _textarea: HTMLTextAreaElement,\n    private readonly _compositionView: HTMLElement,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @IOptionsService private readonly _optionsService: IOptionsService,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService,\n    @ICoreService private readonly _coreService: ICoreService\n  ) {\n    this._isComposing = false;\n    this._isSendingComposition = false;\n    this._compositionPosition = { start: 0, end: 0 };\n  }\n\n  /**\n   * Handles the compositionstart event, activating the composition view.\n   */\n  public compositionstart(): void {\n    this._isComposing = true;\n    this._compositionPosition.start = this._textarea.value.length;\n    this._compositionView.textContent = '';\n    this._compositionView.classList.add('active');\n  }\n\n  /**\n   * Handles the compositionupdate event, updating the composition view.\n   * @param ev The event.\n   */\n  public compositionupdate(ev: CompositionEvent): void {\n    this._compositionView.textContent = ev.data;\n    this.updateCompositionElements();\n    setTimeout(() => {\n      this._compositionPosition.end = this._textarea.value.length;\n    }, 0);\n  }\n\n  /**\n   * Handles the compositionend event, hiding the composition view and sending the composition to\n   * the handler.\n   */\n  public compositionend(): void {\n    this._finalizeComposition(true);\n  }\n\n  /**\n   * Handles the keydown event, routing any necessary events to the CompositionHelper functions.\n   * @param ev The keydown event.\n   * @return Whether the Terminal should continue processing the keydown event.\n   */\n  public keydown(ev: KeyboardEvent): boolean {\n    if (this._isComposing || this._isSendingComposition) {\n      if (ev.keyCode === 229) {\n        // Continue composing if the keyCode is the \"composition character\"\n        return false;\n      } else if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {\n        // Continue composing if the keyCode is a modifier key\n        return false;\n      }\n      // Finish composition immediately. This is mainly here for the case where enter is\n      // pressed and the handler needs to be triggered before the command is executed.\n      this._finalizeComposition(false);\n    }\n\n    if (ev.keyCode === 229) {\n      // If the \"composition character\" is used but gets to this point it means a non-composition\n      // character (eg. numbers and punctuation) was pressed when the IME was active.\n      this._handleAnyTextareaChanges();\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Finalizes the composition, resuming regular input actions. This is called when a composition\n   * is ending.\n   * @param waitForPropagation Whether to wait for events to propagate before sending\n   *   the input. This should be false if a non-composition keystroke is entered before the\n   *   compositionend event is triggered, such as enter, so that the composition is sent before\n   *   the command is executed.\n   */\n  private _finalizeComposition(waitForPropagation: boolean): void {\n    this._compositionView.classList.remove('active');\n    this._isComposing = false;\n    this._clearTextareaPosition();\n\n    if (!waitForPropagation) {\n      // Cancel any delayed composition send requests and send the input immediately.\n      this._isSendingComposition = false;\n      const input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);\n      this._coreService.triggerDataEvent(input, true);\n    } else {\n      // Make a deep copy of the composition position here as a new compositionstart event may\n      // fire before the setTimeout executes.\n      const currentCompositionPosition = {\n        start: this._compositionPosition.start,\n        end: this._compositionPosition.end\n      };\n\n      // Since composition* events happen before the changes take place in the textarea on most\n      // browsers, use a setTimeout with 0ms time to allow the native compositionend event to\n      // complete. This ensures the correct character is retrieved.\n      // This solution was used because:\n      // - The compositionend event's data property is unreliable, at least on Chromium\n      // - The last compositionupdate event's data property does not always accurately describe\n      //   the character, a counter example being Korean where an ending consonsant can move to\n      //   the following character if the following input is a vowel.\n      this._isSendingComposition = true;\n      setTimeout(() => {\n        // Ensure that the input has not already been sent\n        if (this._isSendingComposition) {\n          this._isSendingComposition = false;\n          let input;\n          if (this._isComposing) {\n            // Use the end position to get the string if a new composition has started.\n            input = this._textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);\n          } else {\n            // Don't use the end position here in order to pick up any characters after the\n            // composition has finished, for example when typing a non-composition character\n            // (eg. 2) after a composition character.\n            input = this._textarea.value.substring(currentCompositionPosition.start);\n          }\n          this._coreService.triggerDataEvent(input, true);\n        }\n      }, 0);\n    }\n  }\n\n  /**\n   * Apply any changes made to the textarea after the current event chain is allowed to complete.\n   * This should be called when not currently composing but a keydown event with the \"composition\n   * character\" (229) is triggered, in order to allow non-composition text to be entered when an\n   * IME is active.\n   */\n  private _handleAnyTextareaChanges(): void {\n    const oldValue = this._textarea.value;\n    setTimeout(() => {\n      // Ignore if a composition has started since the timeout\n      if (!this._isComposing) {\n        const newValue = this._textarea.value;\n        const diff = newValue.replace(oldValue, '');\n        if (diff.length > 0) {\n          this._coreService.triggerDataEvent(diff, true);\n        }\n      }\n    }, 0);\n  }\n\n  /**\n   * Positions the composition view on top of the cursor and the textarea just below it (so the\n   * IME helper dialog is positioned correctly).\n   * @param dontRecurse Whether to use setTimeout to recursively trigger another update, this is\n   *   necessary as the IME events across browsers are not consistently triggered.\n   */\n  public updateCompositionElements(dontRecurse?: boolean): void {\n    if (!this._isComposing) {\n      return;\n    }\n\n    if (this._bufferService.buffer.isCursorInViewport) {\n      const cellHeight = Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);\n      const cursorTop = this._bufferService.buffer.y * cellHeight;\n      const cursorLeft = this._bufferService.buffer.x * this._charSizeService.width;\n\n      this._compositionView.style.left = cursorLeft + 'px';\n      this._compositionView.style.top = cursorTop + 'px';\n      this._compositionView.style.height = cellHeight + 'px';\n      this._compositionView.style.lineHeight = cellHeight + 'px';\n      this._compositionView.style.fontFamily = this._optionsService.options.fontFamily;\n      this._compositionView.style.fontSize = this._optionsService.options.fontSize + 'px';\n      // Sync the textarea to the exact position of the composition view so the IME knows where the\n      // text is.\n      const compositionViewBounds = this._compositionView.getBoundingClientRect();\n      this._textarea.style.left = cursorLeft + 'px';\n      this._textarea.style.top = cursorTop + 'px';\n      this._textarea.style.width = compositionViewBounds.width + 'px';\n      this._textarea.style.height = compositionViewBounds.height + 'px';\n      this._textarea.style.lineHeight = compositionViewBounds.height + 'px';\n    }\n\n    if (!dontRecurse) {\n      setTimeout(() => this.updateCompositionElements(true), 0);\n    }\n  }\n\n  /**\n   * Clears the textarea's position so that the cursor does not blink on IE.\n   * @private\n   */\n  private _clearTextareaPosition(): void {\n    this._textarea.style.left = '';\n    this._textarea.style.top = '';\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'common/Lifecycle';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { IColorSet, IViewport } from 'browser/Types';\nimport { ICharSizeService, IRenderService } from 'browser/services/Services';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\nconst FALLBACK_SCROLL_BAR_WIDTH = 15;\n\n/**\n * Represents the viewport of a terminal, the visible area within the larger buffer of output.\n * Logic for the virtual scroll bar is included in this object.\n */\nexport class Viewport extends Disposable implements IViewport {\n  public scrollBarWidth: number = 0;\n  private _currentRowHeight: number = 0;\n  private _lastRecordedBufferLength: number = 0;\n  private _lastRecordedViewportHeight: number = 0;\n  private _lastRecordedBufferHeight: number = 0;\n  private _lastTouchY: number = 0;\n  private _lastScrollTop: number = 0;\n\n  // Stores a partial line amount when scrolling, this is used to keep track of how much of a line\n  // is scrolled so we can \"scroll\" over partial lines and feel natural on touchpads. This is a\n  // quick fix and could have a more robust solution in place that reset the value when needed.\n  private _wheelPartialScroll: number = 0;\n\n  private _refreshAnimationFrame: number | null = null;\n  private _ignoreNextScrollEvent: boolean = false;\n\n  constructor(\n    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,\n    private readonly _viewportElement: HTMLElement,\n    private readonly _scrollArea: HTMLElement,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @IOptionsService private readonly _optionsService: IOptionsService,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService,\n    @IRenderService private readonly _renderService: IRenderService\n  ) {\n    super();\n\n    // Measure the width of the scrollbar. If it is 0 we can assume it's an OSX overlay scrollbar.\n    // Unfortunately the overlay scrollbar would be hidden underneath the screen element in that case,\n    // therefore we account for a standard amount to make it visible\n    this.scrollBarWidth = (this._viewportElement.offsetWidth - this._scrollArea.offsetWidth) || FALLBACK_SCROLL_BAR_WIDTH;\n    this.register(addDisposableDomListener(this._viewportElement, 'scroll', this._onScroll.bind(this)));\n\n    // Perform this async to ensure the ICharSizeService is ready.\n    setTimeout(() => this.syncScrollArea(), 0);\n  }\n\n  public onThemeChange(colors: IColorSet): void {\n    this._viewportElement.style.backgroundColor = colors.background.css;\n  }\n\n  /**\n   * Refreshes row height, setting line-height, viewport height and scroll area height if\n   * necessary.\n   */\n  private _refresh(immediate: boolean): void {\n    if (immediate) {\n      this._innerRefresh();\n      if (this._refreshAnimationFrame !== null) {\n        cancelAnimationFrame(this._refreshAnimationFrame);\n      }\n      return;\n    }\n    if (this._refreshAnimationFrame === null) {\n      this._refreshAnimationFrame = requestAnimationFrame(() => this._innerRefresh());\n    }\n  }\n\n  private _innerRefresh(): void {\n    if (this._charSizeService.height > 0) {\n      this._currentRowHeight = this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio;\n      this._lastRecordedViewportHeight = this._viewportElement.offsetHeight;\n      const newBufferHeight = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._renderService.dimensions.canvasHeight);\n      if (this._lastRecordedBufferHeight !== newBufferHeight) {\n        this._lastRecordedBufferHeight = newBufferHeight;\n        this._scrollArea.style.height = this._lastRecordedBufferHeight + 'px';\n      }\n    }\n\n    // Sync scrollTop\n    const scrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;\n    if (this._viewportElement.scrollTop !== scrollTop) {\n      // Ignore the next scroll event which will be triggered by setting the scrollTop as we do not\n      // want this event to scroll the terminal\n      this._ignoreNextScrollEvent = true;\n      this._viewportElement.scrollTop = scrollTop;\n    }\n\n    this._refreshAnimationFrame = null;\n  }\n  /**\n   * Updates dimensions and synchronizes the scroll area if necessary.\n   */\n  public syncScrollArea(immediate: boolean = false): void {\n    // If buffer height changed\n    if (this._lastRecordedBufferLength !== this._bufferService.buffer.lines.length) {\n      this._lastRecordedBufferLength = this._bufferService.buffer.lines.length;\n      this._refresh(immediate);\n      return;\n    }\n\n    // If viewport height changed\n    if (this._lastRecordedViewportHeight !== this._renderService.dimensions.canvasHeight) {\n      this._refresh(immediate);\n      return;\n    }\n\n    // If the buffer position doesn't match last scroll top\n    const newScrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;\n    if (this._lastScrollTop !== newScrollTop) {\n      this._refresh(immediate);\n      return;\n    }\n\n    // If element's scroll top changed, this can happen when hiding the element\n    if (this._lastScrollTop !== this._viewportElement.scrollTop) {\n      this._refresh(immediate);\n      return;\n    }\n\n    // If row height changed\n    if (this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio !== this._currentRowHeight) {\n      this._refresh(immediate);\n      return;\n    }\n  }\n\n  /**\n   * Handles scroll events on the viewport, calculating the new viewport and requesting the\n   * terminal to scroll to it.\n   * @param ev The scroll event.\n   */\n  private _onScroll(ev: Event): void {\n    // Record current scroll top position\n    this._lastScrollTop = this._viewportElement.scrollTop;\n\n    // Don't attempt to scroll if the element is not visible, otherwise scrollTop will be corrupt\n    // which causes the terminal to scroll the buffer to the top\n    if (!this._viewportElement.offsetParent) {\n      return;\n    }\n\n    // Ignore the event if it was flagged to ignore (when the source of the event is from Viewport)\n    if (this._ignoreNextScrollEvent) {\n      this._ignoreNextScrollEvent = false;\n      return;\n    }\n\n    const newRow = Math.round(this._lastScrollTop / this._currentRowHeight);\n    const diff = newRow - this._bufferService.buffer.ydisp;\n    this._scrollLines(diff, true);\n  }\n\n  /**\n   * Handles bubbling of scroll event in case the viewport has reached top or bottom\n   * @param ev The scroll event.\n   * @param amount The amount scrolled\n   */\n  private _bubbleScroll(ev: Event, amount: number): boolean {\n    const scrollPosFromTop = this._viewportElement.scrollTop + this._lastRecordedViewportHeight;\n    if ((amount < 0 && this._viewportElement.scrollTop !== 0) ||\n        (amount > 0 &&  scrollPosFromTop < this._lastRecordedBufferHeight)) {\n      if (ev.cancelable) {\n        ev.preventDefault();\n      }\n      return false;\n    }\n    return true;\n  }\n\n  /**\n   * Handles mouse wheel events by adjusting the viewport's scrollTop and delegating the actual\n   * scrolling to `onScroll`, this event needs to be attached manually by the consumer of\n   * `Viewport`.\n   * @param ev The mouse wheel event.\n   */\n  public onWheel(ev: WheelEvent): boolean {\n    const amount = this._getPixelsScrolled(ev);\n    if (amount === 0) {\n      return false;\n    }\n    this._viewportElement.scrollTop += amount;\n    return this._bubbleScroll(ev, amount);\n  }\n\n  private _getPixelsScrolled(ev: WheelEvent): number {\n    // Do nothing if it's not a vertical scroll event\n    if (ev.deltaY === 0) {\n      return 0;\n    }\n\n    // Fallback to WheelEvent.DOM_DELTA_PIXEL\n    let amount = this._applyScrollModifier(ev.deltaY, ev);\n    if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {\n      amount *= this._currentRowHeight;\n    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {\n      amount *= this._currentRowHeight * this._bufferService.rows;\n    }\n    return amount;\n  }\n\n  /**\n   * Gets the number of pixels scrolled by the mouse event taking into account what type of delta\n   * is being used.\n   * @param ev The mouse wheel event.\n   */\n  public getLinesScrolled(ev: WheelEvent): number {\n    // Do nothing if it's not a vertical scroll event\n    if (ev.deltaY === 0) {\n      return 0;\n    }\n\n    // Fallback to WheelEvent.DOM_DELTA_LINE\n    let amount = this._applyScrollModifier(ev.deltaY, ev);\n    if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n      amount /= this._currentRowHeight + 0.0; // Prevent integer division\n      this._wheelPartialScroll += amount;\n      amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);\n      this._wheelPartialScroll %= 1;\n    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {\n      amount *= this._bufferService.rows;\n    }\n    return amount;\n  }\n\n  private _applyScrollModifier(amount: number, ev: WheelEvent): number {\n    const modifier = this._optionsService.options.fastScrollModifier;\n    // Multiply the scroll speed when the modifier is down\n    if ((modifier === 'alt' && ev.altKey) ||\n        (modifier === 'ctrl' && ev.ctrlKey) ||\n        (modifier === 'shift' && ev.shiftKey)) {\n      return amount * this._optionsService.options.fastScrollSensitivity * this._optionsService.options.scrollSensitivity;\n    }\n\n    return amount * this._optionsService.options.scrollSensitivity;\n  }\n\n  /**\n   * Handles the touchstart event, recording the touch occurred.\n   * @param ev The touch event.\n   */\n  public onTouchStart(ev: TouchEvent): void {\n    this._lastTouchY = ev.touches[0].pageY;\n  }\n\n  /**\n   * Handles the touchmove event, scrolling the viewport if the position shifted.\n   * @param ev The touch event.\n   */\n  public onTouchMove(ev: TouchEvent): boolean {\n    const deltaY = this._lastTouchY - ev.touches[0].pageY;\n    this._lastTouchY = ev.touches[0].pageY;\n    if (deltaY === 0) {\n      return false;\n    }\n    this._viewportElement.scrollTop += deltaY;\n    return this._bubbleScroll(ev, deltaY);\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ISelectionService } from 'browser/services/Services';\nimport { ICoreService } from 'common/services/Services';\n\n/**\n * Prepares text to be pasted into the terminal by normalizing the line endings\n * @param text The pasted text that needs processing before inserting into the terminal\n */\nexport function prepareTextForTerminal(text: string): string {\n  return text.replace(/\\r?\\n/g, '\\r');\n}\n\n/**\n * Bracket text for paste, if necessary, as per https://cirw.in/blog/bracketed-paste\n * @param text The pasted text to bracket\n */\nexport function bracketTextForPaste(text: string, bracketedPasteMode: boolean): string {\n  if (bracketedPasteMode) {\n    return '\\x1b[200~' + text + '\\x1b[201~';\n  }\n  return text;\n}\n\n/**\n * Binds copy functionality to the given terminal.\n * @param ev The original copy event to be handled\n */\nexport function copyHandler(ev: ClipboardEvent, selectionService: ISelectionService): void {\n  if (ev.clipboardData) {\n    ev.clipboardData.setData('text/plain', selectionService.selectionText);\n  }\n  // Prevent or the original text will be copied.\n  ev.preventDefault();\n}\n\n/**\n * Redirect the clipboard's data to the terminal's input handler.\n * @param ev The original paste event to be handled\n * @param term The terminal on which to apply the handled paste event\n */\nexport function handlePasteEvent(ev: ClipboardEvent, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {\n  ev.stopPropagation();\n  if (ev.clipboardData) {\n    const text = ev.clipboardData.getData('text/plain');\n    paste(text, textarea, bracketedPasteMode, coreService);\n  }\n}\n\nexport function paste(text: string, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {\n  text = prepareTextForTerminal(text);\n  text = bracketTextForPaste(text, bracketedPasteMode);\n  coreService.triggerDataEvent(text, true);\n  textarea.value = '';\n}\n\n/**\n * Moves the textarea under the mouse cursor and focuses it.\n * @param ev The original right click event to be handled.\n * @param textarea The terminal's textarea.\n */\nexport function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement): void {\n\n  // Calculate textarea position relative to the screen element\n  const pos = screenElement.getBoundingClientRect();\n  const left = ev.clientX - pos.left - 10;\n  const top = ev.clientY - pos.top - 10;\n\n  // Bring textarea at the cursor position\n  textarea.style.position = 'absolute';\n  textarea.style.width = '20px';\n  textarea.style.height = '20px';\n  textarea.style.left = `${left}px`;\n  textarea.style.top = `${top}px`;\n  textarea.style.zIndex = '1000';\n\n  textarea.focus();\n\n  // Reset the terminal textarea's styling\n  // Timeout needs to be long enough for click event to be handled.\n  setTimeout(() => {\n    textarea.style.position = null;\n    textarea.style.width = null;\n    textarea.style.height = null;\n    textarea.style.left = null;\n    textarea.style.top = null;\n    textarea.style.zIndex = null;\n  }, 200);\n}\n\n/**\n * Bind to right-click event and allow right-click copy and paste.\n * @param ev The original right click event to be handled.\n * @param textarea The terminal's textarea.\n * @param selectionService The terminal's selection manager.\n * @param shouldSelectWord If true and there is no selection the current word will be selected\n */\nexport function rightClickHandler(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement, selectionService: ISelectionService, shouldSelectWord: boolean): void {\n  moveTextAreaUnderMouseCursor(ev, textarea, screenElement);\n\n  if (shouldSelectWord && !selectionService.isClickInSelection(ev)) {\n    selectionService.selectWordAtCursor(ev);\n  }\n\n  // Get textarea ready to copy from the context menu\n  textarea.value = selectionService.selectionText;\n  textarea.select();\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IInputHandler, IInputHandlingTerminal } from './Types';\nimport { C0, C1 } from 'common/data/EscapeSequences';\nimport { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';\nimport { wcwidth } from 'common/CharWidth';\nimport { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';\nimport { Disposable } from 'common/Lifecycle';\nimport { concat } from 'common/TypedArrayUtils';\nimport { StringToUtf32, stringFromCodePoint, utf32ToString, Utf8ToUtf32 } from 'common/input/TextDecoder';\nimport { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';\nimport { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { IAttributeData, IDisposable } from 'common/Types';\nimport { ICoreService, IBufferService, IOptionsService, ILogService, IDirtyRowService, ICoreMouseService } from 'common/services/Services';\nimport { OscHandler } from 'common/parser/OscParser';\nimport { DcsHandler } from 'common/parser/DcsParser';\n\n/**\n * Map collect to glevel. Used in `selectCharset`.\n */\nconst GLEVEL: {[key: string]: number} = {'(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2};\n\n/**\n * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher.\n */\nconst MAX_PARSEBUFFER_LENGTH = 131072;\n\n\n/**\n * DCS subparser implementations\n */\n\n/**\n * DCS $ q Pt ST\n *   DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html)\n *   Request Status String (DECRQSS), VT420 and up.\n *   Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html)\n */\nclass DECRQSS implements IDcsHandler {\n  private _data: Uint32Array = new Uint32Array(0);\n\n  constructor(\n    private _bufferService: IBufferService,\n    private _coreService: ICoreService,\n    private _logService: ILogService,\n    private _optionsService: IOptionsService\n  ) { }\n\n  hook(params: IParams): void {\n    this._data = new Uint32Array(0);\n  }\n\n  put(data: Uint32Array, start: number, end: number): void {\n    this._data = concat(this._data, data.subarray(start, end));\n  }\n\n  unhook(success: boolean): void {\n    if (!success) {\n      this._data = new Uint32Array(0);\n      return;\n    }\n    const data = utf32ToString(this._data);\n    this._data = new Uint32Array(0);\n    switch (data) {\n      // valid: DCS 1 $ r Pt ST (xterm)\n      case '\"q': // DECSCA\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0\"q${C0.ESC}\\\\`);\n      case '\"p': // DECSCL\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r61\"p${C0.ESC}\\\\`);\n      case 'r': // DECSTBM\n        const pt = '' + (this._bufferService.buffer.scrollTop + 1) +\n                ';' + (this._bufferService.buffer.scrollBottom + 1) + 'r';\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${pt}${C0.ESC}\\\\`);\n      case 'm': // SGR\n        // TODO: report real settings instead of 0m\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0m${C0.ESC}\\\\`);\n      case ' q': // DECSCUSR\n        const STYLES: {[key: string]: number} = {'block': 2, 'underline': 4, 'bar': 6};\n        let style = STYLES[this._optionsService.options.cursorStyle];\n        style -= this._optionsService.options.cursorBlink ? 1 : 0;\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${style} q${C0.ESC}\\\\`);\n      default:\n        // invalid: DCS 0 $ r Pt ST (xterm)\n        this._logService.debug('Unknown DCS $q %s', data);\n        this._coreService.triggerDataEvent(`${C0.ESC}P0$r${C0.ESC}\\\\`);\n    }\n  }\n}\n\n/**\n * DCS Ps; Ps| Pt ST\n *   DECUDK (https://vt100.net/docs/vt510-rm/DECUDK.html)\n *   not supported\n */\n\n/**\n * DCS + q Pt ST (xterm)\n *   Request Terminfo String\n *   not implemented\n */\n\n/**\n * DCS + p Pt ST (xterm)\n *   Set Terminfo Data\n *   not supported\n */\n\n\n\n/**\n * The terminal's standard implementation of IInputHandler, this handles all\n * input from the Parser.\n *\n * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand\n * each function's header comment.\n */\nexport class InputHandler extends Disposable implements IInputHandler {\n  private _parseBuffer: Uint32Array = new Uint32Array(4096);\n  private _stringDecoder: StringToUtf32 = new StringToUtf32();\n  private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32();\n  private _workCell: CellData = new CellData();\n\n  private _onCursorMove = new EventEmitter<void>();\n  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }\n  private _onLineFeed = new EventEmitter<void>();\n  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }\n  private _onScroll = new EventEmitter<number>();\n  public get onScroll(): IEvent<number> { return this._onScroll.event; }\n\n  constructor(\n    protected _terminal: IInputHandlingTerminal,\n    private readonly _bufferService: IBufferService,\n    private readonly _coreService: ICoreService,\n    private readonly _dirtyRowService: IDirtyRowService,\n    private readonly _logService: ILogService,\n    private readonly _optionsService: IOptionsService,\n    private readonly _coreMouseService: ICoreMouseService,\n    private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser())\n  {\n    super();\n\n    this.register(this._parser);\n\n    /**\n     * custom fallback handlers\n     */\n    this._parser.setCsiHandlerFallback((ident, params) => {\n      this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() });\n    });\n    this._parser.setEscHandlerFallback(ident => {\n      this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) });\n    });\n    this._parser.setExecuteHandlerFallback(code => {\n      this._logService.debug('Unknown EXECUTE code: ', { code });\n    });\n    this._parser.setOscHandlerFallback((identifier, action, data) => {\n      this._logService.debug('Unknown OSC code: ', { identifier, action, data });\n    });\n    this._parser.setDcsHandlerFallback((ident, action, payload) => {\n      if (action === 'HOOK') {\n        payload = payload.toArray();\n      }\n      this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload });\n    });\n\n    /**\n     * print handler\n     */\n    this._parser.setPrintHandler((data, start, end) => this.print(data, start, end));\n\n    /**\n     * CSI handler\n     */\n    this._parser.setCsiHandler({final: '@'}, params => this.insertChars(params));\n    this._parser.setCsiHandler({intermediates: ' ', final: '@'}, params => this.scrollLeft(params));\n    this._parser.setCsiHandler({final: 'A'}, params => this.cursorUp(params));\n    this._parser.setCsiHandler({intermediates: ' ', final: 'A'}, params => this.scrollRight(params));\n    this._parser.setCsiHandler({final: 'B'}, params => this.cursorDown(params));\n    this._parser.setCsiHandler({final: 'C'}, params => this.cursorForward(params));\n    this._parser.setCsiHandler({final: 'D'}, params => this.cursorBackward(params));\n    this._parser.setCsiHandler({final: 'E'}, params => this.cursorNextLine(params));\n    this._parser.setCsiHandler({final: 'F'}, params => this.cursorPrecedingLine(params));\n    this._parser.setCsiHandler({final: 'G'}, params => this.cursorCharAbsolute(params));\n    this._parser.setCsiHandler({final: 'H'}, params => this.cursorPosition(params));\n    this._parser.setCsiHandler({final: 'I'}, params => this.cursorForwardTab(params));\n    this._parser.setCsiHandler({final: 'J'}, params => this.eraseInDisplay(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'J'}, params => this.eraseInDisplay(params));\n    this._parser.setCsiHandler({final: 'K'}, params => this.eraseInLine(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'K'}, params => this.eraseInLine(params));\n    this._parser.setCsiHandler({final: 'L'}, params => this.insertLines(params));\n    this._parser.setCsiHandler({final: 'M'}, params => this.deleteLines(params));\n    this._parser.setCsiHandler({final: 'P'}, params => this.deleteChars(params));\n    this._parser.setCsiHandler({final: 'S'}, params => this.scrollUp(params));\n    this._parser.setCsiHandler({final: 'T'}, params => this.scrollDown(params));\n    this._parser.setCsiHandler({final: 'X'}, params => this.eraseChars(params));\n    this._parser.setCsiHandler({final: 'Z'}, params => this.cursorBackwardTab(params));\n    this._parser.setCsiHandler({final: '`'}, params => this.charPosAbsolute(params));\n    this._parser.setCsiHandler({final: 'a'}, params => this.hPositionRelative(params));\n    this._parser.setCsiHandler({final: 'b'}, params => this.repeatPrecedingCharacter(params));\n    this._parser.setCsiHandler({final: 'c'}, params => this.sendDeviceAttributesPrimary(params));\n    this._parser.setCsiHandler({prefix: '>', final: 'c'}, params => this.sendDeviceAttributesSecondary(params));\n    this._parser.setCsiHandler({final: 'd'}, params => this.linePosAbsolute(params));\n    this._parser.setCsiHandler({final: 'e'}, params => this.vPositionRelative(params));\n    this._parser.setCsiHandler({final: 'f'}, params => this.hVPosition(params));\n    this._parser.setCsiHandler({final: 'g'}, params => this.tabClear(params));\n    this._parser.setCsiHandler({final: 'h'}, params => this.setMode(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'h'}, params => this.setModePrivate(params));\n    this._parser.setCsiHandler({final: 'l'}, params => this.resetMode(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'l'}, params => this.resetModePrivate(params));\n    this._parser.setCsiHandler({final: 'm'}, params => this.charAttributes(params));\n    this._parser.setCsiHandler({final: 'n'}, params => this.deviceStatus(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'n'}, params => this.deviceStatusPrivate(params));\n    this._parser.setCsiHandler({intermediates: '!', final: 'p'}, params => this.softReset(params));\n    this._parser.setCsiHandler({intermediates: ' ', final: 'q'}, params => this.setCursorStyle(params));\n    this._parser.setCsiHandler({final: 'r'}, params => this.setScrollRegion(params));\n    this._parser.setCsiHandler({final: 's'}, params => this.saveCursor(params));\n    this._parser.setCsiHandler({final: 'u'}, params => this.restoreCursor(params));\n    this._parser.setCsiHandler({intermediates: '\\'', final: '}'}, params => this.insertColumns(params));\n    this._parser.setCsiHandler({intermediates: '\\'', final: '~'}, params => this.deleteColumns(params));\n\n    /**\n     * execute handler\n     */\n    this._parser.setExecuteHandler(C0.BEL, () => this.bell());\n    this._parser.setExecuteHandler(C0.LF, () => this.lineFeed());\n    this._parser.setExecuteHandler(C0.VT, () => this.lineFeed());\n    this._parser.setExecuteHandler(C0.FF, () => this.lineFeed());\n    this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn());\n    this._parser.setExecuteHandler(C0.BS, () => this.backspace());\n    this._parser.setExecuteHandler(C0.HT, () => this.tab());\n    this._parser.setExecuteHandler(C0.SO, () => this.shiftOut());\n    this._parser.setExecuteHandler(C0.SI, () => this.shiftIn());\n    // FIXME:   What do to with missing? Old code just added those to print.\n\n    this._parser.setExecuteHandler(C1.IND, () => this.index());\n    this._parser.setExecuteHandler(C1.NEL, () => this.nextLine());\n    this._parser.setExecuteHandler(C1.HTS, () => this.tabSet());\n\n    /**\n     * OSC handler\n     */\n    //   0 - icon name + title\n    this._parser.setOscHandler(0, new OscHandler((data: string) => this.setTitle(data)));\n    //   1 - icon name\n    //   2 - title\n    this._parser.setOscHandler(2, new OscHandler((data: string) => this.setTitle(data)));\n    //   3 - set property X in the form \"prop=value\"\n    //   4 - Change Color Number\n    //   5 - Change Special Color Number\n    //   6 - Enable/disable Special Color Number c\n    //   7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939)\n    //  10 - Change VT100 text foreground color to Pt.\n    //  11 - Change VT100 text background color to Pt.\n    //  12 - Change text cursor color to Pt.\n    //  13 - Change mouse foreground color to Pt.\n    //  14 - Change mouse background color to Pt.\n    //  15 - Change Tektronix foreground color to Pt.\n    //  16 - Change Tektronix background color to Pt.\n    //  17 - Change highlight background color to Pt.\n    //  18 - Change Tektronix cursor color to Pt.\n    //  19 - Change highlight foreground color to Pt.\n    //  46 - Change Log File to Pt.\n    //  50 - Set Font to Pt.\n    //  51 - reserved for Emacs shell.\n    //  52 - Manipulate Selection Data.\n    // 104 ; c - Reset Color Number c.\n    // 105 ; c - Reset Special Color Number c.\n    // 106 ; c; f - Enable/disable Special Color Number c.\n    // 110 - Reset VT100 text foreground color.\n    // 111 - Reset VT100 text background color.\n    // 112 - Reset text cursor color.\n    // 113 - Reset mouse foreground color.\n    // 114 - Reset mouse background color.\n    // 115 - Reset Tektronix foreground color.\n    // 116 - Reset Tektronix background color.\n    // 117 - Reset highlight color.\n    // 118 - Reset Tektronix cursor color.\n    // 119 - Reset highlight foreground color.\n\n    /**\n     * ESC handlers\n     */\n    this._parser.setEscHandler({final: '7'}, () => this.saveCursor());\n    this._parser.setEscHandler({final: '8'}, () => this.restoreCursor());\n    this._parser.setEscHandler({final: 'D'}, () => this.index());\n    this._parser.setEscHandler({final: 'E'}, () => this.nextLine());\n    this._parser.setEscHandler({final: 'H'}, () => this.tabSet());\n    this._parser.setEscHandler({final: 'M'}, () => this.reverseIndex());\n    this._parser.setEscHandler({final: '='}, () => this.keypadApplicationMode());\n    this._parser.setEscHandler({final: '>'}, () => this.keypadNumericMode());\n    this._parser.setEscHandler({final: 'c'}, () => this.reset());\n    this._parser.setEscHandler({final: 'n'}, () => this.setgLevel(2));\n    this._parser.setEscHandler({final: 'o'}, () => this.setgLevel(3));\n    this._parser.setEscHandler({final: '|'}, () => this.setgLevel(3));\n    this._parser.setEscHandler({final: '}'}, () => this.setgLevel(2));\n    this._parser.setEscHandler({final: '~'}, () => this.setgLevel(1));\n    this._parser.setEscHandler({intermediates: '%', final: '@'}, () => this.selectDefaultCharset());\n    this._parser.setEscHandler({intermediates: '%', final: 'G'}, () => this.selectDefaultCharset());\n    for (const flag in CHARSETS) {\n      this._parser.setEscHandler({intermediates: '(', final: flag}, () => this.selectCharset('(' + flag));\n      this._parser.setEscHandler({intermediates: ')', final: flag}, () => this.selectCharset(')' + flag));\n      this._parser.setEscHandler({intermediates: '*', final: flag}, () => this.selectCharset('*' + flag));\n      this._parser.setEscHandler({intermediates: '+', final: flag}, () => this.selectCharset('+' + flag));\n      this._parser.setEscHandler({intermediates: '-', final: flag}, () => this.selectCharset('-' + flag));\n      this._parser.setEscHandler({intermediates: '.', final: flag}, () => this.selectCharset('.' + flag));\n      this._parser.setEscHandler({intermediates: '/', final: flag}, () => this.selectCharset('/' + flag)); // TODO: supported?\n    }\n    this._parser.setEscHandler({intermediates: '#', final: '8'}, () => this.screenAlignmentPattern());\n\n    /**\n     * error handler\n     */\n    this._parser.setErrorHandler((state: IParsingState) => {\n      this._logService.error('Parsing error: ', state);\n      return state;\n    });\n\n    /**\n     * DCS handler\n     */\n    this._parser.setDcsHandler({intermediates: '$', final: 'q'}, new DECRQSS(this._bufferService, this._coreService, this._logService, this._optionsService));\n  }\n\n  public dispose(): void {\n    super.dispose();\n  }\n\n  public parse(data: string | Uint8Array): void {\n    let buffer = this._bufferService.buffer;\n    const cursorStartX = buffer.x;\n    const cursorStartY = buffer.y;\n\n    this._logService.debug('parsing data', data);\n\n    // resize input buffer if needed\n    if (this._parseBuffer.length < data.length) {\n      if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) {\n        this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH));\n      }\n    }\n\n    // process big data in smaller chunks\n    if (data.length > MAX_PARSEBUFFER_LENGTH) {\n      for (let i = 0; i < data.length; i += MAX_PARSEBUFFER_LENGTH) {\n        const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length;\n        const len = (typeof data === 'string')\n          ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer)\n          : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer);\n        this._parser.parse(this._parseBuffer, len);\n      }\n    } else {\n      const len = (typeof data === 'string')\n        ? this._stringDecoder.decode(data, this._parseBuffer)\n        : this._utf8Decoder.decode(data, this._parseBuffer);\n      this._parser.parse(this._parseBuffer, len);\n    }\n\n    buffer = this._bufferService.buffer;\n    if (buffer.x !== cursorStartX || buffer.y !== cursorStartY) {\n      this._onCursorMove.fire();\n    }\n    this._terminal.refresh(this._dirtyRowService.start, this._dirtyRowService.end);\n  }\n\n  public print(data: Uint32Array, start: number, end: number): void {\n    let code: number;\n    let chWidth: number;\n    const buffer = this._bufferService.buffer;\n    const charset = this._terminal.charset;\n    const screenReaderMode = this._optionsService.options.screenReaderMode;\n    const cols = this._bufferService.cols;\n    const wraparoundMode = this._terminal.wraparoundMode;\n    const insertMode = this._terminal.insertMode;\n    const curAttr = this._terminal.curAttrData;\n    let bufferRow = buffer.lines.get(buffer.y + buffer.ybase);\n\n    this._dirtyRowService.markDirty(buffer.y);\n    for (let pos = start; pos < end; ++pos) {\n      code = data[pos];\n\n      // calculate print space\n      // expensive call, therefore we save width in line buffer\n      chWidth = wcwidth(code);\n\n      // get charset replacement character\n      // charset is only defined for ASCII, therefore we only\n      // search for an replacement char if code < 127\n      if (code < 127 && charset) {\n        const ch = charset[String.fromCharCode(code)];\n        if (ch) {\n          code = ch.charCodeAt(0);\n        }\n      }\n\n      if (screenReaderMode) {\n        this._terminal.onA11yCharEmitter.fire(stringFromCodePoint(code));\n      }\n\n      // insert combining char at last cursor position\n      // FIXME: needs handling after cursor jumps\n      // buffer.x should never be 0 for a combining char\n      // since they always follow a cell consuming char\n      // therefore we can test for buffer.x to avoid overflow left\n      if (!chWidth && buffer.x) {\n        if (!bufferRow.getWidth(buffer.x - 1)) {\n          // found empty cell after fullwidth, need to go 2 cells back\n          // it is save to step 2 cells back here\n          // since an empty cell is only set by fullwidth chars\n          bufferRow.addCodepointToCell(buffer.x - 2, code);\n        } else {\n          bufferRow.addCodepointToCell(buffer.x - 1, code);\n        }\n        continue;\n      }\n\n      // goto next line if ch would overflow\n      // TODO: needs a global min terminal width of 2\n      // FIXME: additionally ensure chWidth fits into a line\n      //   -->  maybe forbid cols<xy at higher level as it would\n      //        introduce a bad runtime penalty here\n      if (buffer.x + chWidth - 1 >= cols) {\n        // autowrap - DECAWM\n        // automatically wraps to the beginning of the next line\n        if (wraparoundMode) {\n          buffer.x = 0;\n          buffer.y++;\n          if (buffer.y === buffer.scrollBottom + 1) {\n            buffer.y--;\n            this._terminal.scroll(true);\n          } else {\n            if (buffer.y >= this._bufferService.rows) {\n              buffer.y = this._bufferService.rows - 1;\n            }\n            // The line already exists (eg. the initial viewport), mark it as a\n            // wrapped line\n            buffer.lines.get(buffer.y).isWrapped = true;\n          }\n          // row changed, get it again\n          bufferRow = buffer.lines.get(buffer.y + buffer.ybase);\n        } else {\n          buffer.x = cols - 1;\n          if (chWidth === 2) {\n            // FIXME: check for xterm behavior\n            // What to do here? We got a wide char that does not fit into last cell\n            continue;\n          }\n        }\n      }\n\n      // insert mode: move characters to right\n      if (insertMode) {\n        // right shift cells according to the width\n        bufferRow.insertCells(buffer.x, chWidth, buffer.getNullCell(curAttr));\n        // test last cell - since the last cell has only room for\n        // a halfwidth char any fullwidth shifted there is lost\n        // and will be set to empty cell\n        if (bufferRow.getWidth(cols - 1) === 2) {\n          bufferRow.setCellFromCodePoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr.fg, curAttr.bg);\n        }\n      }\n\n      // write current char to buffer and advance cursor\n      bufferRow.setCellFromCodePoint(buffer.x++, code, chWidth, curAttr.fg, curAttr.bg);\n\n      // fullwidth char - also set next cell to placeholder stub and advance cursor\n      // for graphemes bigger than fullwidth we can simply loop to zero\n      // we already made sure above, that buffer.x + chWidth will not overflow right\n      if (chWidth > 0) {\n        while (--chWidth) {\n          // other than a regular empty cell a cell following a wide char has no width\n          bufferRow.setCellFromCodePoint(buffer.x++, 0, 0, curAttr.fg, curAttr.bg);\n        }\n      }\n    }\n    // store last char in Parser.precedingCodepoint for REP to work correctly\n    // This needs to check whether:\n    //  - fullwidth + surrogates: reset\n    //  - combining: only base char gets carried on (bug in xterm?)\n    if (end) {\n      bufferRow.loadCell(buffer.x - 1, this._workCell);\n      if (this._workCell.getWidth() === 2 || this._workCell.getCode() > 0xFFFF) {\n        this._parser.precedingCodepoint = 0;\n      } else if (this._workCell.isCombined()) {\n        this._parser.precedingCodepoint = this._workCell.getChars().charCodeAt(0);\n      } else {\n        this._parser.precedingCodepoint = this._workCell.content;\n      }\n    }\n    this._dirtyRowService.markDirty(buffer.y);\n  }\n\n  /**\n   * Forward addCsiHandler from parser.\n   */\n  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {\n    return this._parser.addCsiHandler(id, callback);\n  }\n\n  /**\n   * Forward addDcsHandler from parser.\n   */\n  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {\n    return this._parser.addDcsHandler(id, new DcsHandler(callback));\n  }\n\n  /**\n   * Forward addEscHandler from parser.\n   */\n  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {\n    return this._parser.addEscHandler(id, callback);\n  }\n\n  /**\n   * Forward addOscHandler from parser.\n   */\n  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {\n    return this._parser.addOscHandler(ident, new OscHandler(callback));\n  }\n\n  /**\n   * BEL\n   * Bell (Ctrl-G).\n   */\n  public bell(): void {\n    this._terminal.bell();\n  }\n\n  /**\n   * LF\n   * Line Feed or New Line (NL).  (LF  is Ctrl-J).\n   */\n  public lineFeed(): void {\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    if (this._optionsService.options.convertEol) {\n      buffer.x = 0;\n    }\n    buffer.y++;\n    if (buffer.y === buffer.scrollBottom + 1) {\n      buffer.y--;\n      this._terminal.scroll();\n    } else if (buffer.y >= this._bufferService.rows) {\n      buffer.y = this._bufferService.rows - 1;\n    }\n    // If the end of the line is hit, prevent this action from wrapping around to the next line.\n    if (buffer.x >= this._bufferService.cols) {\n      buffer.x--;\n    }\n\n    this._onLineFeed.fire();\n  }\n\n  /**\n   * CR\n   * Carriage Return (Ctrl-M).\n   */\n  public carriageReturn(): void {\n    this._bufferService.buffer.x = 0;\n  }\n\n  /**\n   * BS\n   * Backspace (Ctrl-H).\n   */\n  public backspace(): void {\n    this._restrictCursor();\n    if (this._bufferService.buffer.x > 0) {\n      this._bufferService.buffer.x--;\n    }\n  }\n\n  /**\n   * TAB\n   * Horizontal Tab (HT) (Ctrl-I).\n   */\n  public tab(): void {\n    if (this._bufferService.buffer.x >= this._bufferService.cols) {\n      return;\n    }\n    const originalX = this._bufferService.buffer.x;\n    this._bufferService.buffer.x = this._bufferService.buffer.nextStop();\n    if (this._optionsService.options.screenReaderMode) {\n      this._terminal.onA11yTabEmitter.fire(this._bufferService.buffer.x - originalX);\n    }\n  }\n\n  /**\n   * SO\n   * Shift Out (Ctrl-N) -> Switch to Alternate Character Set.  This invokes the\n   * G1 character set.\n   */\n  public shiftOut(): void {\n    this._terminal.setgLevel(1);\n  }\n\n  /**\n   * SI\n   * Shift In (Ctrl-O) -> Switch to Standard Character Set.  This invokes the G0\n   * character set (the default).\n   */\n  public shiftIn(): void {\n    this._terminal.setgLevel(0);\n  }\n\n  /**\n   * Restrict cursor to viewport size / scroll margin (origin mode).\n   */\n  private _restrictCursor(): void {\n    this._bufferService.buffer.x = Math.min(this._bufferService.cols - 1, Math.max(0, this._bufferService.buffer.x));\n    this._bufferService.buffer.y = this._terminal.originMode\n      ? Math.min(this._bufferService.buffer.scrollBottom, Math.max(this._bufferService.buffer.scrollTop, this._bufferService.buffer.y))\n      : Math.min(this._bufferService.rows - 1, Math.max(0, this._bufferService.buffer.y));\n  }\n\n  /**\n   * Set absolute cursor position.\n   */\n  private _setCursor(x: number, y: number): void {\n    if (this._terminal.originMode) {\n      this._bufferService.buffer.x = x;\n      this._bufferService.buffer.y = this._bufferService.buffer.scrollTop + y;\n    } else {\n      this._bufferService.buffer.x = x;\n      this._bufferService.buffer.y = y;\n    }\n    this._restrictCursor();\n  }\n\n  /**\n   * Set relative cursor position.\n   */\n  private _moveCursor(x: number, y: number): void {\n    // for relative changes we have to make sure we are within 0 .. cols/rows - 1\n    // before calculating the new position\n    this._restrictCursor();\n    this._setCursor(this._bufferService.buffer.x + x, this._bufferService.buffer.y + y);\n  }\n\n  /**\n   * CSI Ps A\n   * Cursor Up Ps Times (default = 1) (CUU).\n   */\n  public cursorUp(params: IParams): void {\n    // stop at scrollTop\n    const diffToTop = this._bufferService.buffer.y - this._bufferService.buffer.scrollTop;\n    if (diffToTop >= 0) {\n      this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1));\n    } else {\n      this._moveCursor(0, -(params.params[0] || 1));\n    }\n  }\n\n  /**\n   * CSI Ps B\n   * Cursor Down Ps Times (default = 1) (CUD).\n   */\n  public cursorDown(params: IParams): void {\n    // stop at scrollBottom\n    const diffToBottom = this._bufferService.buffer.scrollBottom - this._bufferService.buffer.y;\n    if (diffToBottom >= 0) {\n      this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1));\n    } else {\n      this._moveCursor(0, params.params[0] || 1);\n    }\n  }\n\n  /**\n   * CSI Ps C\n   * Cursor Forward Ps Times (default = 1) (CUF).\n   */\n  public cursorForward(params: IParams): void {\n    this._moveCursor(params.params[0] || 1, 0);\n  }\n\n  /**\n   * CSI Ps D\n   * Cursor Backward Ps Times (default = 1) (CUB).\n   */\n  public cursorBackward(params: IParams): void {\n    this._moveCursor(-(params.params[0] || 1), 0);\n  }\n\n  /**\n   * CSI Ps E\n   * Cursor Next Line Ps Times (default = 1) (CNL).\n   * Other than cursorDown (CUD) also set the cursor to first column.\n   */\n  public cursorNextLine(params: IParams): void {\n    this.cursorDown(params);\n    this._bufferService.buffer.x = 0;\n  }\n\n  /**\n   * CSI Ps F\n   * Cursor Previous Line Ps Times (default = 1) (CPL).\n   * Other than cursorUp (CUU) also set the cursor to first column.\n   */\n  public cursorPrecedingLine(params: IParams): void {\n    this.cursorUp(params);\n    this._bufferService.buffer.x = 0;\n  }\n\n  /**\n   * CSI Ps G\n   * Cursor Character Absolute  [column] (default = [row,1]) (CHA).\n   */\n  public cursorCharAbsolute(params: IParams): void {\n    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);\n  }\n\n  /**\n   * CSI Ps ; Ps H\n   * Cursor Position [row;column] (default = [1,1]) (CUP).\n   */\n  public cursorPosition(params: IParams): void {\n    this._setCursor(\n      // col\n      (params.length >= 2) ? (params.params[1] || 1) - 1 : 0,\n      // row\n      (params.params[0] || 1) - 1);\n  }\n\n  /**\n   * CSI Pm `  Character Position Absolute\n   *   [column] (default = [row,1]) (HPA).\n   * Currently same functionality as CHA.\n   */\n  public charPosAbsolute(params: IParams): void {\n    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);\n  }\n\n  /**\n   * CSI Pm a  Character Position Relative\n   *   [columns] (default = [row,col+1]) (HPR)\n   * Currently same functionality as CUF.\n   */\n  public hPositionRelative(params: IParams): void {\n    this._moveCursor(params.params[0] || 1, 0);\n  }\n\n  /**\n   * CSI Pm d  Vertical Position Absolute (VPA)\n   *   [row] (default = [1,column])\n   */\n  public linePosAbsolute(params: IParams): void {\n    this._setCursor(this._bufferService.buffer.x, (params.params[0] || 1) - 1);\n  }\n\n  /**\n   * CSI Pm e  Vertical Position Relative (VPR)\n   *   [rows] (default = [row+1,column])\n   * reuse CSI Ps B ?\n   */\n  public vPositionRelative(params: IParams): void {\n    this._moveCursor(0, params.params[0] || 1);\n  }\n\n  /**\n   * CSI Ps ; Ps f\n   *   Horizontal and Vertical Position [row;column] (default =\n   *   [1,1]) (HVP).\n   *   Same as CUP.\n   */\n  public hVPosition(params: IParams): void {\n    this.cursorPosition(params);\n  }\n\n  /**\n   * CSI Ps g  Tab Clear (TBC).\n   *     Ps = 0  -> Clear Current Column (default).\n   *     Ps = 3  -> Clear All.\n   * Potentially:\n   *   Ps = 2  -> Clear Stops on Line.\n   *   http://vt100.net/annarbor/aaa-ug/section6.html\n   */\n  public tabClear(params: IParams): void {\n    const param = params.params[0];\n    if (param === 0) {\n      delete this._bufferService.buffer.tabs[this._bufferService.buffer.x];\n    } else if (param === 3) {\n      this._bufferService.buffer.tabs = {};\n    }\n  }\n\n  /**\n   * CSI Ps I\n   *   Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).\n   */\n  public cursorForwardTab(params: IParams): void {\n    if (this._bufferService.buffer.x >= this._bufferService.cols) {\n      return;\n    }\n    let param = params.params[0] || 1;\n    while (param--) {\n      this._bufferService.buffer.x = this._bufferService.buffer.nextStop();\n    }\n  }\n\n  /**\n   * CSI Ps Z  Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).\n   */\n  public cursorBackwardTab(params: IParams): void {\n    if (this._bufferService.buffer.x >= this._bufferService.cols) {\n      return;\n    }\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    while (param--) {\n      buffer.x = buffer.prevStop();\n    }\n  }\n\n\n  /**\n   * Helper method to erase cells in a terminal row.\n   * The cell gets replaced with the eraseChar of the terminal.\n   * @param y row index\n   * @param start first cell index to be erased\n   * @param end   end - 1 is last erased cell\n   */\n  private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false): void {\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);\n    line.replaceCells(\n      start,\n      end,\n      this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n    );\n    if (clearWrap) {\n      line.isWrapped = false;\n    }\n  }\n\n  /**\n   * Helper method to reset cells in a terminal row.\n   * The cell gets replaced with the eraseChar of the terminal and the isWrapped property is set to false.\n   * @param y row index\n   */\n  private _resetBufferLine(y: number): void {\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);\n    line.fill(this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData()));\n    line.isWrapped = false;\n  }\n\n  /**\n   * CSI Ps J  Erase in Display (ED).\n   *     Ps = 0  -> Erase Below (default).\n   *     Ps = 1  -> Erase Above.\n   *     Ps = 2  -> Erase All.\n   *     Ps = 3  -> Erase Saved Lines (xterm).\n   * CSI ? Ps J\n   *   Erase in Display (DECSED).\n   *     Ps = 0  -> Selective Erase Below (default).\n   *     Ps = 1  -> Selective Erase Above.\n   *     Ps = 2  -> Selective Erase All.\n   */\n  public eraseInDisplay(params: IParams): void {\n    this._restrictCursor();\n    let j;\n    switch (params.params[0]) {\n      case 0:\n        j = this._bufferService.buffer.y;\n        this._dirtyRowService.markDirty(j);\n        this._eraseInBufferLine(j++, this._bufferService.buffer.x, this._bufferService.cols, this._bufferService.buffer.x === 0);\n        for (; j < this._bufferService.rows; j++) {\n          this._resetBufferLine(j);\n        }\n        this._dirtyRowService.markDirty(j);\n        break;\n      case 1:\n        j = this._bufferService.buffer.y;\n        this._dirtyRowService.markDirty(j);\n        // Deleted front part of line and everything before. This line will no longer be wrapped.\n        this._eraseInBufferLine(j, 0, this._bufferService.buffer.x + 1, true);\n        if (this._bufferService.buffer.x + 1 >= this._bufferService.cols) {\n          // Deleted entire previous line. This next line can no longer be wrapped.\n          this._bufferService.buffer.lines.get(j + 1).isWrapped = false;\n        }\n        while (j--) {\n          this._resetBufferLine(j);\n        }\n        this._dirtyRowService.markDirty(0);\n        break;\n      case 2:\n        j = this._bufferService.rows;\n        this._dirtyRowService.markDirty(j - 1);\n        while (j--) {\n          this._resetBufferLine(j);\n        }\n        this._dirtyRowService.markDirty(0);\n        break;\n      case 3:\n        // Clear scrollback (everything not in viewport)\n        const scrollBackSize = this._bufferService.buffer.lines.length - this._bufferService.rows;\n        if (scrollBackSize > 0) {\n          this._bufferService.buffer.lines.trimStart(scrollBackSize);\n          this._bufferService.buffer.ybase = Math.max(this._bufferService.buffer.ybase - scrollBackSize, 0);\n          this._bufferService.buffer.ydisp = Math.max(this._bufferService.buffer.ydisp - scrollBackSize, 0);\n          // Force a scroll event to refresh viewport\n          this._onScroll.fire(0);\n        }\n        break;\n    }\n  }\n\n  /**\n   * CSI Ps K  Erase in Line (EL).\n   *     Ps = 0  -> Erase to Right (default).\n   *     Ps = 1  -> Erase to Left.\n   *     Ps = 2  -> Erase All.\n   * CSI ? Ps K\n   *   Erase in Line (DECSEL).\n   *     Ps = 0  -> Selective Erase to Right (default).\n   *     Ps = 1  -> Selective Erase to Left.\n   *     Ps = 2  -> Selective Erase All.\n   */\n  public eraseInLine(params: IParams): void {\n    this._restrictCursor();\n    switch (params.params[0]) {\n      case 0:\n        this._eraseInBufferLine(this._bufferService.buffer.y, this._bufferService.buffer.x, this._bufferService.cols);\n        break;\n      case 1:\n        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.buffer.x + 1);\n        break;\n      case 2:\n        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.cols);\n        break;\n    }\n    this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n  }\n\n  /**\n   * CSI Ps L\n   * Insert Ps Line(s) (default = 1) (IL).\n   */\n  public insertLines(params: IParams): void {\n    this._restrictCursor();\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n\n    const row: number = buffer.y + buffer.ybase;\n\n    const scrollBottomRowsOffset = this._bufferService.rows - 1 - buffer.scrollBottom;\n    const scrollBottomAbsolute = this._bufferService.rows - 1 + buffer.ybase - scrollBottomRowsOffset + 1;\n    while (param--) {\n      // test: echo -e '\\e[44m\\e[1L\\e[0m'\n      // blankLine(true) - xterm/linux behavior\n      buffer.lines.splice(scrollBottomAbsolute - 1, 1);\n      buffer.lines.splice(row, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));\n    }\n\n    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);\n    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n  }\n\n  /**\n   * CSI Ps M\n   * Delete Ps Line(s) (default = 1) (DL).\n   */\n  public deleteLines(params: IParams): void {\n    this._restrictCursor();\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n\n    const row: number = buffer.y + buffer.ybase;\n\n    let j: number;\n    j = this._bufferService.rows - 1 - buffer.scrollBottom;\n    j = this._bufferService.rows - 1 + buffer.ybase - j;\n    while (param--) {\n      // test: echo -e '\\e[44m\\e[1M\\e[0m'\n      // blankLine(true) - xterm/linux behavior\n      buffer.lines.splice(row, 1);\n      buffer.lines.splice(j, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));\n    }\n\n    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);\n    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n  }\n\n  /**\n   * CSI Ps @\n   * Insert Ps (Blank) Character(s) (default = 1) (ICH).\n   */\n  public insertChars(params: IParams): void {\n    this._restrictCursor();\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);\n    if (line) {\n      line.insertCells(\n        this._bufferService.buffer.x,\n        params.params[0] || 1,\n        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n      );\n      this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n    }\n  }\n\n  /**\n   * CSI Ps P\n   * Delete Ps Character(s) (default = 1) (DCH).\n   */\n  public deleteChars(params: IParams): void {\n    this._restrictCursor();\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);\n    if (line) {\n      line.deleteCells(\n        this._bufferService.buffer.x,\n        params.params[0] || 1,\n        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n      );\n      this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n    }\n  }\n\n  /**\n   * CSI Ps S  Scroll up Ps lines (default = 1) (SU).\n   */\n  public scrollUp(params: IParams): void {\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    while (param--) {\n      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 1);\n      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps T  Scroll down Ps lines (default = 1) (SD).\n   */\n  public scrollDown(params: IParams): void {\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    while (param--) {\n      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 1);\n      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 0, buffer.getBlankLine(DEFAULT_ATTR_DATA));\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps SP @  Scroll left Ps columns (default = 1) (SL) ECMA-48\n   *\n   * Notation: (Pn)\n   * Representation: CSI Pn 02/00 04/00\n   * Parameter default value: Pn = 1\n   * SL causes the data in the presentation component to be moved by n character positions\n   * if the line orientation is horizontal, or by n line positions if the line orientation\n   * is vertical, such that the data appear to move to the left; where n equals the value of Pn.\n   * The active presentation position is not affected by this control function.\n   *\n   * Supported:\n   *   - always left shift (no line orientation setting respected)\n   */\n  public scrollLeft(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = buffer.lines.get(buffer.ybase + y);\n      line.deleteCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps SP A  Scroll right Ps columns (default = 1) (SR) ECMA-48\n   *\n   * Notation: (Pn)\n   * Representation: CSI Pn 02/00 04/01\n   * Parameter default value: Pn = 1\n   * SR causes the data in the presentation component to be moved by n character positions\n   * if the line orientation is horizontal, or by n line positions if the line orientation\n   * is vertical, such that the data appear to move to the right; where n equals the value of Pn.\n   * The active presentation position is not affected by this control function.\n   *\n   * Supported:\n   *   - always right shift (no line orientation setting respected)\n   */\n  public scrollRight(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = buffer.lines.get(buffer.ybase + y);\n      line.insertCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Pm ' }\n   * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.\n   */\n  public insertColumns(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = this._bufferService.buffer.lines.get(buffer.ybase + y);\n      line.insertCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Pm ' ~\n   * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.\n   */\n  public deleteColumns(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = buffer.lines.get(buffer.ybase + y);\n      line.deleteCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps X\n   * Erase Ps Character(s) (default = 1) (ECH).\n   */\n  public eraseChars(params: IParams): void {\n    this._restrictCursor();\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);\n    if (line) {\n      line.replaceCells(\n        this._bufferService.buffer.x,\n        this._bufferService.buffer.x + (params.params[0] || 1),\n        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n      );\n      this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n    }\n  }\n\n  /**\n   * CSI Ps b  Repeat the preceding graphic character Ps times (REP).\n   * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf)\n   *    Notation: (Pn)\n   *    Representation: CSI Pn 06/02\n   *    Parameter default value: Pn = 1\n   *    REP is used to indicate that the preceding character in the data stream,\n   *    if it is a graphic character (represented by one or more bit combinations) including SPACE,\n   *    is to be repeated n times, where n equals the value of Pn.\n   *    If the character preceding REP is a control function or part of a control function,\n   *    the effect of REP is not defined by this Standard.\n   *\n   * Since we propagate the terminal as xterm-256color we have to follow xterm's behavior:\n   *    - fullwidth + surrogate chars are ignored\n   *    - for combining chars only the base char gets repeated\n   *    - text attrs are applied normally\n   *    - wrap around is respected\n   *    - any valid sequence resets the carried forward char\n   *\n   * Note: To get reset on a valid sequence working correctly without much runtime penalty,\n   * the preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`.\n   */\n  public repeatPrecedingCharacter(params: IParams): void {\n    if (!this._parser.precedingCodepoint) {\n      return;\n    }\n    // call print to insert the chars and handle correct wrapping\n    const length = params.params[0] || 1;\n    const data = new Uint32Array(length);\n    for (let i = 0; i < length; ++i) {\n      data[i] = this._parser.precedingCodepoint;\n    }\n    this.print(data, 0, data.length);\n  }\n\n  /**\n   * CSI Ps c  Send Device Attributes (Primary DA).\n   *     Ps = 0  or omitted -> request attributes from terminal.  The\n   *     response depends on the decTerminalID resource setting.\n   *     -> CSI ? 1 ; 2 c  (``VT100 with Advanced Video Option'')\n   *     -> CSI ? 1 ; 0 c  (``VT101 with No Options'')\n   *     -> CSI ? 6 c  (``VT102'')\n   *     -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c  (``VT220'')\n   *   The VT100-style response parameters do not mean anything by\n   *   themselves.  VT220 parameters do, telling the host what fea-\n   *   tures the terminal supports:\n   *     Ps = 1  -> 132-columns.\n   *     Ps = 2  -> Printer.\n   *     Ps = 6  -> Selective erase.\n   *     Ps = 8  -> User-defined keys.\n   *     Ps = 9  -> National replacement character sets.\n   *     Ps = 1 5  -> Technical characters.\n   *     Ps = 2 2  -> ANSI color, e.g., VT525.\n   *     Ps = 2 9  -> ANSI text locator (i.e., DEC Locator mode).\n   * CSI > Ps c\n   *   Send Device Attributes (Secondary DA).\n   *     Ps = 0  or omitted -> request the terminal's identification\n   *     code.  The response depends on the decTerminalID resource set-\n   *     ting.  It should apply only to VT220 and up, but xterm extends\n   *     this to VT100.\n   *     -> CSI  > Pp ; Pv ; Pc c\n   *   where Pp denotes the terminal type\n   *     Pp = 0  -> ``VT100''.\n   *     Pp = 1  -> ``VT220''.\n   *   and Pv is the firmware version (for xterm, this was originally\n   *   the XFree86 patch number, starting with 95).  In a DEC termi-\n   *   nal, Pc indicates the ROM cartridge registration number and is\n   *   always zero.\n   * More information:\n   *   xterm/charproc.c - line 2012, for more information.\n   *   vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)\n   */\n  public sendDeviceAttributesPrimary(params: IParams): void {\n    if (params.params[0] > 0) {\n      return;\n    }\n    if (this._terminal.is('xterm') || this._terminal.is('rxvt-unicode') || this._terminal.is('screen')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[?1;2c');\n    } else if (this._terminal.is('linux')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[?6c');\n    }\n  }\n  public sendDeviceAttributesSecondary(params: IParams): void {\n    if (params.params[0] > 0) {\n      return;\n    }\n    // xterm and urxvt\n    // seem to spit this\n    // out around ~370 times (?).\n    if (this._terminal.is('xterm')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c');\n    } else if (this._terminal.is('rxvt-unicode')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c');\n    } else if (this._terminal.is('linux')) {\n      // not supported by linux console.\n      // linux console echoes parameters.\n      this._coreService.triggerDataEvent(params.params[0] + 'c');\n    } else if (this._terminal.is('screen')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c');\n    }\n  }\n\n  /**\n   * CSI Pm h  Set Mode (SM).\n   *     Ps = 2  -> Keyboard Action Mode (AM).\n   *     Ps = 4  -> Insert Mode (IRM).\n   *     Ps = 1 2  -> Send/receive (SRM).\n   *     Ps = 2 0  -> Automatic Newline (LNM).\n   * CSI ? Pm h\n   *   DEC Private Mode Set (DECSET).\n   *     Ps = 1  -> Application Cursor Keys (DECCKM).\n   *     Ps = 2  -> Designate USASCII for character sets G0-G3\n   *     (DECANM), and set VT100 mode.\n   *     Ps = 3  -> 132 Column Mode (DECCOLM).\n   *     Ps = 4  -> Smooth (Slow) Scroll (DECSCLM).\n   *     Ps = 5  -> Reverse Video (DECSCNM).\n   *     Ps = 6  -> Origin Mode (DECOM).\n   *     Ps = 7  -> Wraparound Mode (DECAWM).\n   *     Ps = 8  -> Auto-repeat Keys (DECARM).\n   *     Ps = 9  -> Send Mouse X & Y on button press.  See the sec-\n   *     tion Mouse Tracking.\n   *     Ps = 1 0  -> Show toolbar (rxvt).\n   *     Ps = 1 2  -> Start Blinking Cursor (att610).\n   *     Ps = 1 8  -> Print form feed (DECPFF).\n   *     Ps = 1 9  -> Set print extent to full screen (DECPEX).\n   *     Ps = 2 5  -> Show Cursor (DECTCEM).\n   *     Ps = 3 0  -> Show scrollbar (rxvt).\n   *     Ps = 3 5  -> Enable font-shifting functions (rxvt).\n   *     Ps = 3 8  -> Enter Tektronix Mode (DECTEK).\n   *     Ps = 4 0  -> Allow 80 -> 132 Mode.\n   *     Ps = 4 1  -> more(1) fix (see curses resource).\n   *     Ps = 4 2  -> Enable Nation Replacement Character sets (DECN-\n   *     RCM).\n   *     Ps = 4 4  -> Turn On Margin Bell.\n   *     Ps = 4 5  -> Reverse-wraparound Mode.\n   *     Ps = 4 6  -> Start Logging.  This is normally disabled by a\n   *     compile-time option.\n   *     Ps = 4 7  -> Use Alternate Screen Buffer.  (This may be dis-\n   *     abled by the titeInhibit resource).\n   *     Ps = 6 6  -> Application keypad (DECNKM).\n   *     Ps = 6 7  -> Backarrow key sends backspace (DECBKM).\n   *     Ps = 1 0 0 0  -> Send Mouse X & Y on button press and\n   *     release.  See the section Mouse Tracking.\n   *     Ps = 1 0 0 1  -> Use Hilite Mouse Tracking.\n   *     Ps = 1 0 0 2  -> Use Cell Motion Mouse Tracking.\n   *     Ps = 1 0 0 3  -> Use All Motion Mouse Tracking.\n   *     Ps = 1 0 0 4  -> Send FocusIn/FocusOut events.\n   *     Ps = 1 0 0 5  -> Enable Extended Mouse Mode.\n   *     Ps = 1 0 1 0  -> Scroll to bottom on tty output (rxvt).\n   *     Ps = 1 0 1 1  -> Scroll to bottom on key press (rxvt).\n   *     Ps = 1 0 3 4  -> Interpret \"meta\" key, sets eighth bit.\n   *     (enables the eightBitInput resource).\n   *     Ps = 1 0 3 5  -> Enable special modifiers for Alt and Num-\n   *     Lock keys.  (This enables the numLock resource).\n   *     Ps = 1 0 3 6  -> Send ESC   when Meta modifies a key.  (This\n   *     enables the metaSendsEscape resource).\n   *     Ps = 1 0 3 7  -> Send DEL from the editing-keypad Delete\n   *     key.\n   *     Ps = 1 0 3 9  -> Send ESC  when Alt modifies a key.  (This\n   *     enables the altSendsEscape resource).\n   *     Ps = 1 0 4 0  -> Keep selection even if not highlighted.\n   *     (This enables the keepSelection resource).\n   *     Ps = 1 0 4 1  -> Use the CLIPBOARD selection.  (This enables\n   *     the selectToClipboard resource).\n   *     Ps = 1 0 4 2  -> Enable Urgency window manager hint when\n   *     Control-G is received.  (This enables the bellIsUrgent\n   *     resource).\n   *     Ps = 1 0 4 3  -> Enable raising of the window when Control-G\n   *     is received.  (enables the popOnBell resource).\n   *     Ps = 1 0 4 7  -> Use Alternate Screen Buffer.  (This may be\n   *     disabled by the titeInhibit resource).\n   *     Ps = 1 0 4 8  -> Save cursor as in DECSC.  (This may be dis-\n   *     abled by the titeInhibit resource).\n   *     Ps = 1 0 4 9  -> Save cursor as in DECSC and use Alternate\n   *     Screen Buffer, clearing it first.  (This may be disabled by\n   *     the titeInhibit resource).  This combines the effects of the 1\n   *     0 4 7  and 1 0 4 8  modes.  Use this with terminfo-based\n   *     applications rather than the 4 7  mode.\n   *     Ps = 1 0 5 0  -> Set terminfo/termcap function-key mode.\n   *     Ps = 1 0 5 1  -> Set Sun function-key mode.\n   *     Ps = 1 0 5 2  -> Set HP function-key mode.\n   *     Ps = 1 0 5 3  -> Set SCO function-key mode.\n   *     Ps = 1 0 6 0  -> Set legacy keyboard emulation (X11R6).\n   *     Ps = 1 0 6 1  -> Set VT220 keyboard emulation.\n   *     Ps = 2 0 0 4  -> Set bracketed paste mode.\n   * Modes:\n   *   http: *vt100.net/docs/vt220-rm/chapter4.html\n   */\n  public setMode(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 4:\n          this._terminal.insertMode = true;\n          break;\n        case 20:\n          // this._t.convertEol = true;\n          break;\n      }\n    }\n  }\n  public setModePrivate(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 1:\n          this._coreService.decPrivateModes.applicationCursorKeys = true;\n          break;\n        case 2:\n          this._terminal.setgCharset(0, DEFAULT_CHARSET);\n          this._terminal.setgCharset(1, DEFAULT_CHARSET);\n          this._terminal.setgCharset(2, DEFAULT_CHARSET);\n          this._terminal.setgCharset(3, DEFAULT_CHARSET);\n          // set VT100 mode here\n          break;\n        case 3: // 132 col mode\n          // TODO: move DECCOLM into compat addon\n          this._terminal.savedCols = this._bufferService.cols;\n          this._terminal.resize(132, this._bufferService.rows);\n          this._terminal.reset();\n          break;\n        case 6:\n          this._terminal.originMode = true;\n          this._setCursor(0, 0);\n          break;\n        case 7:\n          this._terminal.wraparoundMode = true;\n          break;\n        case 12:\n          // this.cursorBlink = true;\n          break;\n        case 66:\n          this._logService.debug('Serial port requested application keypad.');\n          this._terminal.applicationKeypad = true;\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          break;\n        case 9: // X10 Mouse\n          // no release, no motion, no wheel, no modifiers.\n          this._coreMouseService.activeProtocol = 'X10';\n          break;\n        case 1000: // vt200 mouse\n          // no motion.\n          this._coreMouseService.activeProtocol = 'VT200';\n          break;\n        case 1002: // button event mouse\n          this._coreMouseService.activeProtocol = 'DRAG';\n          break;\n        case 1003: // any event mouse\n          // any event - sends motion events,\n          // even if there is no button held down.\n          this._coreMouseService.activeProtocol = 'ANY';\n          break;\n        case 1004: // send focusin/focusout events\n          // focusin: ^[[I\n          // focusout: ^[[O\n          this._terminal.sendFocus = true;\n          break;\n        case 1005: // utf8 ext mode mouse - removed in #2507\n          this._logService.debug('DECSET 1005 not supported (see #2507)');\n          break;\n        case 1006: // sgr ext mode mouse\n          this._coreMouseService.activeEncoding = 'SGR';\n          break;\n        case 1015: // urxvt ext mode mouse - removed in #2507\n          this._logService.debug('DECSET 1015 not supported (see #2507)');\n          break;\n        case 25: // show cursor\n          this._terminal.cursorHidden = false;\n          break;\n        case 1048: // alt screen cursor\n          this.saveCursor();\n          break;\n        case 1049: // alt screen buffer cursor\n          this.saveCursor();\n          // FALL-THROUGH\n        case 47: // alt screen buffer\n        case 1047: // alt screen buffer\n          this._bufferService.buffers.activateAltBuffer(this._terminal.eraseAttrData());\n          this._terminal.refresh(0, this._bufferService.rows - 1);\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          this._terminal.showCursor();\n          break;\n        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n          this._terminal.bracketedPasteMode = true;\n          break;\n      }\n    }\n  }\n\n\n  /**\n   * CSI Pm l  Reset Mode (RM).\n   *     Ps = 2  -> Keyboard Action Mode (AM).\n   *     Ps = 4  -> Replace Mode (IRM).\n   *     Ps = 1 2  -> Send/receive (SRM).\n   *     Ps = 2 0  -> Normal Linefeed (LNM).\n   * CSI ? Pm l\n   *   DEC Private Mode Reset (DECRST).\n   *     Ps = 1  -> Normal Cursor Keys (DECCKM).\n   *     Ps = 2  -> Designate VT52 mode (DECANM).\n   *     Ps = 3  -> 80 Column Mode (DECCOLM).\n   *     Ps = 4  -> Jump (Fast) Scroll (DECSCLM).\n   *     Ps = 5  -> Normal Video (DECSCNM).\n   *     Ps = 6  -> Normal Cursor Mode (DECOM).\n   *     Ps = 7  -> No Wraparound Mode (DECAWM).\n   *     Ps = 8  -> No Auto-repeat Keys (DECARM).\n   *     Ps = 9  -> Don't send Mouse X & Y on button press.\n   *     Ps = 1 0  -> Hide toolbar (rxvt).\n   *     Ps = 1 2  -> Stop Blinking Cursor (att610).\n   *     Ps = 1 8  -> Don't print form feed (DECPFF).\n   *     Ps = 1 9  -> Limit print to scrolling region (DECPEX).\n   *     Ps = 2 5  -> Hide Cursor (DECTCEM).\n   *     Ps = 3 0  -> Don't show scrollbar (rxvt).\n   *     Ps = 3 5  -> Disable font-shifting functions (rxvt).\n   *     Ps = 4 0  -> Disallow 80 -> 132 Mode.\n   *     Ps = 4 1  -> No more(1) fix (see curses resource).\n   *     Ps = 4 2  -> Disable Nation Replacement Character sets (DEC-\n   *     NRCM).\n   *     Ps = 4 4  -> Turn Off Margin Bell.\n   *     Ps = 4 5  -> No Reverse-wraparound Mode.\n   *     Ps = 4 6  -> Stop Logging.  (This is normally disabled by a\n   *     compile-time option).\n   *     Ps = 4 7  -> Use Normal Screen Buffer.\n   *     Ps = 6 6  -> Numeric keypad (DECNKM).\n   *     Ps = 6 7  -> Backarrow key sends delete (DECBKM).\n   *     Ps = 1 0 0 0  -> Don't send Mouse X & Y on button press and\n   *     release.  See the section Mouse Tracking.\n   *     Ps = 1 0 0 1  -> Don't use Hilite Mouse Tracking.\n   *     Ps = 1 0 0 2  -> Don't use Cell Motion Mouse Tracking.\n   *     Ps = 1 0 0 3  -> Don't use All Motion Mouse Tracking.\n   *     Ps = 1 0 0 4  -> Don't send FocusIn/FocusOut events.\n   *     Ps = 1 0 0 5  -> Disable Extended Mouse Mode.\n   *     Ps = 1 0 1 0  -> Don't scroll to bottom on tty output\n   *     (rxvt).\n   *     Ps = 1 0 1 1  -> Don't scroll to bottom on key press (rxvt).\n   *     Ps = 1 0 3 4  -> Don't interpret \"meta\" key.  (This disables\n   *     the eightBitInput resource).\n   *     Ps = 1 0 3 5  -> Disable special modifiers for Alt and Num-\n   *     Lock keys.  (This disables the numLock resource).\n   *     Ps = 1 0 3 6  -> Don't send ESC  when Meta modifies a key.\n   *     (This disables the metaSendsEscape resource).\n   *     Ps = 1 0 3 7  -> Send VT220 Remove from the editing-keypad\n   *     Delete key.\n   *     Ps = 1 0 3 9  -> Don't send ESC  when Alt modifies a key.\n   *     (This disables the altSendsEscape resource).\n   *     Ps = 1 0 4 0  -> Do not keep selection when not highlighted.\n   *     (This disables the keepSelection resource).\n   *     Ps = 1 0 4 1  -> Use the PRIMARY selection.  (This disables\n   *     the selectToClipboard resource).\n   *     Ps = 1 0 4 2  -> Disable Urgency window manager hint when\n   *     Control-G is received.  (This disables the bellIsUrgent\n   *     resource).\n   *     Ps = 1 0 4 3  -> Disable raising of the window when Control-\n   *     G is received.  (This disables the popOnBell resource).\n   *     Ps = 1 0 4 7  -> Use Normal Screen Buffer, clearing screen\n   *     first if in the Alternate Screen.  (This may be disabled by\n   *     the titeInhibit resource).\n   *     Ps = 1 0 4 8  -> Restore cursor as in DECRC.  (This may be\n   *     disabled by the titeInhibit resource).\n   *     Ps = 1 0 4 9  -> Use Normal Screen Buffer and restore cursor\n   *     as in DECRC.  (This may be disabled by the titeInhibit\n   *     resource).  This combines the effects of the 1 0 4 7  and 1 0\n   *     4 8  modes.  Use this with terminfo-based applications rather\n   *     than the 4 7  mode.\n   *     Ps = 1 0 5 0  -> Reset terminfo/termcap function-key mode.\n   *     Ps = 1 0 5 1  -> Reset Sun function-key mode.\n   *     Ps = 1 0 5 2  -> Reset HP function-key mode.\n   *     Ps = 1 0 5 3  -> Reset SCO function-key mode.\n   *     Ps = 1 0 6 0  -> Reset legacy keyboard emulation (X11R6).\n   *     Ps = 1 0 6 1  -> Reset keyboard emulation to Sun/PC style.\n   *     Ps = 2 0 0 4  -> Reset bracketed paste mode.\n   */\n  public resetMode(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 4:\n          this._terminal.insertMode = false;\n          break;\n        case 20:\n          // this._t.convertEol = false;\n          break;\n      }\n    }\n  }\n  public resetModePrivate(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 1:\n          this._coreService.decPrivateModes.applicationCursorKeys = false;\n          break;\n        case 3:\n          // TODO: move DECCOLM into compat addon\n          // Note: This impl currently does not enforce col 80, instead reverts\n          // to previous terminal width before entering DECCOLM 132\n          if (this._bufferService.cols === 132 && this._terminal.savedCols) {\n            this._terminal.resize(this._terminal.savedCols, this._bufferService.rows);\n          }\n          delete this._terminal.savedCols;\n          this._terminal.reset();\n          break;\n        case 6:\n          this._terminal.originMode = false;\n          this._setCursor(0, 0);\n          break;\n        case 7:\n          this._terminal.wraparoundMode = false;\n          break;\n        case 12:\n          // this.cursorBlink = false;\n          break;\n        case 66:\n          this._logService.debug('Switching back to normal keypad.');\n          this._terminal.applicationKeypad = false;\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          break;\n        case 9: // X10 Mouse\n        case 1000: // vt200 mouse\n        case 1002: // button event mouse\n        case 1003: // any event mouse\n          this._coreMouseService.activeProtocol = 'NONE';\n          break;\n        case 1004: // send focusin/focusout events\n          this._terminal.sendFocus = false;\n          break;\n        case 1005: // utf8 ext mode mouse - removed in #2507\n          this._logService.debug('DECRST 1005 not supported (see #2507)');\n          break;\n        case 1006: // sgr ext mode mouse\n          this._coreMouseService.activeEncoding = 'DEFAULT';\n          break;\n        case 1015: // urxvt ext mode mouse - removed in #2507\n        this._logService.debug('DECRST 1015 not supported (see #2507)');\n          break;\n        case 25: // hide cursor\n          this._terminal.cursorHidden = true;\n          break;\n        case 1048: // alt screen cursor\n          this.restoreCursor();\n          break;\n        case 1049: // alt screen buffer cursor\n           // FALL-THROUGH\n        case 47: // normal screen buffer\n        case 1047: // normal screen buffer - clearing it first\n          // Ensure the selection manager has the correct buffer\n          this._bufferService.buffers.activateNormalBuffer();\n          if (params.params[i] === 1049) {\n            this.restoreCursor();\n          }\n          this._terminal.refresh(0, this._bufferService.rows - 1);\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          this._terminal.showCursor();\n          break;\n        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n          this._terminal.bracketedPasteMode = false;\n          break;\n      }\n    }\n  }\n\n  /**\n   * Helper to extract and apply color params/subparams.\n   * Returns advance for params index.\n   */\n  private _extractColor(params: IParams, pos: number, attr: IAttributeData): number {\n    // normalize params\n    // meaning: [target, CM, ign, val, val, val]\n    // RGB    : [ 38/48,  2, ign,   r,   g,   b]\n    // P256   : [ 38/48,  5, ign,   v, ign, ign]\n    const accu = [0, 0, -1, 0, 0, 0];\n\n    // alignment placeholder for non color space sequences\n    let cSpace = 0;\n\n    // return advance we took in params\n    let advance = 0;\n\n    do {\n      accu[advance + cSpace] = params.params[pos + advance];\n      if (params.hasSubParams(pos + advance)) {\n        const subparams = params.getSubParams(pos + advance);\n        let i = 0;\n        do {\n          if (accu[1] === 5) {\n            cSpace = 1;\n          }\n          accu[advance + i + 1 + cSpace] = subparams[i];\n        } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length);\n        break;\n      }\n      // exit early if can decide color mode with semicolons\n      if ((accu[1] === 5 && advance + cSpace >= 2)\n          || (accu[1] === 2 && advance + cSpace >= 5)) {\n        break;\n      }\n      // offset colorSpace slot for semicolon mode\n      if (accu[1]) {\n        cSpace = 1;\n      }\n    } while (++advance + pos < params.length && advance + cSpace < accu.length);\n\n    // set default values to 0\n    for (let i = 2; i < accu.length; ++i) {\n      if (accu[i] === -1) {\n        accu[i] = 0;\n      }\n    }\n\n    // apply colors\n    if (accu[0] === 38) {\n      if (accu[1] === 2) {\n        attr.fg |= Attributes.CM_RGB;\n        attr.fg &= ~Attributes.RGB_MASK;\n        attr.fg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);\n      } else if (accu[1] === 5) {\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.fg |= Attributes.CM_P256 | (accu[3] & 0xff);\n      }\n    } else if (accu[0] === 48) {\n      if (accu[1] === 2) {\n        attr.bg |= Attributes.CM_RGB;\n        attr.bg &= ~Attributes.RGB_MASK;\n        attr.bg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);\n      } else if (accu[1] === 5) {\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.bg |= Attributes.CM_P256 | (accu[3] & 0xff);\n      }\n    }\n\n    return advance;\n  }\n\n  /**\n   * CSI Pm m  Character Attributes (SGR).\n   *     Ps = 0  -> Normal (default).\n   *     Ps = 1  -> Bold.\n   *     Ps = 2  -> Faint, decreased intensity (ISO 6429).\n   *     Ps = 4  -> Underlined.\n   *     Ps = 5  -> Blink (appears as Bold).\n   *     Ps = 7  -> Inverse.\n   *     Ps = 8  -> Invisible, i.e., hidden (VT300).\n   *     Ps = 2 2  -> Normal (neither bold nor faint).\n   *     Ps = 2 4  -> Not underlined.\n   *     Ps = 2 5  -> Steady (not blinking).\n   *     Ps = 2 7  -> Positive (not inverse).\n   *     Ps = 2 8  -> Visible, i.e., not hidden (VT300).\n   *     Ps = 3 0  -> Set foreground color to Black.\n   *     Ps = 3 1  -> Set foreground color to Red.\n   *     Ps = 3 2  -> Set foreground color to Green.\n   *     Ps = 3 3  -> Set foreground color to Yellow.\n   *     Ps = 3 4  -> Set foreground color to Blue.\n   *     Ps = 3 5  -> Set foreground color to Magenta.\n   *     Ps = 3 6  -> Set foreground color to Cyan.\n   *     Ps = 3 7  -> Set foreground color to White.\n   *     Ps = 3 9  -> Set foreground color to default (original).\n   *     Ps = 4 0  -> Set background color to Black.\n   *     Ps = 4 1  -> Set background color to Red.\n   *     Ps = 4 2  -> Set background color to Green.\n   *     Ps = 4 3  -> Set background color to Yellow.\n   *     Ps = 4 4  -> Set background color to Blue.\n   *     Ps = 4 5  -> Set background color to Magenta.\n   *     Ps = 4 6  -> Set background color to Cyan.\n   *     Ps = 4 7  -> Set background color to White.\n   *     Ps = 4 9  -> Set background color to default (original).\n   *\n   *   If 16-color support is compiled, the following apply.  Assume\n   *   that xterm's resources are set so that the ISO color codes are\n   *   the first 8 of a set of 16.  Then the aixterm colors are the\n   *   bright versions of the ISO colors:\n   *     Ps = 9 0  -> Set foreground color to Black.\n   *     Ps = 9 1  -> Set foreground color to Red.\n   *     Ps = 9 2  -> Set foreground color to Green.\n   *     Ps = 9 3  -> Set foreground color to Yellow.\n   *     Ps = 9 4  -> Set foreground color to Blue.\n   *     Ps = 9 5  -> Set foreground color to Magenta.\n   *     Ps = 9 6  -> Set foreground color to Cyan.\n   *     Ps = 9 7  -> Set foreground color to White.\n   *     Ps = 1 0 0  -> Set background color to Black.\n   *     Ps = 1 0 1  -> Set background color to Red.\n   *     Ps = 1 0 2  -> Set background color to Green.\n   *     Ps = 1 0 3  -> Set background color to Yellow.\n   *     Ps = 1 0 4  -> Set background color to Blue.\n   *     Ps = 1 0 5  -> Set background color to Magenta.\n   *     Ps = 1 0 6  -> Set background color to Cyan.\n   *     Ps = 1 0 7  -> Set background color to White.\n   *\n   *   If xterm is compiled with the 16-color support disabled, it\n   *   supports the following, from rxvt:\n   *     Ps = 1 0 0  -> Set foreground and background color to\n   *     default.\n   *\n   *   If 88- or 256-color support is compiled, the following apply.\n   *     Ps = 3 8  ; 5  ; Ps -> Set foreground color to the second\n   *     Ps.\n   *     Ps = 4 8  ; 5  ; Ps -> Set background color to the second\n   *     Ps.\n   */\n  public charAttributes(params: IParams): void {\n    // Optimize a single SGR0.\n    if (params.length === 1 && params.params[0] === 0) {\n      this._terminal.curAttrData.fg = DEFAULT_ATTR_DATA.fg;\n      this._terminal.curAttrData.bg = DEFAULT_ATTR_DATA.bg;\n      return;\n    }\n\n    const l = params.length;\n    let p;\n    const attr = this._terminal.curAttrData;\n\n    for (let i = 0; i < l; i++) {\n      p = params.params[i];\n      if (p >= 30 && p <= 37) {\n        // fg color 8\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.fg |= Attributes.CM_P16 | (p - 30);\n      } else if (p >= 40 && p <= 47) {\n        // bg color 8\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.bg |= Attributes.CM_P16 | (p - 40);\n      } else if (p >= 90 && p <= 97) {\n        // fg color 16\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.fg |= Attributes.CM_P16 | (p - 90) | 8;\n      } else if (p >= 100 && p <= 107) {\n        // bg color 16\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.bg |= Attributes.CM_P16 | (p - 100) | 8;\n      } else if (p === 0) {\n        // default\n        attr.fg = DEFAULT_ATTR_DATA.fg;\n        attr.bg = DEFAULT_ATTR_DATA.bg;\n      } else if (p === 1) {\n        // bold text\n        attr.fg |= FgFlags.BOLD;\n      } else if (p === 3) {\n        // italic text\n        attr.bg |= BgFlags.ITALIC;\n      } else if (p === 4) {\n        // underlined text\n        attr.fg |= FgFlags.UNDERLINE;\n      } else if (p === 5) {\n        // blink\n        attr.fg |= FgFlags.BLINK;\n      } else if (p === 7) {\n        // inverse and positive\n        // test with: echo -e '\\e[31m\\e[42mhello\\e[7mworld\\e[27mhi\\e[m'\n        attr.fg |= FgFlags.INVERSE;\n      } else if (p === 8) {\n        // invisible\n        attr.fg |= FgFlags.INVISIBLE;\n      } else if (p === 2) {\n        // dimmed text\n        attr.bg |= BgFlags.DIM;\n      } else if (p === 22) {\n        // not bold nor faint\n        attr.fg &= ~FgFlags.BOLD;\n        attr.bg &= ~BgFlags.DIM;\n      } else if (p === 23) {\n        // not italic\n        attr.bg &= ~BgFlags.ITALIC;\n      } else if (p === 24) {\n        // not underlined\n        attr.fg &= ~FgFlags.UNDERLINE;\n      } else if (p === 25) {\n        // not blink\n        attr.fg &= ~FgFlags.BLINK;\n      } else if (p === 27) {\n        // not inverse\n        attr.fg &= ~FgFlags.INVERSE;\n      } else if (p === 28) {\n        // not invisible\n        attr.fg &= ~FgFlags.INVISIBLE;\n      } else if (p === 39) {\n        // reset fg\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n      } else if (p === 49) {\n        // reset bg\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n      } else if (p === 38 || p === 48) {\n        // fg color 256 and RGB\n        i += this._extractColor(params, i, attr);\n      } else if (p === 100) {\n        // reset fg/bg\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n      } else {\n        this._logService.debug('Unknown SGR attribute: %d.', p);\n      }\n    }\n  }\n\n  /**\n   * CSI Ps n  Device Status Report (DSR).\n   *     Ps = 5  -> Status Report.  Result (``OK'') is\n   *   CSI 0 n\n   *     Ps = 6  -> Report Cursor Position (CPR) [row;column].\n   *   Result is\n   *   CSI r ; c R\n   * CSI ? Ps n\n   *   Device Status Report (DSR, DEC-specific).\n   *     Ps = 6  -> Report Cursor Position (CPR) [row;column] as CSI\n   *     ? r ; c R (assumes page is zero).\n   *     Ps = 1 5  -> Report Printer status as CSI ? 1 0  n  (ready).\n   *     or CSI ? 1 1  n  (not ready).\n   *     Ps = 2 5  -> Report UDK status as CSI ? 2 0  n  (unlocked)\n   *     or CSI ? 2 1  n  (locked).\n   *     Ps = 2 6  -> Report Keyboard status as\n   *   CSI ? 2 7  ;  1  ;  0  ;  0  n  (North American).\n   *   The last two parameters apply to VT400 & up, and denote key-\n   *   board ready and LK01 respectively.\n   *     Ps = 5 3  -> Report Locator status as\n   *   CSI ? 5 3  n  Locator available, if compiled-in, or\n   *   CSI ? 5 0  n  No Locator, if not.\n   */\n  public deviceStatus(params: IParams): void {\n    switch (params.params[0]) {\n      case 5:\n        // status report\n        this._coreService.triggerDataEvent(`${C0.ESC}[0n`);\n        break;\n      case 6:\n        // cursor position\n        const y = this._bufferService.buffer.y + 1;\n        const x = this._bufferService.buffer.x + 1;\n        this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`);\n        break;\n    }\n  }\n\n  public deviceStatusPrivate(params: IParams): void {\n    // modern xterm doesnt seem to\n    // respond to any of these except ?6, 6, and 5\n    switch (params.params[0]) {\n      case 6:\n        // cursor position\n        const y = this._bufferService.buffer.y + 1;\n        const x = this._bufferService.buffer.x + 1;\n        this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`);\n        break;\n      case 15:\n        // no printer\n        // this.handler(C0.ESC + '[?11n');\n        break;\n      case 25:\n        // dont support user defined keys\n        // this.handler(C0.ESC + '[?21n');\n        break;\n      case 26:\n        // north american keyboard\n        // this.handler(C0.ESC + '[?27;1;0;0n');\n        break;\n      case 53:\n        // no dec locator/mouse\n        // this.handler(C0.ESC + '[?50n');\n        break;\n    }\n  }\n\n  /**\n   * CSI ! p   Soft terminal reset (DECSTR).\n   * http://vt100.net/docs/vt220-rm/table4-10.html\n   */\n  public softReset(params: IParams): void {\n    this._terminal.cursorHidden = false;\n    this._terminal.insertMode = false;\n    this._terminal.originMode = false;\n    this._terminal.wraparoundMode = true;  // defaults: xterm - true, vt100 - false\n    this._terminal.applicationKeypad = false; // ?\n    if (this._terminal.viewport) {\n      this._terminal.viewport.syncScrollArea();\n    }\n    this._coreService.decPrivateModes.applicationCursorKeys = false;\n    this._bufferService.buffer.scrollTop = 0;\n    this._bufferService.buffer.scrollBottom = this._bufferService.rows - 1;\n    this._terminal.curAttrData = DEFAULT_ATTR_DATA.clone();\n    this._bufferService.buffer.x = this._bufferService.buffer.y = 0; // ?\n    this._terminal.charset = null;\n    this._terminal.glevel = 0; // ??\n    this._terminal.charsets = [null]; // ??\n  }\n\n  /**\n   * CSI Ps SP q  Set cursor style (DECSCUSR, VT520).\n   *   Ps = 0  -> blinking block.\n   *   Ps = 1  -> blinking block (default).\n   *   Ps = 2  -> steady block.\n   *   Ps = 3  -> blinking underline.\n   *   Ps = 4  -> steady underline.\n   *   Ps = 5  -> blinking bar (xterm).\n   *   Ps = 6  -> steady bar (xterm).\n   */\n  public setCursorStyle(params: IParams): void {\n    const param = params.params[0] || 1;\n    switch (param) {\n      case 1:\n      case 2:\n        this._optionsService.options.cursorStyle = 'block';\n        break;\n      case 3:\n      case 4:\n        this._optionsService.options.cursorStyle = 'underline';\n        break;\n      case 5:\n      case 6:\n        this._optionsService.options.cursorStyle = 'bar';\n        break;\n    }\n    const isBlinking = param % 2 === 1;\n    this._optionsService.options.cursorBlink = isBlinking;\n  }\n\n  /**\n   * CSI Ps ; Ps r\n   *   Set Scrolling Region [top;bottom] (default = full size of win-\n   *   dow) (DECSTBM).\n   */\n  public setScrollRegion(params: IParams): void {\n    const top = params.params[0] || 1;\n    let bottom: number;\n\n    if (params.length < 2 || (bottom = params.params[1]) >  this._bufferService.rows || bottom === 0) {\n      bottom = this._bufferService.rows;\n    }\n\n    if (bottom > top) {\n      this._bufferService.buffer.scrollTop = top - 1;\n      this._bufferService.buffer.scrollBottom = bottom - 1;\n      this._setCursor(0, 0);\n    }\n  }\n\n\n  /**\n   * CSI s\n   * ESC 7\n   *   Save cursor (ANSI.SYS).\n   */\n  public saveCursor(params?: IParams): void {\n    this._bufferService.buffer.savedX = this._bufferService.buffer.x;\n    this._bufferService.buffer.savedY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;\n    this._bufferService.buffer.savedCurAttrData.fg = this._terminal.curAttrData.fg;\n    this._bufferService.buffer.savedCurAttrData.bg = this._terminal.curAttrData.bg;\n    this._bufferService.buffer.savedCharset = this._terminal.charset;\n  }\n\n\n  /**\n   * CSI u\n   * ESC 8\n   *   Restore cursor (ANSI.SYS).\n   */\n  public restoreCursor(params?: IParams): void {\n    this._bufferService.buffer.x = this._bufferService.buffer.savedX || 0;\n    this._bufferService.buffer.y = Math.max(this._bufferService.buffer.savedY - this._bufferService.buffer.ybase, 0);\n    this._terminal.curAttrData.fg = this._bufferService.buffer.savedCurAttrData.fg;\n    this._terminal.curAttrData.bg = this._bufferService.buffer.savedCurAttrData.bg;\n    this._terminal.charset = (this as any)._savedCharset;\n    if (this._bufferService.buffer.savedCharset) {\n      this._terminal.charset = this._bufferService.buffer.savedCharset;\n    }\n    this._restrictCursor();\n  }\n\n\n  /**\n   * OSC 0; <data> ST (set icon name + window title)\n   * OSC 2; <data> ST (set window title)\n   *   Proxy to set window title. Icon name is not supported.\n   */\n  public setTitle(data: string): void {\n    this._terminal.handleTitle(data);\n  }\n\n  /**\n   * ESC E\n   * C1.NEL\n   *   DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL)\n   *   Moves cursor to first position on next line.\n   */\n  public nextLine(): void {\n    this._bufferService.buffer.x = 0;\n    this.index();\n  }\n\n  /**\n   * ESC =\n   *   DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html)\n   *   Enables the numeric keypad to send application sequences to the host.\n   */\n  public keypadApplicationMode(): void {\n    this._logService.debug('Serial port requested application keypad.');\n    this._terminal.applicationKeypad = true;\n    if (this._terminal.viewport) {\n      this._terminal.viewport.syncScrollArea();\n    }\n  }\n\n  /**\n   * ESC >\n   *   DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html)\n   *   Enables the keypad to send numeric characters to the host.\n   */\n  public keypadNumericMode(): void {\n    this._logService.debug('Switching back to normal keypad.');\n    this._terminal.applicationKeypad = false;\n    if (this._terminal.viewport) {\n      this._terminal.viewport.syncScrollArea();\n    }\n  }\n\n  /**\n   * ESC % @\n   * ESC % G\n   *   Select default character set. UTF-8 is not supported (string are unicode anyways)\n   *   therefore ESC % G does the same.\n   */\n  public selectDefaultCharset(): void {\n    this._terminal.setgLevel(0);\n    this._terminal.setgCharset(0, DEFAULT_CHARSET); // US (default)\n  }\n\n  /**\n   * ESC ( C\n   *   Designate G0 Character Set, VT100, ISO 2022.\n   * ESC ) C\n   *   Designate G1 Character Set (ISO 2022, VT100).\n   * ESC * C\n   *   Designate G2 Character Set (ISO 2022, VT220).\n   * ESC + C\n   *   Designate G3 Character Set (ISO 2022, VT220).\n   * ESC - C\n   *   Designate G1 Character Set (VT300).\n   * ESC . C\n   *   Designate G2 Character Set (VT300).\n   * ESC / C\n   *   Designate G3 Character Set (VT300). C = A  -> ISO Latin-1 Supplemental. - Supported?\n   */\n  public selectCharset(collectAndFlag: string): void {\n    if (collectAndFlag.length !== 2) {\n      this.selectDefaultCharset();\n      return;\n    }\n    if (collectAndFlag[0] === '/') {\n      return;  // TODO: Is this supported?\n    }\n    this._terminal.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET);\n    return;\n  }\n\n  /**\n   * ESC D\n   * C1.IND\n   *   DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html)\n   *   Moves the cursor down one line in the same column.\n   */\n  public index(): void {\n    this._restrictCursor();\n    const buffer = this._bufferService.buffer;\n    this._bufferService.buffer.y++;\n    if (buffer.y === buffer.scrollBottom + 1) {\n      buffer.y--;\n      this._terminal.scroll();\n    } else if (buffer.y >= this._bufferService.rows) {\n      buffer.y = this._bufferService.rows - 1;\n    }\n    this._restrictCursor();\n  }\n\n  /**\n   * ESC H\n   * C1.HTS\n   *   DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html)\n   *   Sets a horizontal tab stop at the column position indicated by\n   *   the value of the active column when the terminal receives an HTS.\n   */\n  public tabSet(): void {\n    this._bufferService.buffer.tabs[this._bufferService.buffer.x] = true;\n  }\n\n  /**\n   * ESC M\n   * C1.RI\n   *   DEC mnemonic: HTS\n   *   Moves the cursor up one line in the same column. If the cursor is at the top margin,\n   *   the page scrolls down.\n   */\n  public reverseIndex(): void {\n    this._restrictCursor();\n    const buffer = this._bufferService.buffer;\n    if (buffer.y === buffer.scrollTop) {\n      // possibly move the code below to term.reverseScroll();\n      // test: echo -ne '\\e[1;1H\\e[44m\\eM\\e[0m'\n      // blankLine(true) is xterm/linux behavior\n      const scrollRegionHeight = buffer.scrollBottom - buffer.scrollTop;\n      buffer.lines.shiftElements(buffer.y + buffer.ybase, scrollRegionHeight, 1);\n      buffer.lines.set(buffer.y + buffer.ybase, buffer.getBlankLine(this._terminal.eraseAttrData()));\n      this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n    } else {\n      buffer.y--;\n      this._restrictCursor(); // quickfix to not run out of bounds\n    }\n  }\n\n  /**\n   * ESC c\n   *   DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html)\n   *   Reset to initial state.\n   */\n  public reset(): void {\n    this._parser.reset();\n    this._terminal.reset();  // TODO: save to move from terminal?\n  }\n\n  /**\n   * ESC n\n   * ESC o\n   * ESC |\n   * ESC }\n   * ESC ~\n   *   DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html)\n   *   When you use a locking shift, the character set remains in GL or GR until\n   *   you use another locking shift. (partly supported)\n   */\n  public setgLevel(level: number): void {\n    this._terminal.setgLevel(level);  // TODO: save to move from terminal?\n  }\n\n  /**\n   * ESC # 8\n   *   DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html)\n   *   This control function fills the complete screen area with\n   *   a test pattern (E) used for adjusting screen alignment.\n   *\n   * TODO: move DECALN into compat addon\n   */\n  public screenAlignmentPattern(): void {\n    // prepare cell data\n    const cell = new CellData();\n    cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0);\n    cell.fg = this._terminal.curAttrData.fg;\n    cell.bg = this._terminal.curAttrData.bg;\n\n    const buffer = this._bufferService.buffer;\n\n    this._setCursor(0, 0);\n    for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) {\n      const row = buffer.y + buffer.ybase + yOffset;\n      buffer.lines.get(row).fill(cell);\n      buffer.lines.get(row).isWrapped = false;\n    }\n    this._dirtyRowService.markAllDirty();\n    this._setCursor(0, 0);\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType } from 'common/parser/Types';\nimport { ParserState, ParserAction } from 'common/parser/Constants';\nimport { Disposable } from 'common/Lifecycle';\nimport { IDisposable } from 'common/Types';\nimport { fill } from 'common/TypedArrayUtils';\nimport { Params } from 'common/parser/Params';\nimport { OscParser } from 'common/parser/OscParser';\nimport { DcsParser } from 'common/parser/DcsParser';\n\n/**\n * Table values are generated like this:\n *    index:  currentState << TableValue.INDEX_STATE_SHIFT | charCode\n *    value:  action << TableValue.TRANSITION_ACTION_SHIFT | nextState\n */\nconst enum TableAccess {\n  TRANSITION_ACTION_SHIFT = 4,\n  TRANSITION_STATE_MASK = 15,\n  INDEX_STATE_SHIFT = 8\n}\n\n/**\n * Transition table for EscapeSequenceParser.\n */\nexport class TransitionTable {\n  public table: Uint8Array;\n\n  constructor(length: number) {\n    this.table = new Uint8Array(length);\n  }\n\n  /**\n   * Set default transition.\n   * @param action default action\n   * @param next default next state\n   */\n  public setDefault(action: ParserAction, next: ParserState): void {\n    fill(this.table, action << TableAccess.TRANSITION_ACTION_SHIFT | next);\n  }\n\n  /**\n   * Add a transition to the transition table.\n   * @param code input character code\n   * @param state current parser state\n   * @param action parser action to be done\n   * @param next next parser state\n   */\n  public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {\n    this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n  }\n\n  /**\n   * Add transitions for multiple input character codes.\n   * @param codes input character code array\n   * @param state current parser state\n   * @param action parser action to be done\n   * @param next next parser state\n   */\n  public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {\n    for (let i = 0; i < codes.length; i++) {\n      this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n    }\n  }\n}\n\n\n// Pseudo-character placeholder for printable non-ascii characters (unicode).\nconst NON_ASCII_PRINTABLE = 0xA0;\n\n\n/**\n * VT500 compatible transition table.\n * Taken from https://vt100.net/emu/dec_ansi_parser.\n */\nexport const VT500_TRANSITION_TABLE = (function (): TransitionTable {\n  const table: TransitionTable = new TransitionTable(4095);\n\n  // range macro for byte\n  const BYTE_VALUES = 256;\n  const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);\n  const r = (start: number, end: number) => blueprint.slice(start, end);\n\n  // Default definitions.\n  const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded\n  const EXECUTABLES = r(0x00, 0x18);\n  EXECUTABLES.push(0x19);\n  EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));\n\n  const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);\n  let state: any;\n\n  // set default transition\n  table.setDefault(ParserAction.ERROR, ParserState.GROUND);\n  // printables\n  table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n  // global anywhere rules\n  for (state in states) {\n    table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);\n    table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);\n    table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);\n    table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator\n    table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE);  // ESC\n    table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING);  // OSC\n    table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n    table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY);  // CSI\n    table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY);  // DCS\n  }\n  // rules for executables and 7f\n  table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);\n  table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);\n  table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);\n  table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n  table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);\n  table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);\n  table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);\n  table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);\n  table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);\n  table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);\n  table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);\n  table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);\n  table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);\n  // osc\n  table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);\n  table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n  table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n  table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);\n  table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n  // sos/pm/apc does nothing\n  table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);\n  table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  // csi entries\n  table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);\n  table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);\n  table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n  table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n  table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n  // esc_intermediate\n  table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n  table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n  table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  // dcs entry\n  table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);\n  table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n  table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n  table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);\n  table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n  table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n  table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n  table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n  table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n  table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n  table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n  table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n  table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n  table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);\n  table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);\n  // special handling of unicode chars\n  table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n  table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n  table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n  return table;\n})();\n\n\n/**\n * EscapeSequenceParser.\n * This class implements the ANSI/DEC compatible parser described by\n * Paul Williams (https://vt100.net/emu/dec_ansi_parser).\n *\n * To implement custom ANSI compliant escape sequences it is not needed to\n * alter this parser, instead consider registering a custom handler.\n * For non ANSI compliant sequences change the transition table with\n * the optional `transitions` constructor argument and\n * reimplement the `parse` method.\n *\n * This parser is currently hardcoded to operate in ZDM (Zero Default Mode)\n * as suggested by the original parser, thus empty parameters are set to 0.\n * This this is not in line with the latest ECMA-48 specification\n * (ZDM was part of the early specs and got completely removed later on).\n *\n * Other than the original parser from vt100.net this parser supports\n * sub parameters in digital parameters separated by colons. Empty sub parameters\n * are set to -1 (no ZDM for sub parameters).\n *\n * About prefix and intermediate bytes:\n * This parser follows the assumptions of the vt100.net parser with these restrictions:\n * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f\n * - max. two intermediates are respected, byte range 0x20 .. 0x2f\n * Note that this is not in line with ECMA-48 which does not limit either of those.\n * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently\n * there are no known sequences that follow the broader definition of the specification.\n *\n * TODO: implement error recovery hook via error handler return values\n */\nexport class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser {\n  public initialState: number;\n  public currentState: number;\n  public precedingCodepoint: number;\n\n  // buffers over several parse calls\n  protected _params: Params;\n  protected _collect: number;\n\n  // handler lookup containers\n  protected _printHandler: PrintHandlerType;\n  protected _executeHandlers: {[flag: number]: ExecuteHandlerType};\n  protected _csiHandlers: IHandlerCollection<CsiHandlerType>;\n  protected _escHandlers: IHandlerCollection<EscHandlerType>;\n  protected _oscParser: IOscParser;\n  protected _dcsParser: IDcsParser;\n  protected _errorHandler: (state: IParsingState) => IParsingState;\n\n  // fallback handlers\n  protected _printHandlerFb: PrintFallbackHandlerType;\n  protected _executeHandlerFb: ExecuteFallbackHandlerType;\n  protected _csiHandlerFb: CsiFallbackHandlerType;\n  protected _escHandlerFb: EscFallbackHandlerType;\n  protected _errorHandlerFb: (state: IParsingState) => IParsingState;\n\n  constructor(readonly TRANSITIONS: TransitionTable = VT500_TRANSITION_TABLE) {\n    super();\n\n    this.initialState = ParserState.GROUND;\n    this.currentState = this.initialState;\n    this._params = new Params(); // defaults to 32 storable params/subparams\n    this._params.addParam(0);    // ZDM\n    this._collect = 0;\n    this.precedingCodepoint = 0;\n\n    // set default fallback handlers and handler lookup containers\n    this._printHandlerFb = (data, start, end): void => { };\n    this._executeHandlerFb = (code: number): void => { };\n    this._csiHandlerFb = (ident: number, params: IParams): void => { };\n    this._escHandlerFb = (ident: number): void => { };\n    this._errorHandlerFb = (state: IParsingState): IParsingState => state;\n    this._printHandler = this._printHandlerFb;\n    this._executeHandlers = Object.create(null);\n    this._csiHandlers = Object.create(null);\n    this._escHandlers = Object.create(null);\n    this._oscParser = new OscParser();\n    this._dcsParser = new DcsParser();\n    this._errorHandler = this._errorHandlerFb;\n\n    // swallow 7bit ST (ESC+\\)\n    this.setEscHandler({final: '\\\\'}, () => {});\n  }\n\n  protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {\n    let res = 0;\n    if (id.prefix) {\n      if (id.prefix.length > 1) {\n        throw new Error('only one byte as prefix supported');\n      }\n      res = id.prefix.charCodeAt(0);\n      if (res && 0x3c > res || res > 0x3f) {\n        throw new Error('prefix must be in range 0x3c .. 0x3f');\n      }\n    }\n    if (id.intermediates) {\n      if (id.intermediates.length > 2) {\n        throw new Error('only two bytes as intermediates are supported');\n      }\n      for (let i = 0; i < id.intermediates.length; ++i) {\n        const intermediate = id.intermediates.charCodeAt(i);\n        if (0x20 > intermediate || intermediate > 0x2f) {\n          throw new Error('intermediate must be in range 0x20 .. 0x2f');\n        }\n        res <<= 8;\n        res |= intermediate;\n      }\n    }\n    if (id.final.length !== 1) {\n      throw new Error('final must be a single byte');\n    }\n    const finalCode = id.final.charCodeAt(0);\n    if (finalRange[0] > finalCode || finalCode > finalRange[1]) {\n      throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);\n    }\n    res <<= 8;\n    res |= finalCode;\n\n    return res;\n  }\n\n  public identToString(ident: number): string {\n    const res: string[] = [];\n    while (ident) {\n      res.push(String.fromCharCode(ident & 0xFF));\n      ident >>= 8;\n    }\n    return res.reverse().join('');\n  }\n\n  public dispose(): void {\n    this._csiHandlers = Object.create(null);\n    this._executeHandlers = Object.create(null);\n    this._escHandlers = Object.create(null);\n    this._oscParser.dispose();\n    this._dcsParser.dispose();\n  }\n\n  public setPrintHandler(handler: PrintHandlerType): void {\n    this._printHandler = handler;\n  }\n  public clearPrintHandler(): void {\n    this._printHandler = this._printHandlerFb;\n  }\n\n  public addEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {\n    const ident = this._identifier(id, [0x30, 0x7e]);\n    if (this._escHandlers[ident] === undefined) {\n      this._escHandlers[ident] = [];\n    }\n    const handlerList = this._escHandlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n  public setEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): void {\n    this._escHandlers[this._identifier(id, [0x30, 0x7e])] = [handler];\n  }\n  public clearEscHandler(id: IFunctionIdentifier): void {\n    if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];\n  }\n  public setEscHandlerFallback(handler: EscFallbackHandlerType): void {\n    this._escHandlerFb = handler;\n  }\n\n  public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {\n    this._executeHandlers[flag.charCodeAt(0)] = handler;\n  }\n  public clearExecuteHandler(flag: string): void {\n    if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];\n  }\n  public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {\n    this._executeHandlerFb = handler;\n  }\n\n  public addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {\n    const ident = this._identifier(id);\n    if (this._csiHandlers[ident] === undefined) {\n      this._csiHandlers[ident] = [];\n    }\n    const handlerList = this._csiHandlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n  public setCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): void {\n    this._csiHandlers[this._identifier(id)] = [handler];\n  }\n  public clearCsiHandler(id: IFunctionIdentifier): void {\n    if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];\n  }\n  public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void {\n    this._csiHandlerFb = callback;\n  }\n\n  public addDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {\n    return this._dcsParser.addHandler(this._identifier(id), handler);\n  }\n  public setDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): void {\n    this._dcsParser.setHandler(this._identifier(id), handler);\n  }\n  public clearDcsHandler(id: IFunctionIdentifier): void {\n    this._dcsParser.clearHandler(this._identifier(id));\n  }\n  public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {\n    this._dcsParser.setHandlerFallback(handler);\n  }\n\n  public addOscHandler(ident: number, handler: IOscHandler): IDisposable {\n    return this._oscParser.addHandler(ident, handler);\n  }\n  public setOscHandler(ident: number, handler: IOscHandler): void {\n    this._oscParser.setHandler(ident, handler);\n  }\n  public clearOscHandler(ident: number): void {\n    this._oscParser.clearHandler(ident);\n  }\n  public setOscHandlerFallback(handler: OscFallbackHandlerType): void {\n    this._oscParser.setHandlerFallback(handler);\n  }\n\n  public setErrorHandler(callback: (state: IParsingState) => IParsingState): void {\n    this._errorHandler = callback;\n  }\n  public clearErrorHandler(): void {\n    this._errorHandler = this._errorHandlerFb;\n  }\n\n  public reset(): void {\n    this.currentState = this.initialState;\n    this._oscParser.reset();\n    this._dcsParser.reset();\n    this._params.reset();\n    this._params.addParam(0); // ZDM\n    this._collect = 0;\n    this.precedingCodepoint = 0;\n  }\n\n\n\n  /**\n   * Parse UTF32 codepoints in `data` up to `length`.\n   *\n   * Note: For several actions with high data load the parsing is optimized\n   * by using local read ahead loops with hardcoded conditions to\n   * avoid costly table lookups. Make sure that any change of table values\n   * will be reflected in the loop conditions as well and vice versa.\n   * Affected states/actions:\n   * - GROUND:PRINT\n   * - CSI_PARAM:PARAM\n   * - DCS_PARAM:PARAM\n   * - OSC_STRING:OSC_PUT\n   * - DCS_PASSTHROUGH:DCS_PUT\n   */\n  public parse(data: Uint32Array, length: number): void {\n    let code = 0;\n    let transition = 0;\n    let currentState = this.currentState;\n    const osc = this._oscParser;\n    const dcs = this._dcsParser;\n    let collect = this._collect;\n    const params = this._params;\n    const table: Uint8Array = this.TRANSITIONS.table;\n\n    // process input string\n    for (let i = 0; i < length; ++i) {\n      code = data[i];\n\n      // normal transition & action lookup\n      transition = table[currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];\n      switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) {\n        case ParserAction.PRINT:\n          // read ahead with loop unrolling\n          // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded\n          for (let j = i + 1; ; ++j) {\n            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n          }\n          break;\n        case ParserAction.EXECUTE:\n          if (this._executeHandlers[code]) this._executeHandlers[code]();\n          else this._executeHandlerFb(code);\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.IGNORE:\n          break;\n        case ParserAction.ERROR:\n          const inject: IParsingState = this._errorHandler(\n            {\n              position: i,\n              code,\n              currentState,\n              collect,\n              params,\n              abort: false\n            });\n          if (inject.abort) return;\n          // inject values: currently not implemented\n          break;\n        case ParserAction.CSI_DISPATCH:\n          // Trigger CSI Handler\n          const handlers = this._csiHandlers[collect << 8 | code];\n          let j = handlers ? handlers.length - 1 : -1;\n          for (; j >= 0; j--) {\n            // undefined or true means success and to stop bubbling\n            if (handlers[j](params) !== false) {\n              break;\n            }\n          }\n          if (j < 0) {\n            this._csiHandlerFb(collect << 8 | code, params);\n          }\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.PARAM:\n          // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a)\n          do {\n            switch (code) {\n              case 0x3b:\n                params.addParam(0);  // ZDM\n                break;\n              case 0x3a:\n                params.addSubParam(-1);\n                break;\n              default:  // 0x30 - 0x39\n                params.addDigit(code - 48);\n            }\n          } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);\n          i--;\n          break;\n        case ParserAction.COLLECT:\n          collect <<= 8;\n          collect |= code;\n          break;\n        case ParserAction.ESC_DISPATCH:\n          const handlersEsc = this._escHandlers[collect << 8 | code];\n          let jj = handlersEsc ? handlersEsc.length - 1 : -1;\n          for (; jj >= 0; jj--) {\n            // undefined or true means success and to stop bubbling\n            if (handlersEsc[jj]() !== false) {\n              break;\n            }\n          }\n          if (jj < 0) {\n            this._escHandlerFb(collect << 8 | code);\n          }\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.CLEAR:\n          params.reset();\n          params.addParam(0); // ZDM\n          collect = 0;\n          break;\n        case ParserAction.DCS_HOOK:\n          dcs.hook(collect << 8 | code, params);\n          break;\n        case ParserAction.DCS_PUT:\n          // inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f\n          // unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort)\n          for (let j = i + 1; ; ++j) {\n            if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {\n              dcs.put(data, i, j);\n              i = j - 1;\n              break;\n            }\n          }\n          break;\n        case ParserAction.DCS_UNHOOK:\n          dcs.unhook(code !== 0x18 && code !== 0x1a);\n          if (code === 0x1b) transition |= ParserState.ESCAPE;\n          params.reset();\n          params.addParam(0); // ZDM\n          collect = 0;\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.OSC_START:\n          osc.start();\n          break;\n        case ParserAction.OSC_PUT:\n          // inner loop: 0x20 (SP) included, 0x7F (DEL) included\n          for (let j = i + 1; ; j++) {\n            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code <= 0x9f)) {\n              osc.put(data, i, j);\n              i = j - 1;\n              break;\n            }\n          }\n          break;\n        case ParserAction.OSC_END:\n          osc.end(code !== 0x18 && code !== 0x1a);\n          if (code === 0x1b) transition |= ParserState.ESCAPE;\n          params.reset();\n          params.addParam(0); // ZDM\n          collect = 0;\n          this.precedingCodepoint = 0;\n          break;\n      }\n      currentState = transition & TableAccess.TRANSITION_STATE_MASK;\n    }\n\n    // save collected intermediates\n    this._collect = collect;\n\n    // save state\n    this.currentState = currentState;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { TextRenderLayer } from '../browser/renderer/TextRenderLayer';\nimport { SelectionRenderLayer } from '../browser/renderer/SelectionRenderLayer';\nimport { CursorRenderLayer } from './CursorRenderLayer';\nimport { IRenderLayer, IRenderer, IRenderDimensions, CharacterJoinerHandler, ICharacterJoinerRegistry } from 'browser/renderer/Types';\nimport { ITerminal } from '../Types';\nimport { LinkRenderLayer } from '../browser/renderer/LinkRenderLayer';\nimport { CharacterJoinerRegistry } from 'browser/renderer/CharacterJoinerRegistry';\nimport { Disposable } from 'common/Lifecycle';\nimport { IColorSet } from 'browser/Types';\nimport { ICharSizeService } from 'browser/services/Services';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { removeTerminalFromCache } from 'browser/renderer/atlas/CharAtlasCache';\n\nlet nextRendererId = 1;\n\nexport class Renderer extends Disposable implements IRenderer {\n  private _id = nextRendererId++;\n\n  private _renderLayers: IRenderLayer[];\n  private _devicePixelRatio: number;\n  private _characterJoinerRegistry: ICharacterJoinerRegistry;\n\n  public dimensions: IRenderDimensions;\n\n  constructor(\n    private _colors: IColorSet,\n    private readonly _terminal: ITerminal,\n    readonly bufferService: IBufferService,\n    private readonly _charSizeService: ICharSizeService,\n    readonly optionsService: IOptionsService\n  ) {\n    super();\n    const allowTransparency = this._terminal.options.allowTransparency;\n    this._characterJoinerRegistry = new CharacterJoinerRegistry(bufferService);\n\n    this._renderLayers = [\n      new TextRenderLayer(this._terminal.screenElement, 0, this._colors, this._characterJoinerRegistry, allowTransparency, this._id, bufferService, optionsService),\n      new SelectionRenderLayer(this._terminal.screenElement, 1, this._colors, this._id, bufferService, optionsService),\n      new LinkRenderLayer(this._terminal.screenElement, 2, this._colors, this._id, this._terminal.linkifier, bufferService, optionsService),\n      new CursorRenderLayer(this._terminal.screenElement, 3, this._colors, this._terminal, this._id, bufferService, optionsService)\n    ];\n    this.dimensions = {\n      scaledCharWidth: null,\n      scaledCharHeight: null,\n      scaledCellWidth: null,\n      scaledCellHeight: null,\n      scaledCharLeft: null,\n      scaledCharTop: null,\n      scaledCanvasWidth: null,\n      scaledCanvasHeight: null,\n      canvasWidth: null,\n      canvasHeight: null,\n      actualCellWidth: null,\n      actualCellHeight: null\n    };\n    this._devicePixelRatio = window.devicePixelRatio;\n    this._updateDimensions();\n    this.onOptionsChanged();\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this._renderLayers.forEach(l => l.dispose());\n    removeTerminalFromCache(this._id);\n  }\n\n  public onDevicePixelRatioChange(): void {\n    // If the device pixel ratio changed, the char atlas needs to be regenerated\n    // and the terminal needs to refreshed\n    if (this._devicePixelRatio !== window.devicePixelRatio) {\n      this._devicePixelRatio = window.devicePixelRatio;\n      this.onResize(this._terminal.cols, this._terminal.rows);\n    }\n  }\n\n  public setColors(colors: IColorSet): void {\n    this._colors = colors;\n\n    // Clear layers and force a full render\n    this._renderLayers.forEach(l => {\n      l.setColors(this._colors);\n      l.reset();\n    });\n  }\n\n  public onResize(cols: number, rows: number): void {\n    // Update character and canvas dimensions\n    this._updateDimensions();\n\n    // Resize all render layers\n    this._renderLayers.forEach(l => l.resize(this.dimensions));\n\n    // Resize the screen\n    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;\n    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;\n  }\n\n  public onCharSizeChanged(): void {\n    this.onResize(this._terminal.cols, this._terminal.rows);\n  }\n\n  public onBlur(): void {\n    this._runOperation(l => l.onBlur());\n  }\n\n  public onFocus(): void {\n    this._runOperation(l => l.onFocus());\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {\n    this._runOperation(l => l.onSelectionChanged(start, end, columnSelectMode));\n  }\n\n  public onCursorMove(): void {\n    this._runOperation(l => l.onCursorMove());\n  }\n\n  public onOptionsChanged(): void {\n    this._runOperation(l => l.onOptionsChanged());\n  }\n\n  public clear(): void {\n    this._runOperation(l => l.reset());\n  }\n\n  private _runOperation(operation: (layer: IRenderLayer) => void): void {\n    this._renderLayers.forEach(l => operation(l));\n  }\n\n  /**\n   * Performs the refresh loop callback, calling refresh only if a refresh is\n   * necessary before queueing up the next one.\n   */\n  public renderRows(start: number, end: number): void {\n    this._renderLayers.forEach(l => l.onGridChanged(start, end));\n  }\n\n  /**\n   * Recalculates the character and canvas dimensions.\n   */\n  private _updateDimensions(): void {\n    if (!this._charSizeService.hasValidSize) {\n      return;\n    }\n\n    // Calculate the scaled character width. Width is floored as it must be\n    // drawn to an integer grid in order for the CharAtlas \"stamps\" to not be\n    // blurry. When text is drawn to the grid not using the CharAtlas, it is\n    // clipped to ensure there is no overlap with the next cell.\n    this.dimensions.scaledCharWidth = Math.floor(this._charSizeService.width * window.devicePixelRatio);\n\n    // Calculate the scaled character height. Height is ceiled in case\n    // devicePixelRatio is a floating point number in order to ensure there is\n    // enough space to draw the character to the cell.\n    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);\n\n    // Calculate the scaled cell height, if lineHeight is not 1 then the value\n    // will be floored because since lineHeight can never be lower then 1, there\n    // is a guarentee that the scaled line height will always be larger than\n    // scaled char height.\n    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);\n\n    // Calculate the y coordinate within a cell that text should draw from in\n    // order to draw in the center of a cell.\n    this.dimensions.scaledCharTop = this._terminal.options.lineHeight === 1 ? 0 : Math.round((this.dimensions.scaledCellHeight - this.dimensions.scaledCharHeight) / 2);\n\n    // Calculate the scaled cell width, taking the letterSpacing into account.\n    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);\n\n    // Calculate the x coordinate with a cell that text should draw from in\n    // order to draw in the center of a cell.\n    this.dimensions.scaledCharLeft = Math.floor(this._terminal.options.letterSpacing / 2);\n\n    // Recalculate the canvas dimensions; scaled* define the actual number of\n    // pixel in the canvas\n    this.dimensions.scaledCanvasHeight = this._terminal.rows * this.dimensions.scaledCellHeight;\n    this.dimensions.scaledCanvasWidth = this._terminal.cols * this.dimensions.scaledCellWidth;\n\n    // The the size of the canvas on the page. It's very important that this\n    // rounds to nearest integer and not ceils as browsers often set\n    // window.devicePixelRatio as something like 1.100000023841858, when it's\n    // actually 1.1. Ceiling causes blurriness as the backing canvas image is 1\n    // pixel too large for the canvas element size.\n    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);\n    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);\n\n    // Get the _actual_ dimensions of an individual cell. This needs to be\n    // derived from the canvasWidth/Height calculated above which takes into\n    // account window.devicePixelRatio. ICharSizeService.width/height by itself\n    // is insufficient when the page is not at 100% zoom level as it's measured\n    // in CSS pixels, but the actual char size on the canvas can differ.\n    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;\n    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n    return this._characterJoinerRegistry.registerCharacterJoiner(handler);\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): boolean {\n    return this._characterJoinerRegistry.deregisterCharacterJoiner(joinerId);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharacterJoinerRegistry, IRenderDimensions } from 'browser/renderer/Types';\nimport { CharData, ICellData } from 'common/Types';\nimport { GridCache } from 'browser/renderer/GridCache';\nimport { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { NULL_CELL_CODE, Content } from 'common/buffer/Constants';\nimport { JoinedCellData } from 'browser/renderer/CharacterJoinerRegistry';\nimport { IColorSet } from 'browser/Types';\nimport { CellData } from 'common/buffer/CellData';\nimport { IOptionsService, IBufferService } from 'common/services/Services';\n\n/**\n * This CharData looks like a null character, which will forc a clear and render\n * when the character changes (a regular space ' ' character may not as it's\n * drawn state is a cleared cell).\n */\n// const OVERLAP_OWNED_CHAR_DATA: CharData = [null, '', 0, -1];\n\nexport class TextRenderLayer extends BaseRenderLayer {\n  private _state: GridCache<CharData>;\n  private _characterWidth: number = 0;\n  private _characterFont: string = '';\n  private _characterOverlapCache: { [key: string]: boolean } = {};\n  private _characterJoinerRegistry: ICharacterJoinerRegistry;\n  private _workCell = new CellData();\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    characterJoinerRegistry: ICharacterJoinerRegistry,\n    alpha: boolean,\n    rendererId: number,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'text', zIndex, alpha, colors, rendererId, bufferService, optionsService);\n    this._state = new GridCache<CharData>();\n    this._characterJoinerRegistry = characterJoinerRegistry;\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n\n    // Clear the character width cache if the font or width has changed\n    const terminalFont = this._getFont(false, false);\n    if (this._characterWidth !== dim.scaledCharWidth || this._characterFont !== terminalFont) {\n      this._characterWidth = dim.scaledCharWidth;\n      this._characterFont = terminalFont;\n      this._characterOverlapCache = {};\n    }\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._state.clear();\n    this._state.resize(this._bufferService.cols, this._bufferService.rows);\n  }\n\n  public reset(): void {\n    this._state.clear();\n    this._clearAll();\n  }\n\n  private _forEachCell(\n    firstRow: number,\n    lastRow: number,\n    joinerRegistry: ICharacterJoinerRegistry | null,\n    callback: (\n      cell: ICellData,\n      x: number,\n      y: number\n    ) => void\n  ): void {\n    for (let y = firstRow; y <= lastRow; y++) {\n      const row = y + this._bufferService.buffer.ydisp;\n      const line = this._bufferService.buffer.lines.get(row);\n      const joinedRanges = joinerRegistry ? joinerRegistry.getJoinedCharacters(row) : [];\n      for (let x = 0; x < this._bufferService.cols; x++) {\n        line!.loadCell(x, this._workCell);\n        let cell = this._workCell;\n\n        // If true, indicates that the current character(s) to draw were joined.\n        let isJoined = false;\n        let lastCharX = x;\n\n        // The character to the left is a wide character, drawing is owned by\n        // the char at x-1\n        if (cell.getWidth() === 0) {\n          continue;\n        }\n\n        // Process any joined character ranges as needed. Because of how the\n        // ranges are produced, we know that they are valid for the characters\n        // and attributes of our input.\n        if (joinedRanges.length > 0 && x === joinedRanges[0][0]) {\n          isJoined = true;\n          const range = joinedRanges.shift()!;\n\n          // We already know the exact start and end column of the joined range,\n          // so we get the string and width representing it directly\n\n          cell = new JoinedCellData(\n            this._workCell,\n            line!.translateToString(true, range[0], range[1]),\n            range[1] - range[0]\n          );\n\n          // Skip over the cells occupied by this range in the loop\n          lastCharX = range[1] - 1;\n        }\n\n        // If the character is an overlapping char and the character to the\n        // right is a space, take ownership of the cell to the right. We skip\n        // this check for joined characters because their rendering likely won't\n        // yield the same result as rendering the last character individually.\n        if (!isJoined && this._isOverlapping(cell)) {\n          // If the character is overlapping, we want to force a re-render on every\n          // frame. This is specifically to work around the case where two\n          // overlaping chars `a` and `b` are adjacent, the cursor is moved to b and a\n          // space is added. Without this, the first half of `b` would never\n          // get removed, and `a` would not re-render because it thinks it's\n          // already in the correct state.\n          // this._state.cache[x][y] = OVERLAP_OWNED_CHAR_DATA;\n          if (lastCharX < line!.length - 1 && line!.getCodePoint(lastCharX + 1) === NULL_CELL_CODE) {\n            // patch width to 2\n            cell.content &= ~Content.WIDTH_MASK;\n            cell.content |= 2 << Content.WIDTH_SHIFT;\n            // this._clearChar(x + 1, y);\n            // The overlapping char's char data will force a clear and render when the\n            // overlapping char is no longer to the left of the character and also when\n            // the space changes to another character.\n            // this._state.cache[x + 1][y] = OVERLAP_OWNED_CHAR_DATA;\n          }\n        }\n\n        callback(\n          cell,\n          x,\n          y\n        );\n\n        x = lastCharX;\n      }\n    }\n  }\n\n  /**\n   * Draws the background for a specified range of columns. Tries to batch adjacent cells of the\n   * same color together to reduce draw calls.\n   */\n  private _drawBackground(firstRow: number, lastRow: number): void {\n    const ctx = this._ctx;\n    const cols = this._bufferService.cols;\n    let startX: number = 0;\n    let startY: number = 0;\n    let prevFillStyle: string | null = null;\n\n    ctx.save();\n\n    this._forEachCell(firstRow, lastRow, null, (cell, x, y) => {\n      // libvte and xterm both draw the background (but not foreground) of invisible characters,\n      // so we should too.\n      let nextFillStyle = null; // null represents default background color\n\n      if (cell.isInverse()) {\n        if (cell.isFgDefault()) {\n          nextFillStyle = this._colors.foreground.css;\n        } else if (cell.isFgRGB()) {\n          nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;\n        } else {\n          nextFillStyle = this._colors.ansi[cell.getFgColor()].css;\n        }\n      } else if (cell.isBgRGB()) {\n        nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;\n      } else if (cell.isBgPalette()) {\n        nextFillStyle = this._colors.ansi[cell.getBgColor()].css;\n      }\n\n      if (prevFillStyle === null) {\n        // This is either the first iteration, or the default background was set. Either way, we\n        // don't need to draw anything.\n        startX = x;\n        startY = y;\n      }\n\n      if (y !== startY) {\n        // our row changed, draw the previous row\n        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';\n        this._fillCells(startX, startY, cols - startX, 1);\n        startX = x;\n        startY = y;\n      } else if (prevFillStyle !== nextFillStyle) {\n        // our color changed, draw the previous characters in this row\n        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';\n        this._fillCells(startX, startY, x - startX, 1);\n        startX = x;\n        startY = y;\n      }\n\n      prevFillStyle = nextFillStyle;\n    });\n\n    // flush the last color we encountered\n    if (prevFillStyle !== null) {\n      ctx.fillStyle = prevFillStyle;\n      this._fillCells(startX, startY, cols - startX, 1);\n    }\n\n    ctx.restore();\n  }\n\n  private _drawForeground(firstRow: number, lastRow: number): void {\n    this._forEachCell(firstRow, lastRow, this._characterJoinerRegistry, (cell, x, y) => {\n      if (cell.isInvisible()) {\n        return;\n      }\n      this._drawChars(cell, x, y);\n      if (cell.isUnderline()) {\n        this._ctx.save();\n\n        if (cell.isInverse()) {\n          if (cell.isBgDefault()) {\n            this._ctx.fillStyle = this._colors.background.css;\n          } else if (cell.isBgRGB()) {\n            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;\n          } else {\n            this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;\n          }\n        } else {\n          if (cell.isFgDefault()) {\n            this._ctx.fillStyle = this._colors.foreground.css;\n          } else if (cell.isFgRGB()) {\n            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;\n          } else {\n            let fg = cell.getFgColor();\n            if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {\n              fg += 8;\n            }\n            this._ctx.fillStyle = this._colors.ansi[fg].css;\n          }\n        }\n\n        this._fillBottomLineAtCells(x, y, cell.getWidth());\n        this._ctx.restore();\n      }\n    });\n  }\n\n  public onGridChanged(firstRow: number, lastRow: number): void {\n    // Resize has not been called yet\n    if (this._state.cache.length === 0) {\n      return;\n    }\n\n    if (this._charAtlas) {\n      this._charAtlas.beginFrame();\n    }\n\n    this._clearCells(0, firstRow, this._bufferService.cols, lastRow - firstRow + 1);\n    this._drawBackground(firstRow, lastRow);\n    this._drawForeground(firstRow, lastRow);\n  }\n\n  public onOptionsChanged(): void {\n    this._setTransparency(this._optionsService.options.allowTransparency);\n  }\n\n  /**\n   * Whether a character is overlapping to the next cell.\n   */\n  private _isOverlapping(cell: ICellData): boolean {\n    // Only single cell characters can be overlapping, rendering issues can\n    // occur without this check\n    if (cell.getWidth() !== 1) {\n      return false;\n    }\n\n    // We assume that any ascii character will not overlap\n    if (cell.getCode() < 256) {\n      return false;\n    }\n\n    const chars = cell.getChars();\n\n    // Deliver from cache if available\n    if (this._characterOverlapCache.hasOwnProperty(chars)) {\n      return this._characterOverlapCache[chars];\n    }\n\n    // Setup the font\n    this._ctx.save();\n    this._ctx.font = this._characterFont;\n\n    // Measure the width of the character, but Math.floor it\n    // because that is what the renderer does when it calculates\n    // the character dimensions we are comparing against\n    const overlaps = Math.floor(this._ctx.measureText(chars).width) > this._characterWidth;\n\n    // Restore the original context\n    this._ctx.restore();\n\n    // Cache and return\n    this._characterOverlapCache[chars] = overlaps;\n    return overlaps;\n  }\n\n  /**\n   * Clear the charcater at the cell specified.\n   * @param x The column of the char.\n   * @param y The row of the char.\n   */\n  // private _clearChar(x: number, y: number): void {\n  //   let colsToClear = 1;\n  //   // Clear the adjacent character if it was wide\n  //   const state = this._state.cache[x][y];\n  //   if (state && state[CHAR_DATA_WIDTH_INDEX] === 2) {\n  //     colsToClear = 2;\n  //   }\n  //   this.clearCells(x, y, colsToClear, 1);\n  // }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport class GridCache<T> {\n  public cache: (T | undefined)[][];\n\n  public constructor() {\n    this.cache = [];\n  }\n\n  public resize(width: number, height: number): void {\n    for (let x = 0; x < width; x++) {\n      if (this.cache.length <= x) {\n        this.cache.push([]);\n      }\n      for (let y = this.cache[x].length; y < height; y++) {\n        this.cache[x].push(undefined);\n      }\n      this.cache[x].length = height;\n    }\n    this.cache.length = width;\n  }\n\n  public clear(): void {\n    for (let x = 0; x < this.cache.length; x++) {\n      for (let y = 0; y < this.cache[x].length; y++) {\n        this.cache[x][y] = undefined;\n      }\n    }\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { IGlyphIdentifier, ICharAtlasConfig } from 'browser/renderer/atlas/Types';\nimport { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';\nimport { DEFAULT_ANSI_COLORS } from 'browser/ColorManager';\nimport { LRUMap } from 'browser/renderer/atlas/LRUMap';\nimport { isFirefox, isSafari } from 'common/Platform';\nimport { IColor } from 'browser/Types';\nimport { throwIfFalsy } from 'browser/renderer/RendererUtils';\n\n// In practice we're probably never going to exhaust a texture this large. For debugging purposes,\n// however, it can be useful to set this to a really tiny value, to verify that LRU eviction works.\nconst TEXTURE_WIDTH = 1024;\nconst TEXTURE_HEIGHT = 1024;\n\nconst TRANSPARENT_COLOR = {\n  css: 'rgba(0, 0, 0, 0)',\n  rgba: 0\n};\n\n// Drawing to the cache is expensive: If we have to draw more than this number of glyphs to the\n// cache in a single frame, give up on trying to cache anything else, and try to finish the current\n// frame ASAP.\n//\n// This helps to limit the amount of damage a program can do when it would otherwise thrash the\n// cache.\nconst FRAME_CACHE_DRAW_LIMIT = 100;\n\n/**\n * The number of milliseconds to wait before generating the ImageBitmap, this is to debounce/batch\n * the operation as window.createImageBitmap is asynchronous.\n */\nconst GLYPH_BITMAP_COMMIT_DELAY = 100;\n\ninterface IGlyphCacheValue {\n  index: number;\n  isEmpty: boolean;\n  inBitmap: boolean;\n}\n\nexport function getGlyphCacheKey(glyph: IGlyphIdentifier): number {\n  // Note that this only returns a valid key when code < 256\n  // Layout:\n  // 0b00000000000000000000000000000001: italic (1)\n  // 0b00000000000000000000000000000010: dim (1)\n  // 0b00000000000000000000000000000100: bold (1)\n  // 0b00000000000000000000111111111000: fg (9)\n  // 0b00000000000111111111000000000000: bg (9)\n  // 0b00011111111000000000000000000000: code (8)\n  // 0b11100000000000000000000000000000: unused (3)\n  return glyph.code << 21 | glyph.bg << 12 | glyph.fg << 3 | (glyph.bold ? 0 : 4) + (glyph.dim ? 0 : 2) + (glyph.italic ? 0 : 1);\n}\n\nexport class DynamicCharAtlas extends BaseCharAtlas {\n  // An ordered map that we're using to keep track of where each glyph is in the atlas texture.\n  // It's ordered so that we can determine when to remove the old entries.\n  private _cacheMap: LRUMap<IGlyphCacheValue>;\n\n  // The texture that the atlas is drawn to\n  private _cacheCanvas: HTMLCanvasElement;\n  private _cacheCtx: CanvasRenderingContext2D;\n\n  // A temporary context that glyphs are drawn to before being transfered to the atlas.\n  private _tmpCtx: CanvasRenderingContext2D;\n\n  // The number of characters stored in the atlas by width/height\n  private _width: number;\n  private _height: number;\n\n  private _drawToCacheCount: number = 0;\n\n  // An array of glyph keys that are waiting on the bitmap to be generated.\n  private _glyphsWaitingOnBitmap: IGlyphCacheValue[] = [];\n\n  // The timeout that is used to batch bitmap generation so it's not requested for every new glyph.\n  private _bitmapCommitTimeout: number | null = null;\n\n  // The bitmap to draw from, this is much faster on other browsers than others.\n  private _bitmap: ImageBitmap | null = null;\n\n  constructor(document: Document, private _config: ICharAtlasConfig) {\n    super();\n    this._cacheCanvas = document.createElement('canvas');\n    this._cacheCanvas.width = TEXTURE_WIDTH;\n    this._cacheCanvas.height = TEXTURE_HEIGHT;\n    // The canvas needs alpha because we use clearColor to convert the background color to alpha.\n    // It might also contain some characters with transparent backgrounds if allowTransparency is\n    // set.\n    this._cacheCtx = throwIfFalsy(this._cacheCanvas.getContext('2d', {alpha: true}));\n\n    const tmpCanvas = document.createElement('canvas');\n    tmpCanvas.width = this._config.scaledCharWidth;\n    tmpCanvas.height = this._config.scaledCharHeight;\n    this._tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d', {alpha: this._config.allowTransparency}));\n\n    this._width = Math.floor(TEXTURE_WIDTH / this._config.scaledCharWidth);\n    this._height = Math.floor(TEXTURE_HEIGHT / this._config.scaledCharHeight);\n    const capacity = this._width * this._height;\n    this._cacheMap = new LRUMap(capacity);\n    this._cacheMap.prealloc(capacity);\n\n    // This is useful for debugging\n    // document.body.appendChild(this._cacheCanvas);\n  }\n\n  public dispose(): void {\n    if (this._bitmapCommitTimeout !== null) {\n      window.clearTimeout(this._bitmapCommitTimeout);\n      this._bitmapCommitTimeout = null;\n    }\n  }\n\n  public beginFrame(): void {\n    this._drawToCacheCount = 0;\n  }\n\n  public draw(\n    ctx: CanvasRenderingContext2D,\n    glyph: IGlyphIdentifier,\n    x: number,\n    y: number\n  ): boolean {\n    // Space is always an empty cell, special case this as it's so common\n    if (glyph.code === 32) {\n      return true;\n    }\n\n    // Exit early for uncachable glyphs\n    if (!this._canCache(glyph)) {\n      return false;\n    }\n\n    const glyphKey = getGlyphCacheKey(glyph);\n    const cacheValue = this._cacheMap.get(glyphKey);\n    if (cacheValue !== null && cacheValue !== undefined) {\n      this._drawFromCache(ctx, cacheValue, x, y);\n      return true;\n    } else if (this._drawToCacheCount < FRAME_CACHE_DRAW_LIMIT) {\n      let index;\n      if (this._cacheMap.size < this._cacheMap.capacity) {\n        index = this._cacheMap.size;\n      } else {\n        // we're out of space, so our call to set will delete this item\n        index = this._cacheMap.peek()!.index;\n      }\n      const cacheValue = this._drawToCache(glyph, index);\n      this._cacheMap.set(glyphKey, cacheValue);\n      this._drawFromCache(ctx, cacheValue, x, y);\n      return true;\n    }\n    return false;\n  }\n\n  private _canCache(glyph: IGlyphIdentifier): boolean {\n    // Only cache ascii and extended characters for now, to be safe. In the future, we could do\n    // something more complicated to determine the expected width of a character.\n    //\n    // If we switch the renderer over to webgl at some point, we may be able to use blending modes\n    // to draw overlapping glyphs from the atlas:\n    // https://github.com/servo/webrender/issues/464#issuecomment-255632875\n    // https://webglfundamentals.org/webgl/lessons/webgl-text-texture.html\n    return glyph.code < 256;\n  }\n\n  private _toCoordinateX(index: number): number {\n    return (index % this._width) * this._config.scaledCharWidth;\n  }\n\n  private _toCoordinateY(index: number): number {\n    return Math.floor(index / this._width) * this._config.scaledCharHeight;\n  }\n\n  private _drawFromCache(\n    ctx: CanvasRenderingContext2D,\n    cacheValue: IGlyphCacheValue,\n    x: number,\n    y: number\n  ): void {\n    // We don't actually need to do anything if this is whitespace.\n    if (cacheValue.isEmpty) {\n      return;\n    }\n    const cacheX = this._toCoordinateX(cacheValue.index);\n    const cacheY = this._toCoordinateY(cacheValue.index);\n    ctx.drawImage(\n      cacheValue.inBitmap ? this._bitmap! : this._cacheCanvas,\n      cacheX,\n      cacheY,\n      this._config.scaledCharWidth,\n      this._config.scaledCharHeight,\n      x,\n      y,\n      this._config.scaledCharWidth,\n      this._config.scaledCharHeight\n    );\n  }\n\n  private _getColorFromAnsiIndex(idx: number): IColor {\n    if (idx < this._config.colors.ansi.length) {\n      return this._config.colors.ansi[idx];\n    }\n    return DEFAULT_ANSI_COLORS[idx];\n  }\n\n  private _getBackgroundColor(glyph: IGlyphIdentifier): IColor {\n    if (this._config.allowTransparency) {\n      // The background color might have some transparency, so we need to render it as fully\n      // transparent in the atlas. Otherwise we'd end up drawing the transparent background twice\n      // around the anti-aliased edges of the glyph, and it would look too dark.\n      return TRANSPARENT_COLOR;\n    } else if (glyph.bg === INVERTED_DEFAULT_COLOR) {\n      return this._config.colors.foreground;\n    } else if (glyph.bg < 256) {\n      return this._getColorFromAnsiIndex(glyph.bg);\n    }\n    return this._config.colors.background;\n  }\n\n  private _getForegroundColor(glyph: IGlyphIdentifier): IColor {\n    if (glyph.fg === INVERTED_DEFAULT_COLOR) {\n      return this._config.colors.background;\n    } else if (glyph.fg < 256) {\n      // 256 color support\n      return this._getColorFromAnsiIndex(glyph.fg);\n    }\n    return this._config.colors.foreground;\n  }\n\n  // TODO: We do this (or something similar) in multiple places. We should split this off\n  // into a shared function.\n  private _drawToCache(glyph: IGlyphIdentifier, index: number): IGlyphCacheValue {\n    this._drawToCacheCount++;\n\n    this._tmpCtx.save();\n\n    // draw the background\n    const backgroundColor = this._getBackgroundColor(glyph);\n    // Use a 'copy' composite operation to clear any existing glyph out of _tmpCtxWithAlpha, regardless of\n    // transparency in backgroundColor\n    this._tmpCtx.globalCompositeOperation = 'copy';\n    this._tmpCtx.fillStyle = backgroundColor.css;\n    this._tmpCtx.fillRect(0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight);\n    this._tmpCtx.globalCompositeOperation = 'source-over';\n\n    // draw the foreground/glyph\n    const fontWeight = glyph.bold ? this._config.fontWeightBold : this._config.fontWeight;\n    const fontStyle = glyph.italic ? 'italic' : '';\n    this._tmpCtx.font =\n      `${fontStyle} ${fontWeight} ${this._config.fontSize * this._config.devicePixelRatio}px ${this._config.fontFamily}`;\n    this._tmpCtx.textBaseline = 'middle';\n\n    this._tmpCtx.fillStyle = this._getForegroundColor(glyph).css;\n\n    // Apply alpha to dim the character\n    if (glyph.dim) {\n      this._tmpCtx.globalAlpha = DIM_OPACITY;\n    }\n    // Draw the character\n    this._tmpCtx.fillText(glyph.chars, 0, this._config.scaledCharHeight / 2);\n    this._tmpCtx.restore();\n\n    // clear the background from the character to avoid issues with drawing over the previous\n    // character if it extends past it's bounds\n    const imageData = this._tmpCtx.getImageData(\n      0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight\n    );\n    let isEmpty = false;\n    if (!this._config.allowTransparency) {\n      isEmpty = clearColor(imageData, backgroundColor);\n    }\n\n    // copy the data from imageData to _cacheCanvas\n    const x = this._toCoordinateX(index);\n    const y = this._toCoordinateY(index);\n    // putImageData doesn't do any blending, so it will overwrite any existing cache entry for us\n    this._cacheCtx.putImageData(imageData, x, y);\n\n    // Add the glyph and queue it to the bitmap (if the browser supports it)\n    const cacheValue = {\n      index,\n      isEmpty,\n      inBitmap: false\n    };\n    this._addGlyphToBitmap(cacheValue);\n\n    return cacheValue;\n  }\n\n  private _addGlyphToBitmap(cacheValue: IGlyphCacheValue): void {\n    // Support is patchy for createImageBitmap at the moment, pass a canvas back\n    // if support is lacking as drawImage works there too. Firefox is also\n    // included here as ImageBitmap appears both buggy and has horrible\n    // performance (tested on v55).\n    if (!('createImageBitmap' in window) || isFirefox || isSafari) {\n      return;\n    }\n\n    // Add the glyph to the queue\n    this._glyphsWaitingOnBitmap.push(cacheValue);\n\n    // Check if bitmap generation timeout already exists\n    if (this._bitmapCommitTimeout !== null) {\n      return;\n    }\n\n    this._bitmapCommitTimeout = window.setTimeout(() => this._generateBitmap(), GLYPH_BITMAP_COMMIT_DELAY);\n  }\n\n  private _generateBitmap(): void {\n    const glyphsMovingToBitmap = this._glyphsWaitingOnBitmap;\n    this._glyphsWaitingOnBitmap = [];\n    window.createImageBitmap(this._cacheCanvas).then(bitmap => {\n      // Set bitmap\n      this._bitmap = bitmap;\n\n      // Mark all new glyphs as in bitmap, excluding glyphs that came in after\n      // the bitmap was requested\n      for (let i = 0; i < glyphsMovingToBitmap.length; i++) {\n        const value = glyphsMovingToBitmap[i];\n        // It doesn't matter if the value was already evicted, it will be\n        // released from memory after this block if so.\n        value.inBitmap = true;\n      }\n    });\n    this._bitmapCommitTimeout = null;\n  }\n}\n\n// This is used for debugging the renderer, just swap out `new DynamicCharAtlas` with\n// `new NoneCharAtlas`.\nexport class NoneCharAtlas extends BaseCharAtlas {\n  constructor(document: Document, config: ICharAtlasConfig) {\n    super();\n  }\n\n  public draw(\n    ctx: CanvasRenderingContext2D,\n    glyph: IGlyphIdentifier,\n    x: number,\n    y: number\n  ): boolean {\n    return false;\n  }\n}\n\n/**\n * Makes a partiicular rgb color in an ImageData completely transparent.\n * @returns True if the result is \"empty\", meaning all pixels are fully transparent.\n */\nfunction clearColor(imageData: ImageData, color: IColor): boolean {\n  let isEmpty = true;\n  const r = color.rgba >>> 24;\n  const g = color.rgba >>> 16 & 0xFF;\n  const b = color.rgba >>> 8 & 0xFF;\n  for (let offset = 0; offset < imageData.data.length; offset += 4) {\n    if (imageData.data[offset] === r &&\n        imageData.data[offset + 1] === g &&\n        imageData.data[offset + 2] === b) {\n      imageData.data[offset + 3] = 0;\n    } else {\n      isEmpty = false;\n    }\n  }\n  return isEmpty;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IGlyphIdentifier } from 'browser/renderer/atlas/Types';\nimport { IDisposable } from 'common/Types';\n\nexport abstract class BaseCharAtlas implements IDisposable {\n  private _didWarmUp: boolean = false;\n\n  public dispose(): void { }\n\n  /**\n   * Perform any work needed to warm the cache before it can be used. May be called multiple times.\n   * Implement _doWarmUp instead if you only want to get called once.\n   */\n  public warmUp(): void {\n    if (!this._didWarmUp) {\n      this._doWarmUp();\n      this._didWarmUp = true;\n    }\n  }\n\n  /**\n   * Perform any work needed to warm the cache before it can be used. Used by the default\n   * implementation of warmUp(), and will only be called once.\n   */\n  protected _doWarmUp(): void { }\n\n  /**\n   * Called when we start drawing a new frame.\n   *\n   * TODO: We rely on this getting called by TextRenderLayer. This should really be called by\n   * Renderer instead, but we need to make Renderer the source-of-truth for the char atlas, instead\n   * of BaseRenderLayer.\n   */\n  public beginFrame(): void { }\n\n  /**\n   * May be called before warmUp finishes, however it is okay for the implementation to\n   * do nothing and return false in that case.\n   *\n   * @param ctx Where to draw the character onto.\n   * @param glyph Information about what to draw\n   * @param x The position on the context to start drawing at\n   * @param y The position on the context to start drawing at\n   * @returns The success state. True if we drew the character.\n   */\n  public abstract draw(\n    ctx: CanvasRenderingContext2D,\n    glyph: IGlyphIdentifier,\n    x: number,\n    y: number\n  ): boolean;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ninterface ILinkedListNode<T> {\n  prev: ILinkedListNode<T> | null;\n  next: ILinkedListNode<T> | null;\n  key: number | null;\n  value: T | null;\n}\n\nexport class LRUMap<T> {\n  private _map: { [key: number]: ILinkedListNode<T> } = {};\n  private _head: ILinkedListNode<T> | null = null;\n  private _tail: ILinkedListNode<T> | null = null;\n  private _nodePool: ILinkedListNode<T>[] = [];\n  public size: number = 0;\n\n  constructor(public capacity: number) { }\n\n  private _unlinkNode(node: ILinkedListNode<T>): void {\n    const prev = node.prev;\n    const next = node.next;\n    if (node === this._head) {\n      this._head = next;\n    }\n    if (node === this._tail) {\n      this._tail = prev;\n    }\n    if (prev !== null) {\n      prev.next = next;\n    }\n    if (next !== null) {\n      next.prev = prev;\n    }\n  }\n\n  private _appendNode(node: ILinkedListNode<T>): void {\n    const tail = this._tail;\n    if (tail !== null) {\n      tail.next = node;\n    }\n    node.prev = tail;\n    node.next = null;\n    this._tail = node;\n    if (this._head === null) {\n      this._head = node;\n    }\n  }\n\n  /**\n   * Preallocate a bunch of linked-list nodes. Allocating these nodes ahead of time means that\n   * they're more likely to live next to each other in memory, which seems to improve performance.\n   *\n   * Each empty object only consumes about 60 bytes of memory, so this is pretty cheap, even for\n   * large maps.\n   */\n  public prealloc(count: number): void {\n    const nodePool = this._nodePool;\n    for (let i = 0; i < count; i++) {\n      nodePool.push({\n        prev: null,\n        next: null,\n        key: null,\n        value: null\n      });\n    }\n  }\n\n  public get(key: number): T | null {\n    // This is unsafe: We're assuming our keyspace doesn't overlap with Object.prototype. However,\n    // it's faster than calling hasOwnProperty, and in our case, it would never overlap.\n    const node = this._map[key];\n    if (node !== undefined) {\n      this._unlinkNode(node);\n      this._appendNode(node);\n      return node.value;\n    }\n    return null;\n  }\n\n  /**\n   * Gets a value from a key without marking it as the most recently used item.\n   */\n  public peekValue(key: number): T | null {\n    const node = this._map[key];\n    if (node !== undefined) {\n      return node.value;\n    }\n    return null;\n  }\n\n  public peek(): T | null {\n    const head = this._head;\n    return head === null ? null : head.value;\n  }\n\n  public set(key: number, value: T): void {\n    // This is unsafe: See note above.\n    let node = this._map[key];\n    if (node !== undefined) {\n      // already exists, we just need to mutate it and move it to the end of the list\n      node = this._map[key];\n      this._unlinkNode(node);\n      node.value = value;\n    } else if (this.size >= this.capacity) {\n      // we're out of space: recycle the head node, move it to the tail\n      node = this._head!;\n      this._unlinkNode(node);\n      delete this._map[node.key!];\n      node.key = key;\n      node.value = value;\n      this._map[key] = node;\n    } else {\n      // make a new element\n      const nodePool = this._nodePool;\n      if (nodePool.length > 0) {\n        // use a preallocated node if we can\n        node = nodePool.pop()!;\n        node.key = key;\n        node.value = value;\n      } else {\n        node = {\n          prev: null,\n          next: null,\n          key,\n          value\n        };\n      }\n      this._map[key] = node;\n      this.size++;\n    }\n    this._appendNode(node);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions } from 'browser/renderer/Types';\nimport { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';\nimport { IColorSet } from 'browser/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\ninterface ISelectionState {\n  start?: [number, number];\n  end?: [number, number];\n  columnSelectMode?: boolean;\n  ydisp?: number;\n}\n\nexport class SelectionRenderLayer extends BaseRenderLayer {\n  private _state!: ISelectionState;\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    rendererId: number,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'selection', zIndex, true, colors, rendererId, bufferService, optionsService);\n    this._clearState();\n  }\n\n  private _clearState(): void {\n    this._state = {\n      start: undefined,\n      end: undefined,\n      columnSelectMode: undefined,\n      ydisp: undefined\n    };\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._clearState();\n  }\n\n  public reset(): void {\n    if (this._state.start && this._state.end) {\n      this._clearState();\n      this._clearAll();\n    }\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {\n    // Selection has not changed\n    if (!this._didStateChange(start, end, columnSelectMode, this._bufferService.buffer.ydisp)) {\n      return;\n    }\n\n    // Remove all selections\n    this._clearAll();\n\n    // Selection does not exist\n    if (!start || !end) {\n      this._clearState();\n      return;\n    }\n\n    // Translate from buffer position to viewport position\n    const viewportStartRow = start[1] - this._bufferService.buffer.ydisp;\n    const viewportEndRow = end[1] - this._bufferService.buffer.ydisp;\n    const viewportCappedStartRow = Math.max(viewportStartRow, 0);\n    const viewportCappedEndRow = Math.min(viewportEndRow, this._bufferService.rows - 1);\n\n    // No need to draw the selection\n    if (viewportCappedStartRow >= this._bufferService.rows || viewportCappedEndRow < 0) {\n      return;\n    }\n\n    this._ctx.fillStyle = this._colors.selection.css;\n\n    if (columnSelectMode) {\n      const startCol = start[0];\n      const width = end[0] - startCol;\n      const height = viewportCappedEndRow - viewportCappedStartRow + 1;\n      this._fillCells(startCol, viewportCappedStartRow, width, height);\n    } else {\n      // Draw first row\n      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;\n      const startRowEndCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;\n      this._fillCells(startCol, viewportCappedStartRow, startRowEndCol - startCol, 1);\n\n      // Draw middle rows\n      const middleRowsCount = Math.max(viewportCappedEndRow - viewportCappedStartRow - 1, 0);\n      this._fillCells(0, viewportCappedStartRow + 1, this._bufferService.cols, middleRowsCount);\n\n      // Draw final row\n      if (viewportCappedStartRow !== viewportCappedEndRow) {\n        // Only draw viewportEndRow if it's not the same as viewportStartRow\n        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;\n        this._fillCells(0, viewportCappedEndRow, endCol, 1);\n      }\n    }\n\n    // Save state for next render\n    this._state.start = [start[0], start[1]];\n    this._state.end = [end[0], end[1]];\n    this._state.columnSelectMode = columnSelectMode;\n    this._state.ydisp = this._bufferService.buffer.ydisp;\n  }\n\n  private _didStateChange(start: [number, number], end: [number, number], columnSelectMode: boolean, ydisp: number): boolean {\n    return !this._areCoordinatesEqual(start, this._state.start) ||\n      !this._areCoordinatesEqual(end, this._state.end) ||\n      columnSelectMode !== this._state.columnSelectMode ||\n      ydisp !== this._state.ydisp;\n  }\n\n  private _areCoordinatesEqual(coord1: [number, number] | undefined, coord2: [number, number] | undefined): boolean {\n    if (!coord1 || !coord2) {\n      return false;\n    }\n\n    return coord1[0] === coord2[0] && coord1[1] === coord2[1];\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions } from 'browser/renderer/Types';\nimport { BaseRenderLayer } from '../browser/renderer/BaseRenderLayer';\nimport { ITerminal } from '../Types';\nimport { ICellData } from 'common/Types';\nimport { CellData } from 'common/buffer/CellData';\nimport { IColorSet } from 'browser/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\ninterface ICursorState {\n  x: number;\n  y: number;\n  isFocused: boolean;\n  style: string;\n  width: number;\n}\n\n/**\n * The time between cursor blinks.\n */\nconst BLINK_INTERVAL = 600;\n\nexport class CursorRenderLayer extends BaseRenderLayer {\n  private _state: ICursorState;\n  private _cursorRenderers: {[key: string]: (x: number, y: number, cell: ICellData) => void};\n  private _cursorBlinkStateManager: CursorBlinkStateManager;\n  private _cell: ICellData = new CellData();\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    private _terminal: ITerminal,\n    rendererId: number,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'cursor', zIndex, true, colors, rendererId, bufferService, optionsService);\n    this._state = {\n      x: null,\n      y: null,\n      isFocused: null,\n      style: null,\n      width: null\n    };\n    this._cursorRenderers = {\n      'bar': this._renderBarCursor.bind(this),\n      'block': this._renderBlockCursor.bind(this),\n      'underline': this._renderUnderlineCursor.bind(this)\n    };\n    // TODO: Consider initial options? Maybe onOptionsChanged should be called at the end of open?\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._state = {\n      x: null,\n      y: null,\n      isFocused: null,\n      style: null,\n      width: null\n    };\n  }\n\n  public reset(): void {\n    this._clearCursor();\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.dispose();\n      this._cursorBlinkStateManager = null;\n      this.onOptionsChanged();\n    }\n  }\n\n  public onBlur(): void {\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.pause();\n    }\n    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);\n  }\n\n  public onFocus(): void {\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.resume();\n    } else {\n      this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);\n    }\n  }\n\n  public onOptionsChanged(): void {\n    if (this._optionsService.options.cursorBlink) {\n      if (!this._cursorBlinkStateManager) {\n        this._cursorBlinkStateManager = new CursorBlinkStateManager(this._terminal.isFocused, () => {\n          this._render(true);\n        });\n      }\n    } else {\n      if (this._cursorBlinkStateManager) {\n        this._cursorBlinkStateManager.dispose();\n        this._cursorBlinkStateManager = null;\n      }\n    }\n    // Request a refresh from the terminal as management of rendering is being\n    // moved back to the terminal\n    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);\n  }\n\n  public onCursorMove(): void {\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.restartBlinkAnimation();\n    }\n  }\n\n  public onGridChanged(startRow: number, endRow: number): void {\n    if (!this._cursorBlinkStateManager || this._cursorBlinkStateManager.isPaused) {\n      this._render(false);\n    } else {\n      this._cursorBlinkStateManager.restartBlinkAnimation();\n    }\n  }\n\n  private _render(triggeredByAnimationFrame: boolean): void {\n    // Don't draw the cursor if it's hidden\n    if (!this._terminal.cursorState || this._terminal.cursorHidden) {\n      this._clearCursor();\n      return;\n    }\n\n    const cursorY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;\n    const viewportRelativeCursorY = cursorY - this._bufferService.buffer.ydisp;\n\n    // Don't draw the cursor if it's off-screen\n    if (viewportRelativeCursorY < 0 || viewportRelativeCursorY >= this._bufferService.rows) {\n      this._clearCursor();\n      return;\n    }\n\n    this._bufferService.buffer.lines.get(cursorY).loadCell(this._bufferService.buffer.x, this._cell);\n    if (this._cell.content === undefined) {\n      return;\n    }\n\n    if (!this._terminal.isFocused) {\n      this._clearCursor();\n      this._ctx.save();\n      this._ctx.fillStyle = this._colors.cursor.css;\n      const cursorStyle = this._optionsService.options.cursorStyle;\n      if (cursorStyle && cursorStyle !== 'block') {\n        this._cursorRenderers[cursorStyle](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);\n      } else {\n        this._renderBlurCursor(this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);\n      }\n      this._ctx.restore();\n      this._state.x = this._bufferService.buffer.x;\n      this._state.y = viewportRelativeCursorY;\n      this._state.isFocused = false;\n      this._state.style = cursorStyle;\n      this._state.width = this._cell.getWidth();\n      return;\n    }\n\n    // Don't draw the cursor if it's blinking\n    if (this._cursorBlinkStateManager && !this._cursorBlinkStateManager.isCursorVisible) {\n      this._clearCursor();\n      return;\n    }\n\n    if (this._state) {\n      // The cursor is already in the correct spot, don't redraw\n      if (this._state.x === this._bufferService.buffer.x &&\n          this._state.y === viewportRelativeCursorY &&\n          this._state.isFocused === this._terminal.isFocused &&\n          this._state.style === this._optionsService.options.cursorStyle &&\n          this._state.width === this._cell.getWidth()) {\n        return;\n      }\n      this._clearCursor();\n    }\n\n    this._ctx.save();\n    this._cursorRenderers[this._optionsService.options.cursorStyle || 'block'](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);\n    this._ctx.restore();\n\n    this._state.x = this._bufferService.buffer.x;\n    this._state.y = viewportRelativeCursorY;\n    this._state.isFocused = false;\n    this._state.style = this._optionsService.options.cursorStyle;\n    this._state.width = this._cell.getWidth();\n  }\n\n  private _clearCursor(): void {\n    if (this._state) {\n      this._clearCells(this._state.x, this._state.y, this._state.width, 1);\n      this._state = {\n        x: null,\n        y: null,\n        isFocused: null,\n        style: null,\n        width: null\n      };\n    }\n  }\n\n  private _renderBarCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.fillStyle = this._colors.cursor.css;\n    this._fillLeftLineAtCell(x, y);\n    this._ctx.restore();\n  }\n\n  private _renderBlockCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.fillStyle = this._colors.cursor.css;\n    this._fillCells(x, y, cell.getWidth(), 1);\n    this._ctx.fillStyle = this._colors.cursorAccent.css;\n    this._fillCharTrueColor(cell, x, y);\n    this._ctx.restore();\n  }\n\n  private _renderUnderlineCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.fillStyle = this._colors.cursor.css;\n    this._fillBottomLineAtCells(x, y);\n    this._ctx.restore();\n  }\n\n  private _renderBlurCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.strokeStyle = this._colors.cursor.css;\n    this._strokeRectAtCell(x, y, cell.getWidth(), 1);\n    this._ctx.restore();\n  }\n}\n\nclass CursorBlinkStateManager {\n  public isCursorVisible: boolean;\n\n  private _animationFrame: number;\n  private _blinkStartTimeout: number;\n  private _blinkInterval: number;\n\n  /**\n   * The time at which the animation frame was restarted, this is used on the\n   * next render to restart the timers so they don't need to restart the timers\n   * multiple times over a short period.\n   */\n  private _animationTimeRestarted: number;\n\n  constructor(\n    isFocused: boolean,\n    private _renderCallback: () => void\n  ) {\n    this.isCursorVisible = true;\n    if (isFocused) {\n      this._restartInterval();\n    }\n  }\n\n  public get isPaused(): boolean { return !(this._blinkStartTimeout || this._blinkInterval); }\n\n  public dispose(): void {\n    if (this._blinkInterval) {\n      window.clearInterval(this._blinkInterval);\n      this._blinkInterval = null;\n    }\n    if (this._blinkStartTimeout) {\n      window.clearTimeout(this._blinkStartTimeout);\n      this._blinkStartTimeout = null;\n    }\n    if (this._animationFrame) {\n      window.cancelAnimationFrame(this._animationFrame);\n      this._animationFrame = null;\n    }\n  }\n\n  public restartBlinkAnimation(): void {\n    if (this.isPaused) {\n      return;\n    }\n    // Save a timestamp so that the restart can be done on the next interval\n    this._animationTimeRestarted = Date.now();\n    // Force a cursor render to ensure it's visible and in the correct position\n    this.isCursorVisible = true;\n    if (!this._animationFrame) {\n      this._animationFrame = window.requestAnimationFrame(() => {\n        this._renderCallback();\n        this._animationFrame = null;\n      });\n    }\n  }\n\n  private _restartInterval(timeToStart: number = BLINK_INTERVAL): void {\n    // Clear any existing interval\n    if (this._blinkInterval) {\n      window.clearInterval(this._blinkInterval);\n    }\n\n    // Setup the initial timeout which will hide the cursor, this is done before\n    // the regular interval is setup in order to support restarting the blink\n    // animation in a lightweight way (without thrashing clearInterval and\n    // setInterval).\n    this._blinkStartTimeout = <number><any>setTimeout(() => {\n      // Check if another animation restart was requested while this was being\n      // started\n      if (this._animationTimeRestarted) {\n        const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);\n        this._animationTimeRestarted = null;\n        if (time > 0) {\n          this._restartInterval(time);\n          return;\n        }\n      }\n\n      // Hide the cursor\n      this.isCursorVisible = false;\n      this._animationFrame = window.requestAnimationFrame(() => {\n        this._renderCallback();\n        this._animationFrame = null;\n      });\n\n      // Setup the blink interval\n      this._blinkInterval = <number><any>setInterval(() => {\n        // Adjust the animation time if it was restarted\n        if (this._animationTimeRestarted) {\n          // calc time diff\n          // Make restart interval do a setTimeout initially?\n          const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);\n          this._animationTimeRestarted = null;\n          this._restartInterval(time);\n          return;\n        }\n\n        // Invert visibility and render\n        this.isCursorVisible = !this.isCursorVisible;\n        this._animationFrame = window.requestAnimationFrame(() => {\n          this._renderCallback();\n          this._animationFrame = null;\n        });\n      }, BLINK_INTERVAL);\n    }, timeToStart);\n  }\n\n  public pause(): void {\n    this.isCursorVisible = true;\n    if (this._blinkInterval) {\n      window.clearInterval(this._blinkInterval);\n      this._blinkInterval = null;\n    }\n    if (this._blinkStartTimeout) {\n      window.clearTimeout(this._blinkStartTimeout);\n      this._blinkStartTimeout = null;\n    }\n    if (this._animationFrame) {\n      window.cancelAnimationFrame(this._animationFrame);\n      this._animationFrame = null;\n    }\n  }\n\n  public resume(): void {\n    this._animationTimeRestarted = null;\n    this._restartInterval();\n    this.restartBlinkAnimation();\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions } from 'browser/renderer/Types';\nimport { BaseRenderLayer } from './BaseRenderLayer';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { is256Color } from 'browser/renderer/atlas/CharAtlasUtils';\nimport { IColorSet, ILinkifierEvent, ILinkifier } from 'browser/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\nexport class LinkRenderLayer extends BaseRenderLayer {\n  private _state: ILinkifierEvent | undefined;\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    rendererId: number,\n    linkifier: ILinkifier,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'link', zIndex, true, colors, rendererId, bufferService, optionsService);\n    linkifier.onLinkHover(e => this._onLinkHover(e));\n    linkifier.onLinkLeave(e => this._onLinkLeave(e));\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._state = undefined;\n  }\n\n  public reset(): void {\n    this._clearCurrentLink();\n  }\n\n  private _clearCurrentLink(): void {\n    if (this._state) {\n      this._clearCells(this._state.x1, this._state.y1, this._state.cols - this._state.x1, 1);\n      const middleRowCount = this._state.y2 - this._state.y1 - 1;\n      if (middleRowCount > 0) {\n        this._clearCells(0, this._state.y1 + 1, this._state.cols, middleRowCount);\n      }\n      this._clearCells(0, this._state.y2, this._state.x2, 1);\n      this._state = undefined;\n    }\n  }\n\n  private _onLinkHover(e: ILinkifierEvent): void {\n    if (e.fg === INVERTED_DEFAULT_COLOR) {\n      this._ctx.fillStyle = this._colors.background.css;\n    } else if (e.fg && is256Color(e.fg)) {\n      // 256 color support\n      this._ctx.fillStyle = this._colors.ansi[e.fg].css;\n    } else {\n      this._ctx.fillStyle = this._colors.foreground.css;\n    }\n\n    if (e.y1 === e.y2) {\n      // Single line link\n      this._fillBottomLineAtCells(e.x1, e.y1, e.x2 - e.x1);\n    } else {\n      // Multi-line link\n      this._fillBottomLineAtCells(e.x1, e.y1, e.cols - e.x1);\n      for (let y = e.y1 + 1; y < e.y2; y++) {\n        this._fillBottomLineAtCells(0, y, e.cols);\n      }\n      this._fillBottomLineAtCells(0, e.y2, e.x2);\n    }\n    this._state = e;\n  }\n\n  private _onLinkLeave(e: ILinkifierEvent): void {\n    this._clearCurrentLink();\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ILinkifierEvent, ILinkMatcher, LinkMatcherHandler, ILinkMatcherOptions, ILinkifier, IMouseZoneManager, IMouseZone, IRegisteredLinkMatcher } from 'browser/Types';\nimport { IBufferStringIteratorResult } from 'common/buffer/Types';\nimport { getStringCellWidth } from 'common/CharWidth';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { ILogService, IBufferService } from 'common/services/Services';\n\n/**\n * Limit of the unwrapping line expansion (overscan) at the top and bottom\n * of the actual viewport in ASCII characters.\n * A limit of 2000 should match most sane urls.\n */\nconst OVERSCAN_CHAR_LIMIT = 2000;\n\n/**\n * The Linkifier applies links to rows shortly after they have been refreshed.\n */\nexport class Linkifier implements ILinkifier {\n  /**\n   * The time to wait after a row is changed before it is linkified. This prevents\n   * the costly operation of searching every row multiple times, potentially a\n   * huge amount of times.\n   */\n  protected static _timeBeforeLatency = 200;\n\n  protected _linkMatchers: IRegisteredLinkMatcher[] = [];\n\n  private _mouseZoneManager: IMouseZoneManager | undefined;\n  private _element: HTMLElement | undefined;\n\n  private _rowsTimeoutId: number | undefined;\n  private _nextLinkMatcherId = 0;\n  private _rowsToLinkify: { start: number | undefined, end: number | undefined };\n\n  private _onLinkHover = new EventEmitter<ILinkifierEvent>();\n  public get onLinkHover(): IEvent<ILinkifierEvent> { return this._onLinkHover.event; }\n  private _onLinkLeave = new EventEmitter<ILinkifierEvent>();\n  public get onLinkLeave(): IEvent<ILinkifierEvent> { return this._onLinkLeave.event; }\n  private _onLinkTooltip = new EventEmitter<ILinkifierEvent>();\n  public get onLinkTooltip(): IEvent<ILinkifierEvent> { return this._onLinkTooltip.event; }\n\n  constructor(\n    protected readonly _bufferService: IBufferService,\n    private readonly _logService: ILogService\n  ) {\n    this._rowsToLinkify = {\n      start: undefined,\n      end: undefined\n    };\n  }\n\n  /**\n   * Attaches the linkifier to the DOM, enabling linkification.\n   * @param mouseZoneManager The mouse zone manager to register link zones with.\n   */\n  public attachToDom(element: HTMLElement, mouseZoneManager: IMouseZoneManager): void {\n    this._element = element;\n    this._mouseZoneManager = mouseZoneManager;\n  }\n\n  /**\n   * Queue linkification on a set of rows.\n   * @param start The row to linkify from (inclusive).\n   * @param end The row to linkify to (inclusive).\n   */\n  public linkifyRows(start: number, end: number): void {\n    // Don't attempt linkify if not yet attached to DOM\n    if (!this._mouseZoneManager) {\n      return;\n    }\n\n    // Increase range to linkify\n    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {\n      this._rowsToLinkify.start = start;\n      this._rowsToLinkify.end = end;\n    } else {\n      this._rowsToLinkify.start = Math.min(this._rowsToLinkify.start, start);\n      this._rowsToLinkify.end = Math.max(this._rowsToLinkify.end, end);\n    }\n\n    // Clear out any existing links on this row range\n    this._mouseZoneManager.clearAll(start, end);\n\n    // Restart timer\n    if (this._rowsTimeoutId) {\n      clearTimeout(this._rowsTimeoutId);\n    }\n    this._rowsTimeoutId = <number><any>setTimeout(() => this._linkifyRows(), Linkifier._timeBeforeLatency);\n  }\n\n  /**\n   * Linkifies the rows requested.\n   */\n  private _linkifyRows(): void {\n    this._rowsTimeoutId = undefined;\n    const buffer = this._bufferService.buffer;\n\n    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {\n      this._logService.debug('_rowToLinkify was unset before _linkifyRows was called');\n      return;\n    }\n\n    // Ensure the start row exists\n    const absoluteRowIndexStart = buffer.ydisp + this._rowsToLinkify.start;\n    if (absoluteRowIndexStart >= buffer.lines.length) {\n      return;\n    }\n\n    // Invalidate bad end row values (if a resize happened)\n    const absoluteRowIndexEnd = buffer.ydisp + Math.min(this._rowsToLinkify.end, this._bufferService.rows) + 1;\n\n    // Iterate over the range of unwrapped content strings within start..end\n    // (excluding).\n    // _doLinkifyRow gets full unwrapped lines with the start row as buffer offset\n    // for every matcher.\n    // The unwrapping is needed to also match content that got wrapped across\n    // several buffer lines. To avoid a worst case scenario where the whole buffer\n    // contains just a single unwrapped string we limit this line expansion beyond\n    // the viewport to +OVERSCAN_CHAR_LIMIT chars (overscan) at top and bottom.\n    // This comes with the tradeoff that matches longer than OVERSCAN_CHAR_LIMIT\n    // chars will not match anymore at the viewport borders.\n    const overscanLineLimit = Math.ceil(OVERSCAN_CHAR_LIMIT / this._bufferService.cols);\n    const iterator = this._bufferService.buffer.iterator(\n      false, absoluteRowIndexStart, absoluteRowIndexEnd, overscanLineLimit, overscanLineLimit);\n    while (iterator.hasNext()) {\n      const lineData: IBufferStringIteratorResult = iterator.next();\n      for (let i = 0; i < this._linkMatchers.length; i++) {\n        this._doLinkifyRow(lineData.range.first, lineData.content, this._linkMatchers[i]);\n      }\n    }\n\n    this._rowsToLinkify.start = undefined;\n    this._rowsToLinkify.end = undefined;\n  }\n\n  /**\n   * Registers a link matcher, allowing custom link patterns to be matched and\n   * handled.\n   * @param regex The regular expression to search for. Specifically, this\n   * searches the textContent of the rows. You will want to use \\s to match a\n   * space ' ' character for example.\n   * @param handler The callback when the link is called.\n   * @param options Options for the link matcher.\n   * @return The ID of the new matcher, this can be used to deregister.\n   */\n  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: ILinkMatcherOptions = {}): number {\n    if (!handler) {\n      throw new Error('handler must be defined');\n    }\n    const matcher: IRegisteredLinkMatcher = {\n      id: this._nextLinkMatcherId++,\n      regex,\n      handler,\n      matchIndex: options.matchIndex,\n      validationCallback: options.validationCallback,\n      hoverTooltipCallback: options.tooltipCallback,\n      hoverLeaveCallback: options.leaveCallback,\n      willLinkActivate: options.willLinkActivate,\n      priority: options.priority || 0\n    };\n    this._addLinkMatcherToList(matcher);\n    return matcher.id;\n  }\n\n  /**\n   * Inserts a link matcher to the list in the correct position based on the\n   * priority of each link matcher. New link matchers of equal priority are\n   * considered after older link matchers.\n   * @param matcher The link matcher to be added.\n   */\n  private _addLinkMatcherToList(matcher: IRegisteredLinkMatcher): void {\n    if (this._linkMatchers.length === 0) {\n      this._linkMatchers.push(matcher);\n      return;\n    }\n\n    for (let i = this._linkMatchers.length - 1; i >= 0; i--) {\n      if (matcher.priority <= this._linkMatchers[i].priority) {\n        this._linkMatchers.splice(i + 1, 0, matcher);\n        return;\n      }\n    }\n\n    this._linkMatchers.splice(0, 0, matcher);\n  }\n\n  /**\n   * Deregisters a link matcher if it has been registered.\n   * @param matcherId The link matcher's ID (returned after register)\n   * @return Whether a link matcher was found and deregistered.\n   */\n  public deregisterLinkMatcher(matcherId: number): boolean {\n    for (let i = 0; i < this._linkMatchers.length; i++) {\n      if (this._linkMatchers[i].id === matcherId) {\n        this._linkMatchers.splice(i, 1);\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Linkifies a row given a specific handler.\n   * @param rowIndex The row index to linkify (absolute index).\n   * @param text string content of the unwrapped row.\n   * @param matcher The link matcher for this line.\n   */\n  private _doLinkifyRow(rowIndex: number, text: string, matcher: ILinkMatcher): void {\n    // clone regex to do a global search on text\n    const rex = new RegExp(matcher.regex.source, (matcher.regex.flags || '') + 'g');\n    let match;\n    let stringIndex = -1;\n    while ((match = rex.exec(text)) !== null) {\n      const uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];\n      if (!uri) {\n        // something matched but does not comply with the given matchIndex\n        // since this is most likely a bug the regex itself we simply do nothing here\n        this._logService.debug('match found without corresponding matchIndex', match, matcher);\n        break;\n      }\n\n      // Get index, match.index is for the outer match which includes negated chars\n      // therefore we cannot use match.index directly, instead we search the position\n      // of the match group in text again\n      // also correct regex and string search offsets for the next loop run\n      stringIndex = text.indexOf(uri, stringIndex + 1);\n      rex.lastIndex = stringIndex + uri.length;\n      if (stringIndex < 0) {\n        // invalid stringIndex (should not have happened)\n        break;\n      }\n\n      // get the buffer index as [absolute row, col] for the match\n      const bufferIndex = this._bufferService.buffer.stringIndexToBufferIndex(rowIndex, stringIndex);\n      if (bufferIndex[0] < 0) {\n        // invalid bufferIndex (should not have happened)\n        break;\n      }\n\n      const line = this._bufferService.buffer.lines.get(bufferIndex[0]);\n      if (!line) {\n        break;\n      }\n\n      const attr = line.getFg(bufferIndex[1]);\n      const fg = attr ? (attr >> 9) & 0x1ff : undefined;\n\n      if (matcher.validationCallback) {\n        matcher.validationCallback(uri, isValid => {\n          // Discard link if the line has already changed\n          if (this._rowsTimeoutId) {\n            return;\n          }\n          if (isValid) {\n            this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);\n          }\n        });\n      } else {\n        this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);\n      }\n    }\n  }\n\n  /**\n   * Registers a link to the mouse zone manager.\n   * @param x The column the link starts.\n   * @param y The row the link is on.\n   * @param uri The URI of the link.\n   * @param matcher The link matcher for the link.\n   * @param fg The link color for hover event.\n   */\n  private _addLink(x: number, y: number, uri: string, matcher: ILinkMatcher, fg: number | undefined): void {\n    if (!this._mouseZoneManager || !this._element) {\n      return;\n    }\n\n    const width = getStringCellWidth(uri);\n    const x1 = x % this._bufferService.cols;\n    const y1 = y + Math.floor(x / this._bufferService.cols);\n    let x2 = (x1 + width) % this._bufferService.cols;\n    let y2 = y1 + Math.floor((x1 + width) / this._bufferService.cols);\n    if (x2 === 0) {\n      x2 = this._bufferService.cols;\n      y2--;\n    }\n\n    this._mouseZoneManager.add(new MouseZone(\n      x1 + 1,\n      y1 + 1,\n      x2 + 1,\n      y2 + 1,\n      e => {\n        if (matcher.handler) {\n          return matcher.handler(e, uri);\n        }\n        window.open(uri, '_blank');\n      },\n      () => {\n        this._onLinkHover.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));\n        this._element!.classList.add('xterm-cursor-pointer');\n      },\n      e => {\n        this._onLinkTooltip.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));\n        if (matcher.hoverTooltipCallback) {\n          // Note that IViewportRange use 1-based coordinates to align with escape sequences such\n          // as CUP which use 1,1 as the default for row/col\n          matcher.hoverTooltipCallback(e, uri, { start: { x: x1, y: y1 }, end: { x: x2, y: y2 } });\n        }\n      },\n      () => {\n        this._onLinkLeave.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));\n        this._element!.classList.remove('xterm-cursor-pointer');\n        if (matcher.hoverLeaveCallback) {\n          matcher.hoverLeaveCallback();\n        }\n      },\n      e => {\n        if (matcher.willLinkActivate) {\n          return matcher.willLinkActivate(e, uri);\n        }\n        return true;\n      }\n    ));\n  }\n\n  private _createLinkHoverEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent {\n    return { x1, y1, x2, y2, cols: this._bufferService.cols, fg };\n  }\n}\n\nexport class MouseZone implements IMouseZone {\n  constructor(\n    public x1: number,\n    public y1: number,\n    public x2: number,\n    public y2: number,\n    public clickCallback: (e: MouseEvent) => any,\n    public hoverCallback: (e: MouseEvent) => any,\n    public tooltipCallback: (e: MouseEvent) => any,\n    public leaveCallback: () => void,\n    public willLinkActivate: (e: MouseEvent) => boolean\n  ) {\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ISelectionRedrawRequestEvent } from 'browser/selection/Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IBufferLine, IDisposable } from 'common/Types';\nimport * as Browser from 'common/Platform';\nimport { SelectionModel } from 'browser/selection/SelectionModel';\nimport { CellData } from 'common/buffer/CellData';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { ICharSizeService, IMouseService, ISelectionService } from 'browser/services/Services';\nimport { IBufferService, IOptionsService, ICoreService } from 'common/services/Services';\nimport { getCoordsRelativeToElement } from 'browser/input/Mouse';\nimport { moveToCellSequence } from 'browser/input/MoveToCell';\n\n/**\n * The number of pixels the mouse needs to be above or below the viewport in\n * order to scroll at the maximum speed.\n */\nconst DRAG_SCROLL_MAX_THRESHOLD = 50;\n\n/**\n * The maximum scrolling speed\n */\nconst DRAG_SCROLL_MAX_SPEED = 15;\n\n/**\n * The number of milliseconds between drag scroll updates.\n */\nconst DRAG_SCROLL_INTERVAL = 50;\n\n/**\n * The maximum amount of time that can have elapsed for an alt click to move the\n * cursor.\n */\nconst ALT_CLICK_MOVE_CURSOR_TIME = 500;\n\nconst NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);\nconst ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');\n\n/**\n * Represents a position of a word on a line.\n */\ninterface IWordPosition {\n  start: number;\n  length: number;\n}\n\n/**\n * A selection mode, this drives how the selection behaves on mouse move.\n */\nexport const enum SelectionMode {\n  NORMAL,\n  WORD,\n  LINE,\n  COLUMN\n}\n\n/**\n * A class that manages the selection of the terminal. With help from\n * SelectionModel, SelectionService handles with all logic associated with\n * dealing with the selection, including handling mouse interaction, wide\n * characters and fetching the actual text within the selection. Rendering is\n * not handled by the SelectionService but the onRedrawRequest event is fired\n * when the selection is ready to be redrawn (on an animation frame).\n */\nexport class SelectionService implements ISelectionService {\n  serviceBrand: any;\n\n  protected _model: SelectionModel;\n\n  /**\n   * The amount to scroll every drag scroll update (depends on how far the mouse\n   * drag is above or below the terminal).\n   */\n  private _dragScrollAmount: number = 0;\n\n  /**\n   * The current selection mode.\n   */\n  protected _activeSelectionMode: SelectionMode;\n\n  /**\n   * A setInterval timer that is active while the mouse is down whose callback\n   * scrolls the viewport when necessary.\n   */\n  private _dragScrollIntervalTimer: number | undefined;\n\n  /**\n   * The animation frame ID used for refreshing the selection.\n   */\n  private _refreshAnimationFrame: number | undefined;\n\n  /**\n   * Whether selection is enabled.\n   */\n  private _enabled = true;\n\n  private _mouseMoveListener: EventListener;\n  private _mouseUpListener: EventListener;\n  private _trimListener: IDisposable;\n  private _workCell: CellData = new CellData();\n\n  private _mouseDownTimeStamp: number = 0;\n\n  private _onLinuxMouseSelection = new EventEmitter<string>();\n  public get onLinuxMouseSelection(): IEvent<string> { return this._onLinuxMouseSelection.event; }\n  private _onRedrawRequest = new EventEmitter<ISelectionRedrawRequestEvent>();\n  public get onRedrawRequest(): IEvent<ISelectionRedrawRequestEvent> { return this._onRedrawRequest.event; }\n  private _onSelectionChange = new EventEmitter<void>();\n  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }\n\n  constructor(\n    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,\n    private readonly _element: HTMLElement,\n    private readonly _screenElement: HTMLElement,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @ICoreService private readonly _coreService: ICoreService,\n    @IMouseService private readonly _mouseService: IMouseService,\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    // Init listeners\n    this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);\n    this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);\n    this._coreService.onUserInput(() => {\n      if (this.hasSelection) {\n        this.clearSelection();\n      }\n    });\n    this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._onTrim(amount));\n    this._bufferService.buffers.onBufferActivate(e => this._onBufferActivate(e));\n\n    this.enable();\n\n    this._model = new SelectionModel(this._bufferService);\n    this._activeSelectionMode = SelectionMode.NORMAL;\n  }\n\n  public dispose(): void {\n    this._removeMouseDownListeners();\n  }\n\n  public reset(): void {\n    this.clearSelection();\n  }\n\n  /**\n   * Disables the selection manager. This is useful for when terminal mouse\n   * are enabled.\n   */\n  public disable(): void {\n    this.clearSelection();\n    this._enabled = false;\n  }\n\n  /**\n   * Enable the selection manager.\n   */\n  public enable(): void {\n    this._enabled = true;\n  }\n\n  public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }\n  public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }\n\n  /**\n   * Gets whether there is an active text selection.\n   */\n  public get hasSelection(): boolean {\n    const start = this._model.finalSelectionStart;\n    const end = this._model.finalSelectionEnd;\n    if (!start || !end) {\n      return false;\n    }\n    return start[0] !== end[0] || start[1] !== end[1];\n  }\n\n  /**\n   * Gets the text currently selected.\n   */\n  public get selectionText(): string {\n    const start = this._model.finalSelectionStart;\n    const end = this._model.finalSelectionEnd;\n    if (!start || !end) {\n      return '';\n    }\n\n    const buffer = this._bufferService.buffer;\n    const result: string[] = [];\n\n    if (this._activeSelectionMode === SelectionMode.COLUMN) {\n      // Ignore zero width selections\n      if (start[0] === end[0]) {\n        return '';\n      }\n\n      for (let i = start[1]; i <= end[1]; i++) {\n        const lineText = buffer.translateBufferLineToString(i, true, start[0], end[0]);\n        result.push(lineText);\n      }\n    } else {\n      // Get first row\n      const startRowEndCol = start[1] === end[1] ? end[0] : undefined;\n      result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));\n\n      // Get middle rows\n      for (let i = start[1] + 1; i <= end[1] - 1; i++) {\n        const bufferLine = buffer.lines.get(i);\n        const lineText = buffer.translateBufferLineToString(i, true);\n        if (bufferLine && bufferLine.isWrapped) {\n          result[result.length - 1] += lineText;\n        } else {\n          result.push(lineText);\n        }\n      }\n\n      // Get final row\n      if (start[1] !== end[1]) {\n        const bufferLine = buffer.lines.get(end[1]);\n        const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);\n        if (bufferLine && bufferLine!.isWrapped) {\n          result[result.length - 1] += lineText;\n        } else {\n          result.push(lineText);\n        }\n      }\n    }\n\n    // Format string by replacing non-breaking space chars with regular spaces\n    // and joining the array into a multi-line string.\n    const formattedResult = result.map(line => {\n      return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');\n    }).join(Browser.isWindows ? '\\r\\n' : '\\n');\n\n    return formattedResult;\n  }\n\n  /**\n   * Clears the current terminal selection.\n   */\n  public clearSelection(): void {\n    this._model.clearSelection();\n    this._removeMouseDownListeners();\n    this.refresh();\n    this._onSelectionChange.fire();\n  }\n\n  /**\n   * Queues a refresh, redrawing the selection on the next opportunity.\n   * @param isLinuxMouseSelection Whether the selection should be registered as a new\n   * selection on Linux.\n   */\n  public refresh(isLinuxMouseSelection?: boolean): void {\n    // Queue the refresh for the renderer\n    if (!this._refreshAnimationFrame) {\n      this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());\n    }\n\n    // If the platform is Linux and the refresh call comes from a mouse event,\n    // we need to update the selection for middle click to paste selection.\n    if (Browser.isLinux && isLinuxMouseSelection) {\n      const selectionText = this.selectionText;\n      if (selectionText.length) {\n        this._onLinuxMouseSelection.fire(this.selectionText);\n      }\n    }\n  }\n\n  /**\n   * Fires the refresh event, causing consumers to pick it up and redraw the\n   * selection state.\n   */\n  private _refresh(): void {\n    this._refreshAnimationFrame = undefined;\n    this._onRedrawRequest.fire({\n      start: this._model.finalSelectionStart,\n      end: this._model.finalSelectionEnd,\n      columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN\n    });\n  }\n\n  /**\n   * Checks if the current click was inside the current selection\n   * @param event The mouse event\n   */\n  public isClickInSelection(event: MouseEvent): boolean {\n    const coords = this._getMouseBufferCoords(event);\n    const start = this._model.finalSelectionStart;\n    const end = this._model.finalSelectionEnd;\n\n    if (!start || !end || !coords) {\n      return false;\n    }\n\n    return this._areCoordsInSelection(coords, start, end);\n  }\n\n  protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {\n    return (coords[1] > start[1] && coords[1] < end[1]) ||\n        (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||\n        (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||\n        (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);\n  }\n\n  /**\n   * Selects word at the current mouse event coordinates.\n   * @param event The mouse event.\n   */\n  public selectWordAtCursor(event: MouseEvent): void {\n    const coords = this._getMouseBufferCoords(event);\n    if (coords) {\n      this._selectWordAt(coords, false);\n      this._model.selectionEnd = undefined;\n      this.refresh(true);\n    }\n  }\n\n  /**\n   * Selects all text within the terminal.\n   */\n  public selectAll(): void {\n    this._model.isSelectAllActive = true;\n    this.refresh();\n    this._onSelectionChange.fire();\n  }\n\n  public selectLines(start: number, end: number): void {\n    this._model.clearSelection();\n    start = Math.max(start, 0);\n    end = Math.min(end, this._bufferService.buffer.lines.length - 1);\n    this._model.selectionStart = [0, start];\n    this._model.selectionEnd = [this._bufferService.cols, end];\n    this.refresh();\n    this._onSelectionChange.fire();\n  }\n\n  /**\n   * Handle the buffer being trimmed, adjust the selection position.\n   * @param amount The amount the buffer is being trimmed.\n   */\n  private _onTrim(amount: number): void {\n    const needsRefresh = this._model.onTrim(amount);\n    if (needsRefresh) {\n      this.refresh();\n    }\n  }\n\n  /**\n   * Gets the 0-based [x, y] buffer coordinates of the current mouse event.\n   * @param event The mouse event.\n   */\n  private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {\n    const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);\n    if (!coords) {\n      return undefined;\n    }\n\n    // Convert to 0-based\n    coords[0]--;\n    coords[1]--;\n\n    // Convert viewport coords to buffer coords\n    coords[1] += this._bufferService.buffer.ydisp;\n    return coords;\n  }\n\n  /**\n   * Gets the amount the viewport should be scrolled based on how far out of the\n   * terminal the mouse is.\n   * @param event The mouse event.\n   */\n  private _getMouseEventScrollAmount(event: MouseEvent): number {\n    let offset = getCoordsRelativeToElement(event, this._screenElement)[1];\n    const terminalHeight = this._bufferService.rows * Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);\n    if (offset >= 0 && offset <= terminalHeight) {\n      return 0;\n    }\n    if (offset > terminalHeight) {\n      offset -= terminalHeight;\n    }\n\n    offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);\n    offset /= DRAG_SCROLL_MAX_THRESHOLD;\n    return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));\n  }\n\n  /**\n   * Returns whether the selection manager should force selection, regardless of\n   * whether the terminal is in mouse events mode.\n   * @param event The mouse event.\n   */\n  public shouldForceSelection(event: MouseEvent): boolean {\n    if (Browser.isMac) {\n      return event.altKey && this._optionsService.options.macOptionClickForcesSelection;\n    }\n\n    return event.shiftKey;\n  }\n\n  /**\n   * Handles te mousedown event, setting up for a new selection.\n   * @param event The mousedown event.\n   */\n  public onMouseDown(event: MouseEvent): void {\n    this._mouseDownTimeStamp = event.timeStamp;\n    // If we have selection, we want the context menu on right click even if the\n    // terminal is in mouse mode.\n    if (event.button === 2 && this.hasSelection) {\n      return;\n    }\n\n    // Only action the primary button\n    if (event.button !== 0) {\n      return;\n    }\n\n    // Allow selection when using a specific modifier key, even when disabled\n    if (!this._enabled) {\n      if (!this.shouldForceSelection(event)) {\n        return;\n      }\n\n      // Don't send the mouse down event to the current process, we want to select\n      event.stopPropagation();\n    }\n\n    // Tell the browser not to start a regular selection\n    event.preventDefault();\n\n    // Reset drag scroll state\n    this._dragScrollAmount = 0;\n\n    if (this._enabled && event.shiftKey) {\n      this._onIncrementalClick(event);\n    } else {\n      if (event.detail === 1) {\n        this._onSingleClick(event);\n      } else if (event.detail === 2) {\n        this._onDoubleClick(event);\n      } else if (event.detail === 3) {\n        this._onTripleClick(event);\n      }\n    }\n\n    this._addMouseDownListeners();\n    this.refresh(true);\n  }\n\n  /**\n   * Adds listeners when mousedown is triggered.\n   */\n  private _addMouseDownListeners(): void {\n    // Listen on the document so that dragging outside of viewport works\n    if (this._screenElement.ownerDocument) {\n      this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);\n      this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);\n    }\n    this._dragScrollIntervalTimer = window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);\n  }\n\n  /**\n   * Removes the listeners that are registered when mousedown is triggered.\n   */\n  private _removeMouseDownListeners(): void {\n    if (this._screenElement.ownerDocument) {\n      this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);\n      this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);\n    }\n    clearInterval(this._dragScrollIntervalTimer);\n    this._dragScrollIntervalTimer = undefined;\n  }\n\n  /**\n   * Performs an incremental click, setting the selection end position to the mouse\n   * position.\n   * @param event The mouse event.\n   */\n  private _onIncrementalClick(event: MouseEvent): void {\n    if (this._model.selectionStart) {\n      this._model.selectionEnd = this._getMouseBufferCoords(event);\n    }\n  }\n\n  /**\n   * Performs a single click, resetting relevant state and setting the selection\n   * start position.\n   * @param event The mouse event.\n   */\n  private _onSingleClick(event: MouseEvent): void {\n    this._model.selectionStartLength = 0;\n    this._model.isSelectAllActive = false;\n    this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;\n\n    // Initialize the new selection\n    this._model.selectionStart = this._getMouseBufferCoords(event);\n    if (!this._model.selectionStart) {\n      return;\n    }\n    this._model.selectionEnd = undefined;\n\n    // Ensure the line exists\n    const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);\n    if (!line) {\n      return;\n    }\n\n    // Return early if the click event is not in the buffer (eg. in scroll bar)\n    if (line.length === this._model.selectionStart[0]) {\n      return;\n    }\n\n    // If the mouse is over the second half of a wide character, adjust the\n    // selection to cover the whole character\n    if (line.hasWidth(this._model.selectionStart[0]) === 0) {\n      this._model.selectionStart[0]++;\n    }\n  }\n\n  /**\n   * Performs a double click, selecting the current work.\n   * @param event The mouse event.\n   */\n  private _onDoubleClick(event: MouseEvent): void {\n    const coords = this._getMouseBufferCoords(event);\n    if (coords) {\n      this._activeSelectionMode = SelectionMode.WORD;\n      this._selectWordAt(coords, true);\n    }\n  }\n\n  /**\n   * Performs a triple click, selecting the current line and activating line\n   * select mode.\n   * @param event The mouse event.\n   */\n  private _onTripleClick(event: MouseEvent): void {\n    const coords = this._getMouseBufferCoords(event);\n    if (coords) {\n      this._activeSelectionMode = SelectionMode.LINE;\n      this._selectLineAt(coords[1]);\n    }\n  }\n\n  /**\n   * Returns whether the selection manager should operate in column select mode\n   * @param event the mouse or keyboard event\n   */\n  public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {\n    return event.altKey && !(Browser.isMac && this._optionsService.options.macOptionClickForcesSelection);\n  }\n\n  /**\n   * Handles the mousemove event when the mouse button is down, recording the\n   * end of the selection and refreshing the selection.\n   * @param event The mousemove event.\n   */\n  private _onMouseMove(event: MouseEvent): void {\n    // If the mousemove listener is active it means that a selection is\n    // currently being made, we should stop propagation to prevent mouse events\n    // to be sent to the pty.\n    event.stopImmediatePropagation();\n\n    // Do nothing if there is no selection start, this can happen if the first\n    // click in the terminal is an incremental click\n    if (!this._model.selectionStart) {\n      return;\n    }\n\n    // Record the previous position so we know whether to redraw the selection\n    // at the end.\n    const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;\n\n    // Set the initial selection end based on the mouse coordinates\n    this._model.selectionEnd = this._getMouseBufferCoords(event);\n    if (!this._model.selectionEnd) {\n      this.refresh(true);\n      return;\n    }\n\n    // Select the entire line if line select mode is active.\n    if (this._activeSelectionMode === SelectionMode.LINE) {\n      if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {\n        this._model.selectionEnd[0] = 0;\n      } else {\n        this._model.selectionEnd[0] = this._bufferService.cols;\n      }\n    } else if (this._activeSelectionMode === SelectionMode.WORD) {\n      this._selectToWordAt(this._model.selectionEnd);\n    }\n\n    // Determine the amount of scrolling that will happen.\n    this._dragScrollAmount = this._getMouseEventScrollAmount(event);\n\n    // If the cursor was above or below the viewport, make sure it's at the\n    // start or end of the viewport respectively. This should only happen when\n    // NOT in column select mode.\n    if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n      if (this._dragScrollAmount > 0) {\n        this._model.selectionEnd[0] = this._bufferService.cols;\n      } else if (this._dragScrollAmount < 0) {\n        this._model.selectionEnd[0] = 0;\n      }\n    }\n\n    // If the character is a wide character include the cell to the right in the\n    // selection. Note that selections at the very end of the line will never\n    // have a character.\n    const buffer = this._bufferService.buffer;\n    if (this._model.selectionEnd[1] < buffer.lines.length) {\n      const line = buffer.lines.get(this._model.selectionEnd[1]);\n      if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {\n        this._model.selectionEnd[0]++;\n      }\n    }\n\n    // Only draw here if the selection changes.\n    if (!previousSelectionEnd ||\n      previousSelectionEnd[0] !== this._model.selectionEnd[0] ||\n      previousSelectionEnd[1] !== this._model.selectionEnd[1]) {\n      this.refresh(true);\n    }\n  }\n\n  /**\n   * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the\n   * scrolling of the viewport.\n   */\n  private _dragScroll(): void {\n    if (!this._model.selectionEnd || !this._model.selectionStart) {\n      return;\n    }\n    if (this._dragScrollAmount) {\n      this._scrollLines(this._dragScrollAmount, false);\n      // Re-evaluate selection\n      // If the cursor was above or below the viewport, make sure it's at the\n      // start or end of the viewport respectively. This should only happen when\n      // NOT in column select mode.\n      const buffer = this._bufferService.buffer;\n      if (this._dragScrollAmount > 0) {\n        if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n          this._model.selectionEnd[0] = this._bufferService.cols;\n        }\n        this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);\n      } else {\n        if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n          this._model.selectionEnd[0] = 0;\n        }\n        this._model.selectionEnd[1] = buffer.ydisp;\n      }\n      this.refresh();\n    }\n  }\n\n  /**\n   * Handles the mouseup event, removing the mousedown listeners.\n   * @param event The mouseup event.\n   */\n  private _onMouseUp(event: MouseEvent): void {\n    const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;\n\n    this._removeMouseDownListeners();\n\n    if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME) {\n      if (event.altKey && this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {\n        const coordinates = this._mouseService.getCoords(\n          event,\n          this._element,\n          this._bufferService.cols,\n          this._bufferService.rows,\n          false\n        );\n        if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {\n          const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);\n          this._coreService.triggerDataEvent(sequence, true);\n        }\n      }\n    } else if (this.hasSelection) {\n      this._onSelectionChange.fire();\n    }\n  }\n\n  private _onBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {\n    this.clearSelection();\n    // Only adjust the selection on trim, shiftElements is rarely used (only in\n    // reverseIndex) and delete in a splice is only ever used when the same\n    // number of elements was just added. Given this is could actually be\n    // beneficial to leave the selection as is for these cases.\n    if (this._trimListener) {\n      this._trimListener.dispose();\n    }\n    this._trimListener = e.activeBuffer.lines.onTrim(amount => this._onTrim(amount));\n  }\n\n  /**\n   * Converts a viewport column to the character index on the buffer line, the\n   * latter takes into account wide characters.\n   * @param coords The coordinates to find the 2 index for.\n   */\n  private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, coords: [number, number]): number {\n    let charIndex = coords[0];\n    for (let i = 0; coords[0] >= i; i++) {\n      const length = bufferLine.loadCell(i, this._workCell).getChars().length;\n      if (this._workCell.getWidth() === 0) {\n        // Wide characters aren't included in the line string so decrement the\n        // index so the index is back on the wide character.\n        charIndex--;\n      } else if (length > 1 && coords[0] !== i) {\n        // Emojis take up multiple characters, so adjust accordingly. For these\n        // we don't want ot include the character at the column as we're\n        // returning the start index in the string, not the end index.\n        charIndex += length - 1;\n      }\n    }\n    return charIndex;\n  }\n\n  public setSelection(col: number, row: number, length: number): void {\n    this._model.clearSelection();\n    this._removeMouseDownListeners();\n    this._model.selectionStart = [col, row];\n    this._model.selectionStartLength = length;\n    this.refresh();\n  }\n\n  /**\n   * Gets positional information for the word at the coordinated specified.\n   * @param coords The coordinates to get the word at.\n   */\n  private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {\n    // Ensure coords are within viewport (eg. not within scroll bar)\n    if (coords[0] >= this._bufferService.cols) {\n      return undefined;\n    }\n\n    const buffer = this._bufferService.buffer;\n    const bufferLine = buffer.lines.get(coords[1]);\n    if (!bufferLine) {\n      return undefined;\n    }\n\n    const line = buffer.translateBufferLineToString(coords[1], false);\n\n    // Get actual index, taking into consideration wide characters\n    let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);\n    let endIndex = startIndex;\n\n    // Record offset to be used later\n    const charOffset = coords[0] - startIndex;\n    let leftWideCharCount = 0;\n    let rightWideCharCount = 0;\n    let leftLongCharOffset = 0;\n    let rightLongCharOffset = 0;\n\n    if (line.charAt(startIndex) === ' ') {\n      // Expand until non-whitespace is hit\n      while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {\n        startIndex--;\n      }\n      while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {\n        endIndex++;\n      }\n    } else {\n      // Expand until whitespace is hit. This algorithm works by scanning left\n      // and right from the starting position, keeping both the index format\n      // (line) and the column format (bufferLine) in sync. When a wide\n      // character is hit, it is recorded and the column index is adjusted.\n      let startCol = coords[0];\n      let endCol = coords[0];\n\n      // Consider the initial position, skip it and increment the wide char\n      // variable\n      if (bufferLine.getWidth(startCol) === 0) {\n        leftWideCharCount++;\n        startCol--;\n      }\n      if (bufferLine.getWidth(endCol) === 2) {\n        rightWideCharCount++;\n        endCol++;\n      }\n\n      // Adjust the end index for characters whose length are > 1 (emojis)\n      const length = bufferLine.getString(endCol).length;\n      if (length > 1) {\n        rightLongCharOffset += length - 1;\n        endIndex += length - 1;\n      }\n\n      // Expand the string in both directions until a space is hit\n      while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {\n        bufferLine.loadCell(startCol - 1, this._workCell);\n        const length = this._workCell.getChars().length;\n        if (this._workCell.getWidth() === 0) {\n          // If the next character is a wide char, record it and skip the column\n          leftWideCharCount++;\n          startCol--;\n        } else if (length > 1) {\n          // If the next character's string is longer than 1 char (eg. emoji),\n          // adjust the index\n          leftLongCharOffset += length - 1;\n          startIndex -= length - 1;\n        }\n        startIndex--;\n        startCol--;\n      }\n      while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {\n        bufferLine.loadCell(endCol + 1, this._workCell);\n        const length = this._workCell.getChars().length;\n        if (this._workCell.getWidth() === 2) {\n          // If the next character is a wide char, record it and skip the column\n          rightWideCharCount++;\n          endCol++;\n        } else if (length > 1) {\n          // If the next character's string is longer than 1 char (eg. emoji),\n          // adjust the index\n          rightLongCharOffset += length - 1;\n          endIndex += length - 1;\n        }\n        endIndex++;\n        endCol++;\n      }\n    }\n\n    // Incremenet the end index so it is at the start of the next character\n    endIndex++;\n\n    // Calculate the start _column_, converting the the string indexes back to\n    // column coordinates.\n    let start =\n        startIndex // The index of the selection's start char in the line string\n        + charOffset // The difference between the initial char's column and index\n        - leftWideCharCount // The number of wide chars left of the initial char\n        + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n\n    // Calculate the length in _columns_, converting the the string indexes back\n    // to column coordinates.\n    let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols\n        endIndex // The index of the selection's end char in the line string\n        - startIndex // The index of the selection's start char in the line string\n        + leftWideCharCount // The number of wide chars left of the initial char\n        + rightWideCharCount // The number of wide chars right of the initial char (inclusive)\n        - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n        - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)\n\n    if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {\n      return undefined;\n    }\n\n    // Recurse upwards if the line is wrapped and the word wraps to the above line\n    if (followWrappedLinesAbove) {\n      if (start === 0 && bufferLine.getCodePoint(0) !== 32 /*' '*/) {\n        const previousBufferLine = buffer.lines.get(coords[1] - 1);\n        if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {\n          const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);\n          if (previousLineWordPosition) {\n            const offset = this._bufferService.cols - previousLineWordPosition.start;\n            start -= offset;\n            length += offset;\n          }\n        }\n      }\n    }\n\n    // Recurse downwards if the line is wrapped and the word wraps to the next line\n    if (followWrappedLinesBelow) {\n      if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {\n        const nextBufferLine = buffer.lines.get(coords[1] + 1);\n        if (nextBufferLine && nextBufferLine.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /*' '*/) {\n          const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);\n          if (nextLineWordPosition) {\n            length += nextLineWordPosition.length;\n          }\n        }\n      }\n    }\n\n    return { start, length };\n  }\n\n  /**\n   * Selects the word at the coordinates specified.\n   * @param coords The coordinates to get the word at.\n   * @param allowWhitespaceOnlySelection If whitespace should be selected\n   */\n  protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {\n    const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);\n    if (wordPosition) {\n      // Adjust negative start value\n      while (wordPosition.start < 0) {\n        wordPosition.start += this._bufferService.cols;\n        coords[1]--;\n      }\n      this._model.selectionStart = [wordPosition.start, coords[1]];\n      this._model.selectionStartLength = wordPosition.length;\n    }\n  }\n\n  /**\n   * Sets the selection end to the word at the coordinated specified.\n   * @param coords The coordinates to get the word at.\n   */\n  private _selectToWordAt(coords: [number, number]): void {\n    const wordPosition = this._getWordAt(coords, true);\n    if (wordPosition) {\n      let endRow = coords[1];\n\n      // Adjust negative start value\n      while (wordPosition.start < 0) {\n        wordPosition.start += this._bufferService.cols;\n        endRow--;\n      }\n\n      // Adjust wrapped length value, this only needs to happen when values are reversed as in that\n      // case we're interested in the start of the word, not the end\n      if (!this._model.areSelectionValuesReversed()) {\n        while (wordPosition.start + wordPosition.length > this._bufferService.cols) {\n          wordPosition.length -= this._bufferService.cols;\n          endRow++;\n        }\n      }\n\n      this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];\n    }\n  }\n\n  /**\n   * Gets whether the character is considered a word separator by the select\n   * word logic.\n   * @param char The character to check.\n   */\n  private _isCharWordSeparator(cell: CellData): boolean {\n    // Zero width characters are never separators as they are always to the\n    // right of wide characters\n    if (cell.getWidth() === 0) {\n      return false;\n    }\n    return this._optionsService.options.wordSeparator.indexOf(cell.getChars()) >= 0;\n  }\n\n  /**\n   * Selects the line specified.\n   * @param line The line index.\n   */\n  protected _selectLineAt(line: number): void {\n    const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);\n    this._model.selectionStart = [0, wrappedRange.first];\n    this._model.selectionEnd = [this._bufferService.cols, wrappedRange.last];\n    this._model.selectionStartLength = 0;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService } from 'common/services/Services';\n\n/**\n * Represents a selection within the buffer. This model only cares about column\n * and row coordinates, not wide characters.\n */\nexport class SelectionModel {\n  /**\n   * Whether select all is currently active.\n   */\n  public isSelectAllActive: boolean = false;\n\n  /**\n   * The minimal length of the selection from the start position. When double\n   * clicking on a word, the word will be selected which makes the selection\n   * start at the start of the word and makes this variable the length.\n   */\n  public selectionStartLength: number = 0;\n\n  /**\n   * The [x, y] position the selection starts at.\n   */\n  public selectionStart: [number, number] | undefined;\n\n  /**\n   * The [x, y] position the selection ends at.\n   */\n  public selectionEnd: [number, number] | undefined;\n\n  constructor(\n    private _bufferService: IBufferService\n  ) {\n  }\n\n  /**\n   * Clears the current selection.\n   */\n  public clearSelection(): void {\n    this.selectionStart = undefined;\n    this.selectionEnd = undefined;\n    this.isSelectAllActive = false;\n    this.selectionStartLength = 0;\n  }\n\n  /**\n   * The final selection start, taking into consideration select all.\n   */\n  public get finalSelectionStart(): [number, number] | undefined {\n    if (this.isSelectAllActive) {\n      return [0, 0];\n    }\n\n    if (!this.selectionEnd || !this.selectionStart) {\n      return this.selectionStart;\n    }\n\n    return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;\n  }\n\n  /**\n   * The final selection end, taking into consideration select all, double click\n   * word selection and triple click line selection.\n   */\n  public get finalSelectionEnd(): [number, number] | undefined {\n    if (this.isSelectAllActive) {\n      return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1];\n    }\n\n    if (!this.selectionStart) {\n      return undefined;\n    }\n\n    // Use the selection start + length if the end doesn't exist or they're reversed\n    if (!this.selectionEnd || this.areSelectionValuesReversed()) {\n      const startPlusLength = this.selectionStart[0] + this.selectionStartLength;\n      if (startPlusLength > this._bufferService.cols) {\n        return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];\n      }\n      return [startPlusLength, this.selectionStart[1]];\n    }\n\n    // Ensure the the word/line is selected after a double/triple click\n    if (this.selectionStartLength) {\n      // Select the larger of the two when start and end are on the same line\n      if (this.selectionEnd[1] === this.selectionStart[1]) {\n        return [Math.max(this.selectionStart[0] + this.selectionStartLength, this.selectionEnd[0]), this.selectionEnd[1]];\n      }\n    }\n    return this.selectionEnd;\n  }\n\n  /**\n   * Returns whether the selection start and end are reversed.\n   */\n  public areSelectionValuesReversed(): boolean {\n    const start = this.selectionStart;\n    const end = this.selectionEnd;\n    if (!start || !end) {\n      return false;\n    }\n    return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]);\n  }\n\n  /**\n   * Handle the buffer being trimmed, adjust the selection position.\n   * @param amount The amount the buffer is being trimmed.\n   * @return Whether a refresh is necessary.\n   */\n  public onTrim(amount: number): boolean {\n    // Adjust the selection position based on the trimmed amount.\n    if (this.selectionStart) {\n      this.selectionStart[1] -= amount;\n    }\n    if (this.selectionEnd) {\n      this.selectionEnd[1] -= amount;\n    }\n\n    // The selection has moved off the buffer, clear it.\n    if (this.selectionEnd && this.selectionEnd[1] < 0) {\n      this.clearSelection();\n      return true;\n    }\n\n    // If the selection start is trimmed, ensure the start column is 0.\n    if (this.selectionStart && this.selectionStart[1] < 0) {\n      this.selectionStart[1] = 0;\n    }\n    return false;\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { C0 } from 'common/data/EscapeSequences';\nimport { IBufferService } from 'common/services/Services';\n\nconst enum Direction {\n  UP = 'A',\n  DOWN = 'B',\n  RIGHT = 'C',\n  LEFT = 'D'\n}\n\n/**\n * Concatenates all the arrow sequences together.\n * Resets the starting row to an unwrapped row, moves to the requested row,\n * then moves to requested col.\n */\nexport function moveToCellSequence(targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  const startX = bufferService.buffer.x;\n  const startY = bufferService.buffer.y;\n\n  // The alt buffer should try to navigate between rows\n  if (!bufferService.buffer.hasScrollback) {\n    return resetStartingRow(startX, startY, targetX, targetY, bufferService, applicationCursor) +\n      moveToRequestedRow(startY, targetY, bufferService, applicationCursor) +\n      moveToRequestedCol(startX, startY, targetX, targetY, bufferService, applicationCursor);\n  }\n\n  // Only move horizontally for the normal buffer\n  return moveHorizontallyOnly(startX, startY, targetX, targetY, bufferService, applicationCursor);\n}\n\n/**\n * If the initial position of the cursor is on a row that is wrapped, move the\n * cursor up to the first row that is not wrapped to have accurate vertical\n * positioning.\n */\nfunction resetStartingRow(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length === 0) {\n    return '';\n  }\n  return repeat(bufferLine(\n    startX, startY, startX,\n    startY - wrappedRowsForRow(bufferService, startY), false, bufferService\n  ).length, sequence(Direction.LEFT, applicationCursor));\n}\n\n/**\n * Using the reset starting and ending row, move to the requested row,\n * ignoring wrapped rows\n */\nfunction moveToRequestedRow(startY: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  const startRow = startY - wrappedRowsForRow(bufferService, startY);\n  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);\n\n  const rowsToMove = Math.abs(startRow - endRow) - wrappedRowsCount(startY, targetY, bufferService);\n\n  return repeat(rowsToMove, sequence(verticalDirection(startY, targetY), applicationCursor));\n}\n\n/**\n * Move to the requested col on the ending row\n */\nfunction moveToRequestedCol(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  let startRow;\n  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length > 0) {\n    startRow = targetY - wrappedRowsForRow(bufferService, targetY);\n  } else {\n    startRow = startY;\n  }\n\n  const endRow = targetY;\n  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);\n\n  return repeat(bufferLine(\n    startX, startRow, targetX, endRow,\n    direction === Direction.RIGHT, bufferService\n  ).length, sequence(direction, applicationCursor));\n}\n\nfunction moveHorizontallyOnly(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);\n  return repeat(Math.abs(startX - targetX), sequence(direction, applicationCursor));\n}\n\n/**\n * Utility functions\n */\n\n/**\n * Calculates the number of wrapped rows between the unwrapped starting and\n * ending rows. These rows need to ignored since the cursor skips over them.\n */\nfunction wrappedRowsCount(startY: number, targetY: number, bufferService: IBufferService): number {\n  let wrappedRows = 0;\n  const startRow = startY - wrappedRowsForRow(bufferService, startY);\n  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);\n\n  for (let i = 0; i < Math.abs(startRow - endRow); i++) {\n    const direction = verticalDirection(startY, targetY) === Direction.UP ? -1 : 1;\n    const line = bufferService.buffer.lines.get(startRow + (direction * i));\n    if (line && line.isWrapped) {\n      wrappedRows++;\n    }\n  }\n\n  return wrappedRows;\n}\n\n/**\n * Calculates the number of wrapped rows that make up a given row.\n * @param currentRow The row to determine how many wrapped rows make it up\n */\nfunction wrappedRowsForRow(bufferService: IBufferService, currentRow: number): number {\n  let rowCount = 0;\n  let line = bufferService.buffer.lines.get(currentRow);\n  let lineWraps = line && line.isWrapped;\n\n  while (lineWraps && currentRow >= 0 && currentRow < bufferService.rows) {\n    rowCount++;\n    line = bufferService.buffer.lines.get(--currentRow);\n    lineWraps = line && line.isWrapped;\n  }\n\n  return rowCount;\n}\n\n/**\n * Direction determiners\n */\n\n/**\n * Determines if the right or left arrow is needed\n */\nfunction horizontalDirection(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): Direction {\n  let startRow;\n  if (moveToRequestedRow(targetX, targetY, bufferService, applicationCursor).length > 0) {\n    startRow = targetY - wrappedRowsForRow(bufferService, targetY);\n  } else {\n    startRow = startY;\n  }\n\n  if ((startX < targetX &&\n    startRow <= targetY) || // down/right or same y/right\n    (startX >= targetX &&\n    startRow < targetY)) {  // down/left or same y/left\n    return Direction.RIGHT;\n  }\n  return Direction.LEFT;\n}\n\n/**\n * Determines if the up or down arrow is needed\n */\nfunction verticalDirection(startY: number, targetY: number): Direction {\n  return startY > targetY ? Direction.UP : Direction.DOWN;\n}\n\n/**\n * Constructs the string of chars in the buffer from a starting row and col\n * to an ending row and col\n * @param startCol The starting column position\n * @param startRow The starting row position\n * @param endCol The ending column position\n * @param endRow The ending row position\n * @param forward Direction to move\n */\nfunction bufferLine(\n  startCol: number,\n  startRow: number,\n  endCol: number,\n  endRow: number,\n  forward: boolean,\n  bufferService: IBufferService\n): string {\n  let currentCol = startCol;\n  let currentRow = startRow;\n  let bufferStr = '';\n\n  while (currentCol !== endCol || currentRow !== endRow) {\n    currentCol += forward ? 1 : -1;\n\n    if (forward && currentCol > bufferService.cols - 1) {\n      bufferStr += bufferService.buffer.translateBufferLineToString(\n        currentRow, false, startCol, currentCol\n      );\n      currentCol = 0;\n      startCol = 0;\n      currentRow++;\n    } else if (!forward && currentCol < 0) {\n      bufferStr += bufferService.buffer.translateBufferLineToString(\n        currentRow, false, 0, startCol + 1\n      );\n      currentCol = bufferService.cols - 1;\n      startCol = currentCol;\n      currentRow--;\n    }\n  }\n\n  return bufferStr + bufferService.buffer.translateBufferLineToString(\n    currentRow, false, startCol, currentCol\n  );\n}\n\n/**\n * Constructs the escape sequence for clicking an arrow\n * @param direction The direction to move\n */\nfunction sequence(direction: Direction, applicationCursor: boolean): string {\n  const mod =  applicationCursor ? 'O' : '[';\n  return C0.ESC + mod + direction;\n}\n\n/**\n * Returns a string repeated a given number of times\n * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\n * @param count The number of times to repeat the string\n * @param string The string that is to be repeated\n */\nfunction repeat(count: number, str: string): string {\n  count = Math.floor(count);\n  let rpt = '';\n  for (let i = 0; i < count; i++) {\n    rpt += str;\n  }\n  return rpt;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService } from 'common/services/Services';\nimport { ISoundService } from 'browser/services/Services';\n\nexport class SoundService implements ISoundService {\n  serviceBrand: any;\n\n  private static _audioContext: AudioContext;\n\n  static get audioContext(): AudioContext | null {\n    if (!SoundService._audioContext) {\n      const audioContextCtor: typeof AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;\n      if (!audioContextCtor) {\n        console.warn('Web Audio API is not supported by this browser. Consider upgrading to the latest version');\n        return null;\n      }\n      SoundService._audioContext = new audioContextCtor();\n    }\n    return SoundService._audioContext;\n  }\n\n  constructor(\n    @IOptionsService private _optionsService: IOptionsService\n  ) {\n  }\n\n  public playBellSound(): void {\n    const ctx = SoundService.audioContext;\n    if (!ctx) {\n      return;\n    }\n    const bellAudioSource = ctx.createBufferSource();\n    ctx.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)), (buffer) => {\n      bellAudioSource.buffer = buffer;\n      bellAudioSource.connect(ctx.destination);\n      bellAudioSource.start(0);\n    });\n  }\n\n  private _base64ToArrayBuffer(base64: string): ArrayBuffer {\n    const binaryString = window.atob(base64);\n    const len = binaryString.length;\n    const bytes = new Uint8Array(len);\n\n    for (let i = 0; i < len; i++) {\n      bytes[i] = binaryString.charCodeAt(i);\n    }\n\n    return bytes.buffer;\n  }\n\n  private _removeMimeType(dataURI: string): string {\n    // Split the input to get the mime-type and the data itself\n    const splitUri = dataURI.split(',');\n\n    // Return only the data\n    return splitUri[1];\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'common/Lifecycle';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { IMouseService, ISelectionService } from 'browser/services/Services';\nimport { IMouseZoneManager, IMouseZone } from 'browser/Types';\nimport { IBufferService } from 'common/services/Services';\n\nconst HOVER_DURATION = 500;\n\n/**\n * The MouseZoneManager allows components to register zones within the terminal\n * that trigger hover and click callbacks.\n *\n * This class was intentionally made not so robust initially as the only case it\n * needed to support was single-line links which never overlap. Improvements can\n * be made in the future.\n */\nexport class MouseZoneManager extends Disposable implements IMouseZoneManager {\n  private _zones: IMouseZone[] = [];\n\n  private _areZonesActive: boolean = false;\n  private _mouseMoveListener: (e: MouseEvent) => any;\n  private _mouseLeaveListener: (e: MouseEvent) => any;\n  private _clickListener: (e: MouseEvent) => any;\n\n  private _tooltipTimeout: number | undefined;\n  private _currentZone: IMouseZone | undefined;\n  private _lastHoverCoords: [number | undefined, number | undefined] = [undefined, undefined];\n  private _initialSelectionLength: number = 0;\n\n  constructor(\n    private readonly _element: HTMLElement,\n    private readonly _screenElement: HTMLElement,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @IMouseService private readonly _mouseService: IMouseService,\n    @ISelectionService private readonly _selectionService: ISelectionService\n  ) {\n    super();\n\n    this.register(addDisposableDomListener(this._element, 'mousedown', e => this._onMouseDown(e)));\n\n    // These events are expensive, only listen to it when mouse zones are active\n    this._mouseMoveListener = e => this._onMouseMove(e);\n    this._mouseLeaveListener = e => this._onMouseLeave(e);\n    this._clickListener = e => this._onClick(e);\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this._deactivate();\n  }\n\n  public add(zone: IMouseZone): void {\n    this._zones.push(zone);\n    if (this._zones.length === 1) {\n      this._activate();\n    }\n  }\n\n  public clearAll(start?: number, end?: number): void {\n    // Exit if there's nothing to clear\n    if (this._zones.length === 0) {\n      return;\n    }\n\n    // Clear all if start/end weren't set\n    if (!start || !end) {\n      start = 0;\n      end = this._bufferService.rows - 1;\n    }\n\n    // Iterate through zones and clear them out if they're within the range\n    for (let i = 0; i < this._zones.length; i++) {\n      const zone = this._zones[i];\n      if ((zone.y1 > start && zone.y1 <= end + 1) ||\n          (zone.y2 > start && zone.y2 <= end + 1) ||\n          (zone.y1 < start && zone.y2 > end + 1)) {\n        if (this._currentZone && this._currentZone === zone) {\n          this._currentZone.leaveCallback();\n          this._currentZone = undefined;\n        }\n        this._zones.splice(i--, 1);\n      }\n    }\n\n    // Deactivate the mouse zone manager if all the zones have been removed\n    if (this._zones.length === 0) {\n      this._deactivate();\n    }\n  }\n\n  private _activate(): void {\n    if (!this._areZonesActive) {\n      this._areZonesActive = true;\n      this._element.addEventListener('mousemove', this._mouseMoveListener);\n      this._element.addEventListener('mouseleave', this._mouseLeaveListener);\n      this._element.addEventListener('click', this._clickListener);\n    }\n  }\n\n  private _deactivate(): void {\n    if (this._areZonesActive) {\n      this._areZonesActive = false;\n      this._element.removeEventListener('mousemove', this._mouseMoveListener);\n      this._element.removeEventListener('mouseleave', this._mouseLeaveListener);\n      this._element.removeEventListener('click', this._clickListener);\n    }\n  }\n\n  private _onMouseMove(e: MouseEvent): void {\n    // TODO: Ideally this would only clear the hover state when the mouse moves\n    // outside of the mouse zone\n    if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) {\n      this._onHover(e);\n      // Record the current coordinates\n      this._lastHoverCoords = [e.pageX, e.pageY];\n    }\n  }\n\n  private _onHover(e: MouseEvent): void {\n    const zone = this._findZoneEventAt(e);\n\n    // Do nothing if the zone is the same\n    if (zone === this._currentZone) {\n      return;\n    }\n\n    // Fire the hover end callback and cancel any existing timer if a new zone\n    // is being hovered\n    if (this._currentZone) {\n      this._currentZone.leaveCallback();\n      this._currentZone = undefined;\n      if (this._tooltipTimeout) {\n        clearTimeout(this._tooltipTimeout);\n      }\n    }\n\n    // Exit if there is not zone\n    if (!zone) {\n      return;\n    }\n    this._currentZone = zone;\n\n    // Trigger the hover callback\n    if (zone.hoverCallback) {\n      zone.hoverCallback(e);\n    }\n\n    // Restart the tooltip timeout\n    this._tooltipTimeout = <number><any>setTimeout(() => this._onTooltip(e), HOVER_DURATION);\n  }\n\n  private _onTooltip(e: MouseEvent): void {\n    this._tooltipTimeout = undefined;\n    const zone = this._findZoneEventAt(e);\n    if (zone && zone.tooltipCallback) {\n      zone.tooltipCallback(e);\n    }\n  }\n\n  private _onMouseDown(e: MouseEvent): void {\n    // Store current terminal selection length, to check if we're performing\n    // a selection operation\n    this._initialSelectionLength = this._getSelectionLength();\n\n    // Ignore the event if there are no zones active\n    if (!this._areZonesActive) {\n      return;\n    }\n\n    // Find the active zone, prevent event propagation if found to prevent other\n    // components from handling the mouse event.\n    const zone = this._findZoneEventAt(e);\n    if (zone) {\n      if (zone.willLinkActivate(e)) {\n        e.preventDefault();\n        e.stopImmediatePropagation();\n      }\n    }\n  }\n\n  private _onMouseLeave(e: MouseEvent): void {\n    // Fire the hover end callback and cancel any existing timer if the mouse\n    // leaves the terminal element\n    if (this._currentZone) {\n      this._currentZone.leaveCallback();\n      this._currentZone = undefined;\n      if (this._tooltipTimeout) {\n        clearTimeout(this._tooltipTimeout);\n      }\n    }\n  }\n\n  private _onClick(e: MouseEvent): void {\n    // Find the active zone and click it if found and no selection was\n    // being performed\n    const zone = this._findZoneEventAt(e);\n    const currentSelectionLength = this._getSelectionLength();\n\n    if (zone && currentSelectionLength === this._initialSelectionLength) {\n      zone.clickCallback(e);\n      e.preventDefault();\n      e.stopImmediatePropagation();\n    }\n  }\n\n  private _getSelectionLength(): number {\n    const selectionText = this._selectionService.selectionText;\n    return selectionText ? selectionText.length : 0;\n  }\n\n  private _findZoneEventAt(e: MouseEvent): IMouseZone | undefined {\n    const coords = this._mouseService.getCoords(e, this._screenElement, this._bufferService.cols, this._bufferService.rows);\n    if (!coords) {\n      return undefined;\n    }\n    const x = coords[0];\n    const y = coords[1];\n    for (let i = 0; i < this._zones.length; i++) {\n      const zone = this._zones[i];\n      if (zone.y1 === zone.y2) {\n        // Single line link\n        if (y === zone.y1 && x >= zone.x1 && x < zone.x2) {\n          return zone;\n        }\n      } else {\n        // Multi-line link\n        if ((y === zone.y1 && x >= zone.x1) ||\n            (y === zone.y2 && x < zone.x2) ||\n            (y > zone.y1 && y < zone.y2)) {\n          return zone;\n        }\n      }\n    }\n    return undefined;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport * as Strings from './browser/LocalizableStrings';\nimport { ITerminal } from './Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { isMac } from 'common/Platform';\nimport { RenderDebouncer } from 'browser/RenderDebouncer';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { Disposable } from 'common/Lifecycle';\nimport { ScreenDprMonitor } from 'browser/ScreenDprMonitor';\nimport { IRenderService } from 'browser/services/Services';\n\nconst MAX_ROWS_TO_READ = 20;\n\nconst enum BoundaryPosition {\n  TOP,\n  BOTTOM\n}\n\nexport class AccessibilityManager extends Disposable {\n  private _accessibilityTreeRoot: HTMLElement;\n  private _rowContainer: HTMLElement;\n  private _rowElements: HTMLElement[];\n  private _liveRegion: HTMLElement;\n  private _liveRegionLineCount: number = 0;\n\n  private _renderRowsDebouncer: RenderDebouncer;\n  private _screenDprMonitor: ScreenDprMonitor;\n\n  private _topBoundaryFocusListener: (e: FocusEvent) => void;\n  private _bottomBoundaryFocusListener: (e: FocusEvent) => void;\n\n  /**\n   * This queue has a character pushed to it for keys that are pressed, if the\n   * next character added to the terminal is equal to the key char then it is\n   * not announced (added to live region) because it has already been announced\n   * by the textarea event (which cannot be canceled). There are some race\n   * condition cases if there is typing while data is streaming, but this covers\n   * the main case of typing into the prompt and inputting the answer to a\n   * question (Y/N, etc.).\n   */\n  private _charsToConsume: string[] = [];\n\n  private _charsToAnnounce: string = '';\n\n  constructor(\n    private readonly _terminal: ITerminal,\n    private readonly _renderService: IRenderService\n  ) {\n    super();\n    this._accessibilityTreeRoot = document.createElement('div');\n    this._accessibilityTreeRoot.classList.add('xterm-accessibility');\n\n    this._rowContainer = document.createElement('div');\n    this._rowContainer.classList.add('xterm-accessibility-tree');\n    this._rowElements = [];\n    for (let i = 0; i < this._terminal.rows; i++) {\n      this._rowElements[i] = this._createAccessibilityTreeNode();\n      this._rowContainer.appendChild(this._rowElements[i]);\n    }\n\n    this._topBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.TOP);\n    this._bottomBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.BOTTOM);\n    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n    this._refreshRowsDimensions();\n    this._accessibilityTreeRoot.appendChild(this._rowContainer);\n\n    this._renderRowsDebouncer = new RenderDebouncer(this._renderRows.bind(this));\n    this._refreshRows();\n\n    this._liveRegion = document.createElement('div');\n    this._liveRegion.classList.add('live-region');\n    this._liveRegion.setAttribute('aria-live', 'assertive');\n    this._accessibilityTreeRoot.appendChild(this._liveRegion);\n\n    this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityTreeRoot);\n\n    this.register(this._renderRowsDebouncer);\n    this.register(this._terminal.onResize(e => this._onResize(e.rows)));\n    this.register(this._terminal.onRender(e => this._refreshRows(e.start, e.end)));\n    this.register(this._terminal.onScroll(() => this._refreshRows()));\n    // Line feed is an issue as the prompt won't be read out after a command is run\n    this.register(this._terminal.onA11yChar(char => this._onChar(char)));\n    this.register(this._terminal.onLineFeed(() => this._onChar('\\n')));\n    this.register(this._terminal.onA11yTab(spaceCount => this._onTab(spaceCount)));\n    this.register(this._terminal.onKey(e => this._onKey(e.key)));\n    this.register(this._terminal.onBlur(() => this._clearLiveRegion()));\n    this.register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions()));\n\n    this._screenDprMonitor = new ScreenDprMonitor();\n    this.register(this._screenDprMonitor);\n    this._screenDprMonitor.setListener(() => this._refreshRowsDimensions());\n    // This shouldn't be needed on modern browsers but is present in case the\n    // media query that drives the ScreenDprMonitor isn't supported\n    this.register(addDisposableDomListener(window, 'resize', () => this._refreshRowsDimensions()));\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this._terminal.element.removeChild(this._accessibilityTreeRoot);\n    this._rowElements.length = 0;\n  }\n\n  private _onBoundaryFocus(e: FocusEvent, position: BoundaryPosition): void {\n    const boundaryElement = <HTMLElement>e.target;\n    const beforeBoundaryElement = this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2];\n\n    // Don't scroll if the buffer top has reached the end in that direction\n    const posInSet = boundaryElement.getAttribute('aria-posinset');\n    const lastRowPos = position === BoundaryPosition.TOP ? '1' : `${this._terminal.buffer.lines.length}`;\n    if (posInSet === lastRowPos) {\n      return;\n    }\n\n    // Don't scroll when the last focused item was not the second row (focus is going the other\n    // direction)\n    if (e.relatedTarget !== beforeBoundaryElement) {\n      return;\n    }\n\n    // Remove old boundary element from array\n    let topBoundaryElement: HTMLElement;\n    let bottomBoundaryElement: HTMLElement;\n    if (position === BoundaryPosition.TOP) {\n      topBoundaryElement = boundaryElement;\n      bottomBoundaryElement = this._rowElements.pop()!;\n      this._rowContainer.removeChild(bottomBoundaryElement);\n    } else {\n      topBoundaryElement = this._rowElements.shift()!;\n      bottomBoundaryElement = boundaryElement;\n      this._rowContainer.removeChild(topBoundaryElement);\n    }\n\n    // Remove listeners from old boundary elements\n    topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener);\n    bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n    // Add new element to array/DOM\n    if (position === BoundaryPosition.TOP) {\n      const newElement = this._createAccessibilityTreeNode();\n      this._rowElements.unshift(newElement);\n      this._rowContainer.insertAdjacentElement('afterbegin', newElement);\n    } else {\n      const newElement = this._createAccessibilityTreeNode();\n      this._rowElements.push(newElement);\n      this._rowContainer.appendChild(newElement);\n    }\n\n    // Add listeners to new boundary elements\n    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n    // Scroll up\n    this._terminal.scrollLines(position === BoundaryPosition.TOP ? -1 : 1);\n\n    // Focus new boundary before element\n    this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2].focus();\n\n    // Prevent the standard behavior\n    e.preventDefault();\n    e.stopImmediatePropagation();\n  }\n\n  private _onResize(rows: number): void {\n    // Remove bottom boundary listener\n    this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n    // Grow rows as required\n    for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) {\n      this._rowElements[i] = this._createAccessibilityTreeNode();\n      this._rowContainer.appendChild(this._rowElements[i]);\n    }\n    // Shrink rows as required\n    while (this._rowElements.length > rows) {\n      this._rowContainer.removeChild(this._rowElements.pop()!);\n    }\n\n    // Add bottom boundary listener\n    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n    this._refreshRowsDimensions();\n  }\n\n  private _createAccessibilityTreeNode(): HTMLElement {\n    const element = document.createElement('div');\n    element.setAttribute('role', 'listitem');\n    element.tabIndex = -1;\n    this._refreshRowDimensions(element);\n    return element;\n  }\n\n  private _onTab(spaceCount: number): void {\n    for (let i = 0; i < spaceCount; i++) {\n      this._onChar(' ');\n    }\n  }\n\n  private _onChar(char: string): void {\n    if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) {\n      if (this._charsToConsume.length > 0) {\n        // Have the screen reader ignore the char if it was just input\n        const shiftedChar = this._charsToConsume.shift();\n        if (shiftedChar !== char) {\n          this._charsToAnnounce += char;\n        }\n      } else {\n        this._charsToAnnounce += char;\n      }\n\n      if (char === '\\n') {\n        this._liveRegionLineCount++;\n        if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) {\n          this._liveRegion.textContent += Strings.tooMuchOutput;\n        }\n      }\n\n      // Only detach/attach on mac as otherwise messages can go unaccounced\n      if (isMac) {\n        if (this._liveRegion.textContent && this._liveRegion.textContent.length > 0 && !this._liveRegion.parentNode) {\n          setTimeout(() => {\n            this._accessibilityTreeRoot.appendChild(this._liveRegion);\n          }, 0);\n        }\n      }\n    }\n  }\n\n  private _clearLiveRegion(): void {\n    this._liveRegion.textContent = '';\n    this._liveRegionLineCount = 0;\n\n    // Only detach/attach on mac as otherwise messages can go unaccounced\n    if (isMac) {\n      if (this._liveRegion.parentNode) {\n        this._accessibilityTreeRoot.removeChild(this._liveRegion);\n      }\n    }\n  }\n\n  private _onKey(keyChar: string): void {\n    this._clearLiveRegion();\n    this._charsToConsume.push(keyChar);\n  }\n\n  private _refreshRows(start?: number, end?: number): void {\n    this._renderRowsDebouncer.refresh(start, end, this._terminal.rows);\n  }\n\n  private _renderRows(start: number, end: number): void {\n    const buffer: IBuffer = this._terminal.buffer;\n    const setSize = buffer.lines.length.toString();\n    for (let i = start; i <= end; i++) {\n      const lineData = buffer.translateBufferLineToString(buffer.ydisp + i, true);\n      const posInSet = (buffer.ydisp + i + 1).toString();\n      const element = this._rowElements[i];\n      if (element) {\n        if (lineData.length === 0) {\n          element.innerHTML = '&nbsp;';\n        } else {\n          element.textContent = lineData;\n        }\n        element.setAttribute('aria-posinset', posInSet);\n        element.setAttribute('aria-setsize', setSize);\n      }\n    }\n    this._announceCharacters();\n  }\n\n  private _refreshRowsDimensions(): void {\n    if (!this._renderService.dimensions.actualCellHeight) {\n      return;\n    }\n    if (this._rowElements.length !== this._terminal.rows) {\n      this._onResize(this._terminal.rows);\n    }\n    for (let i = 0; i < this._terminal.rows; i++) {\n      this._refreshRowDimensions(this._rowElements[i]);\n    }\n  }\n\n  private _refreshRowDimensions(element: HTMLElement): void {\n    element.style.height = `${this._renderService.dimensions.actualCellHeight}px`;\n  }\n\n  private _announceCharacters(): void {\n    if (this._charsToAnnounce.length === 0) {\n      return;\n    }\n    this._liveRegion.textContent += this._charsToAnnounce;\n    this._charsToAnnounce = '';\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { ITerminal } from '../../Types';\nimport { BOLD_CLASS, ITALIC_CLASS, CURSOR_CLASS, CURSOR_STYLE_BLOCK_CLASS, CURSOR_BLINK_CLASS, CURSOR_STYLE_BAR_CLASS, CURSOR_STYLE_UNDERLINE_CLASS, DomRendererRowFactory } from 'browser/renderer/dom/DomRendererRowFactory';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { Disposable } from 'common/Lifecycle';\nimport { IColorSet, ILinkifierEvent } from 'browser/Types';\nimport { ICharSizeService } from 'browser/services/Services';\nimport { IOptionsService } from 'common/services/Services';\n\nconst TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-';\nconst ROW_CONTAINER_CLASS = 'xterm-rows';\nconst FG_CLASS_PREFIX = 'xterm-fg-';\nconst BG_CLASS_PREFIX = 'xterm-bg-';\nconst FOCUS_CLASS = 'xterm-focus';\nconst SELECTION_CLASS = 'xterm-selection';\n\nlet nextTerminalId = 1;\n\n/**\n * A fallback renderer for when canvas is slow. This is not meant to be\n * particularly fast or feature complete, more just stable and usable for when\n * canvas is not an option.\n */\nexport class DomRenderer extends Disposable implements IRenderer {\n  private _rowFactory: DomRendererRowFactory;\n  private _terminalClass: number = nextTerminalId++;\n\n  private _themeStyleElement: HTMLStyleElement;\n  private _dimensionsStyleElement: HTMLStyleElement;\n  private _rowContainer: HTMLElement;\n  private _rowElements: HTMLElement[] = [];\n  private _selectionContainer: HTMLElement;\n\n  public dimensions: IRenderDimensions;\n\n  constructor(\n    private _terminal: ITerminal,\n    private _colors: IColorSet,\n    private _charSizeService: ICharSizeService,\n    private _optionsService: IOptionsService\n  ) {\n    super();\n\n    this._rowContainer = document.createElement('div');\n    this._rowContainer.classList.add(ROW_CONTAINER_CLASS);\n    this._rowContainer.style.lineHeight = 'normal';\n    this._rowContainer.setAttribute('aria-hidden', 'true');\n    this._refreshRowElements(this._terminal.cols, this._terminal.rows);\n    this._selectionContainer = document.createElement('div');\n    this._selectionContainer.classList.add(SELECTION_CLASS);\n    this._selectionContainer.setAttribute('aria-hidden', 'true');\n\n    this.dimensions = {\n      scaledCharWidth: null,\n      scaledCharHeight: null,\n      scaledCellWidth: null,\n      scaledCellHeight: null,\n      scaledCharLeft: null,\n      scaledCharTop: null,\n      scaledCanvasWidth: null,\n      scaledCanvasHeight: null,\n      canvasWidth: null,\n      canvasHeight: null,\n      actualCellWidth: null,\n      actualCellHeight: null\n    };\n    this._updateDimensions();\n    this._injectCss();\n\n    this._rowFactory = new DomRendererRowFactory(document, this._optionsService);\n\n    this._terminal.element.classList.add(TERMINAL_CLASS_PREFIX + this._terminalClass);\n    this._terminal.screenElement.appendChild(this._rowContainer);\n    this._terminal.screenElement.appendChild(this._selectionContainer);\n\n    this._terminal.linkifier.onLinkHover(e => this._onLinkHover(e));\n    this._terminal.linkifier.onLinkLeave(e => this._onLinkLeave(e));\n  }\n\n  public dispose(): void {\n    this._terminal.element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass);\n    this._terminal.screenElement.removeChild(this._rowContainer);\n    this._terminal.screenElement.removeChild(this._selectionContainer);\n    this._terminal.screenElement.removeChild(this._themeStyleElement);\n    this._terminal.screenElement.removeChild(this._dimensionsStyleElement);\n    super.dispose();\n  }\n\n  private _updateDimensions(): void {\n    this.dimensions.scaledCharWidth = this._charSizeService.width * window.devicePixelRatio;\n    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);\n    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);\n    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);\n    this.dimensions.scaledCharLeft = 0;\n    this.dimensions.scaledCharTop = 0;\n    this.dimensions.scaledCanvasWidth = this.dimensions.scaledCellWidth * this._terminal.cols;\n    this.dimensions.scaledCanvasHeight = this.dimensions.scaledCellHeight * this._terminal.rows;\n    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);\n    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);\n    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;\n    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;\n\n    this._rowElements.forEach(element => {\n      element.style.width = `${this.dimensions.canvasWidth}px`;\n      element.style.height = `${this.dimensions.actualCellHeight}px`;\n      element.style.lineHeight = `${this.dimensions.actualCellHeight}px`;\n      // Make sure rows don't overflow onto following row\n      element.style.overflow = 'hidden';\n    });\n\n    if (!this._dimensionsStyleElement) {\n      this._dimensionsStyleElement = document.createElement('style');\n      this._terminal.screenElement.appendChild(this._dimensionsStyleElement);\n    }\n\n    const styles =\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} span {` +\n        ` display: inline-block;` +\n        ` height: 100%;` +\n        ` vertical-align: top;` +\n        ` width: ${this.dimensions.actualCellWidth}px` +\n        `}`;\n\n    this._dimensionsStyleElement.innerHTML = styles;\n\n    this._selectionContainer.style.height = (<any>this._terminal)._viewportElement.style.height;\n    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;\n    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;\n  }\n\n  public setColors(colors: IColorSet): void {\n    this._colors = colors;\n    this._injectCss();\n  }\n\n  private _injectCss(): void {\n    if (!this._themeStyleElement) {\n      this._themeStyleElement = document.createElement('style');\n      this._terminal.screenElement.appendChild(this._themeStyleElement);\n    }\n\n    // Base CSS\n    let styles =\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} {` +\n        ` color: ${this._colors.foreground.css};` +\n        ` background-color: ${this._colors.background.css};` +\n        ` font-family: ${this._terminal.options.fontFamily};` +\n        ` font-size: ${this._terminal.options.fontSize}px;` +\n        `}`;\n    // Text styles\n    styles +=\n        `${this._terminalSelector} span:not(.${BOLD_CLASS}) {` +\n        ` font-weight: ${this._terminal.options.fontWeight};` +\n        `}` +\n        `${this._terminalSelector} span.${BOLD_CLASS} {` +\n        ` font-weight: ${this._terminal.options.fontWeightBold};` +\n        `}` +\n        `${this._terminalSelector} span.${ITALIC_CLASS} {` +\n        ` font-style: italic;` +\n        `}`;\n    // Blink animation\n    styles +=\n        `@keyframes blink_box_shadow {` +\n        ` 50% {` +\n        `  box-shadow: none;` +\n        ` }` +\n        `}`;\n    styles +=\n        `@keyframes blink_block {` +\n        ` 0% {` +\n        `  background-color: ${this._colors.cursor.css};` +\n        `  color: ${this._colors.cursorAccent.css};` +\n        ` }` +\n        ` 50% {` +\n        `  background-color: ${this._colors.cursorAccent.css};` +\n        `  color: ${this._colors.cursor.css};` +\n        ` }` +\n        `}`;\n    // Cursor\n    styles +=\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}:not(.${FOCUS_CLASS}) .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +\n        ` outline: 1px solid ${this._colors.cursor.css};` +\n        ` outline-offset: -1px;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}:not(.${CURSOR_STYLE_BLOCK_CLASS}) {` +\n        ` animation: blink_box_shadow 1s step-end infinite;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +\n        ` animation: blink_block 1s step-end infinite;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +\n        ` background-color: ${this._colors.cursor.css};` +\n        ` color: ${this._colors.cursorAccent.css};` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BAR_CLASS} {` +\n        ` box-shadow: 1px 0 0 ${this._colors.cursor.css} inset;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_UNDERLINE_CLASS} {` +\n        ` box-shadow: 0 -1px 0 ${this._colors.cursor.css} inset;` +\n        `}`;\n    // Selection\n    styles +=\n        `${this._terminalSelector} .${SELECTION_CLASS} {` +\n        ` position: absolute;` +\n        ` top: 0;` +\n        ` left: 0;` +\n        ` z-index: 1;` +\n        ` pointer-events: none;` +\n        `}` +\n        `${this._terminalSelector} .${SELECTION_CLASS} div {` +\n        ` position: absolute;` +\n        ` background-color: ${this._colors.selection.css};` +\n        `}`;\n    // Colors\n    this._colors.ansi.forEach((c, i) => {\n      styles +=\n          `${this._terminalSelector} .${FG_CLASS_PREFIX}${i} { color: ${c.css}; }` +\n          `${this._terminalSelector} .${BG_CLASS_PREFIX}${i} { background-color: ${c.css}; }`;\n    });\n    styles +=\n        `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { color: ${this._colors.background.css}; }` +\n        `${this._terminalSelector} .${BG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { background-color: ${this._colors.foreground.css}; }`;\n\n    this._themeStyleElement.innerHTML = styles;\n  }\n\n  public onDevicePixelRatioChange(): void {\n    this._updateDimensions();\n  }\n\n  private _refreshRowElements(cols: number, rows: number): void {\n    // Add missing elements\n    for (let i = this._rowElements.length; i <= rows; i++) {\n      const row = document.createElement('div');\n      this._rowContainer.appendChild(row);\n      this._rowElements.push(row);\n    }\n    // Remove excess elements\n    while (this._rowElements.length > rows) {\n      this._rowContainer.removeChild(this._rowElements.pop());\n    }\n  }\n\n  public onResize(cols: number, rows: number): void {\n    this._refreshRowElements(cols, rows);\n    this._updateDimensions();\n  }\n\n  public onCharSizeChanged(): void {\n    this._updateDimensions();\n  }\n\n  public onBlur(): void {\n    this._rowContainer.classList.remove(FOCUS_CLASS);\n  }\n\n  public onFocus(): void {\n    this._rowContainer.classList.add(FOCUS_CLASS);\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {\n    // Remove all selections\n    while (this._selectionContainer.children.length) {\n      this._selectionContainer.removeChild(this._selectionContainer.children[0]);\n    }\n\n    // Selection does not exist\n    if (!start || !end) {\n      return;\n    }\n\n    // Translate from buffer position to viewport position\n    const viewportStartRow = start[1] - this._terminal.buffer.ydisp;\n    const viewportEndRow = end[1] - this._terminal.buffer.ydisp;\n    const viewportCappedStartRow = Math.max(viewportStartRow, 0);\n    const viewportCappedEndRow = Math.min(viewportEndRow, this._terminal.rows - 1);\n\n    // No need to draw the selection\n    if (viewportCappedStartRow >= this._terminal.rows || viewportCappedEndRow < 0) {\n      return;\n    }\n\n    // Create the selections\n    const documentFragment = document.createDocumentFragment();\n\n    if (columnSelectMode) {\n      documentFragment.appendChild(\n        this._createSelectionElement(viewportCappedStartRow, start[0], end[0], viewportCappedEndRow - viewportCappedStartRow + 1)\n      );\n    } else {\n      // Draw first row\n      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;\n      const endCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._terminal.cols;\n      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol));\n      // Draw middle rows\n      const middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1;\n      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._terminal.cols, middleRowsCount));\n      // Draw final row\n      if (viewportCappedStartRow !== viewportCappedEndRow) {\n        // Only draw viewportEndRow if it's not the same as viewporttartRow\n        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._terminal.cols;\n        documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol));\n      }\n    }\n    this._selectionContainer.appendChild(documentFragment);\n  }\n\n  /**\n   * Creates a selection element at the specified position.\n   * @param row The row of the selection.\n   * @param colStart The start column.\n   * @param colEnd The end columns.\n   */\n  private _createSelectionElement(row: number, colStart: number, colEnd: number, rowCount: number = 1): HTMLElement {\n    const element = document.createElement('div');\n    element.style.height = `${rowCount * this.dimensions.actualCellHeight}px`;\n    element.style.top = `${row * this.dimensions.actualCellHeight}px`;\n    element.style.left = `${colStart * this.dimensions.actualCellWidth}px`;\n    element.style.width = `${this.dimensions.actualCellWidth * (colEnd - colStart)}px`;\n    return element;\n  }\n\n  public onCursorMove(): void {\n    // No-op, the cursor is drawn when rows are drawn\n  }\n\n  public onOptionsChanged(): void {\n    // Force a refresh\n    this._updateDimensions();\n    this._injectCss();\n    this._terminal.refresh(0, this._terminal.rows - 1);\n  }\n\n  public clear(): void {\n    this._rowElements.forEach(e => e.innerHTML = '');\n  }\n\n  public renderRows(start: number, end: number): void {\n    const terminal = this._terminal;\n\n    const cursorAbsoluteY = terminal.buffer.ybase + terminal.buffer.y;\n    const cursorX = this._terminal.buffer.x;\n    const cursorBlink = this._terminal.options.cursorBlink;\n\n    for (let y = start; y <= end; y++) {\n      const rowElement = this._rowElements[y];\n      rowElement.innerHTML = '';\n\n      const row = y + terminal.buffer.ydisp;\n      const lineData = terminal.buffer.lines.get(row);\n      const cursorStyle = terminal.options.cursorStyle;\n      rowElement.appendChild(this._rowFactory.createRow(lineData, row === cursorAbsoluteY, cursorStyle, cursorX, cursorBlink, this.dimensions.actualCellWidth, terminal.cols));\n    }\n  }\n\n  private get _terminalSelector(): string {\n    return `.${TERMINAL_CLASS_PREFIX}${this._terminalClass}`;\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number { return -1; }\n  public deregisterCharacterJoiner(joinerId: number): boolean { return false; }\n\n  private _onLinkHover(e: ILinkifierEvent): void {\n    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true);\n  }\n\n  private _onLinkLeave(e: ILinkifierEvent): void {\n    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false);\n  }\n\n  private _setCellUnderline(x: number, x2: number, y: number, y2: number, cols: number, enabled: boolean): void {\n    while (x !== x2 || y !== y2) {\n      const row = this._rowElements[y];\n      if (!row) {\n        return;\n      }\n      const span = <HTMLElement>row.children[x];\n      if (span) {\n        span.style.textDecoration = enabled ? 'underline' : 'none';\n      }\n      if (++x >= cols) {\n        x = 0;\n        y++;\n      }\n    }\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine } from 'common/Types';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { NULL_CELL_CODE, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { IOptionsService } from 'common/services/Services';\n\nexport const BOLD_CLASS = 'xterm-bold';\nexport const DIM_CLASS = 'xterm-dim';\nexport const ITALIC_CLASS = 'xterm-italic';\nexport const UNDERLINE_CLASS = 'xterm-underline';\nexport const CURSOR_CLASS = 'xterm-cursor';\nexport const CURSOR_BLINK_CLASS = 'xterm-cursor-blink';\nexport const CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block';\nexport const CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar';\nexport const CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline';\n\nexport class DomRendererRowFactory {\n  private _workCell: CellData = new CellData();\n\n  constructor(\n    private _document: Document,\n    private _optionsService: IOptionsService\n  ) {\n  }\n\n  public createRow(lineData: IBufferLine, isCursorRow: boolean, cursorStyle: string | undefined, cursorX: number, cursorBlink: boolean, cellWidth: number, cols: number): DocumentFragment {\n    const fragment = this._document.createDocumentFragment();\n\n    // Find the line length first, this prevents the need to output a bunch of\n    // empty cells at the end. This cannot easily be integrated into the main\n    // loop below because of the colCount feature (which can be removed after we\n    // properly support reflow and disallow data to go beyond the right-side of\n    // the viewport).\n    let lineLength = 0;\n    for (let x = Math.min(lineData.length, cols) - 1; x >= 0; x--) {\n      if (lineData.loadCell(x, this._workCell).getCode() !== NULL_CELL_CODE || (isCursorRow && x === cursorX)) {\n        lineLength = x + 1;\n        break;\n      }\n    }\n\n    for (let x = 0; x < lineLength; x++) {\n      lineData.loadCell(x, this._workCell);\n      const width = this._workCell.getWidth();\n\n      // The character to the left is a wide character, drawing is owned by the char at x-1\n      if (width === 0) {\n        continue;\n      }\n\n      const charElement = this._document.createElement('span');\n      if (width > 1) {\n        charElement.style.width = `${cellWidth * width}px`;\n      }\n\n      if (isCursorRow && x === cursorX) {\n        charElement.classList.add(CURSOR_CLASS);\n\n        if (cursorBlink) {\n          charElement.classList.add(CURSOR_BLINK_CLASS);\n        }\n\n        switch (cursorStyle) {\n          case 'bar':\n            charElement.classList.add(CURSOR_STYLE_BAR_CLASS);\n            break;\n          case 'underline':\n            charElement.classList.add(CURSOR_STYLE_UNDERLINE_CLASS);\n            break;\n          default:\n            charElement.classList.add(CURSOR_STYLE_BLOCK_CLASS);\n            break;\n        }\n      }\n\n      if (this._workCell.isBold()) {\n        charElement.classList.add(BOLD_CLASS);\n      }\n\n      if (this._workCell.isItalic()) {\n        charElement.classList.add(ITALIC_CLASS);\n      }\n\n      if (this._workCell.isDim()) {\n        charElement.classList.add(DIM_CLASS);\n      }\n\n      if (this._workCell.isUnderline()) {\n        charElement.classList.add(UNDERLINE_CLASS);\n      }\n\n      charElement.textContent = this._workCell.getChars() || WHITESPACE_CELL_CHAR;\n\n      const swapColor = this._workCell.isInverse();\n\n      // fg\n      if (this._workCell.isFgRGB()) {\n        let style = charElement.getAttribute('style') || '';\n        style += `${swapColor ? 'background-' : ''}color:rgb(${(AttributeData.toColorRGB(this._workCell.getFgColor())).join(',')});`;\n        charElement.setAttribute('style', style);\n      } else if (this._workCell.isFgPalette()) {\n        let fg = this._workCell.getFgColor();\n        if (this._workCell.isBold() && fg < 8 && !swapColor && this._optionsService.options.drawBoldTextInBrightColors) {\n          fg += 8;\n        }\n        charElement.classList.add(`xterm-${swapColor ? 'b' : 'f'}g-${fg}`);\n      } else if (swapColor) {\n        charElement.classList.add(`xterm-bg-${INVERTED_DEFAULT_COLOR}`);\n      }\n\n      // bg\n      if (this._workCell.isBgRGB()) {\n        let style = charElement.getAttribute('style') || '';\n        style += `${swapColor ? '' : 'background-'}color:rgb(${(AttributeData.toColorRGB(this._workCell.getBgColor())).join(',')});`;\n        charElement.setAttribute('style', style);\n      } else if (this._workCell.isBgPalette()) {\n        charElement.classList.add(`xterm-${swapColor ? 'f' : 'b'}g-${this._workCell.getBgColor()}`);\n      } else if (swapColor) {\n        charElement.classList.add(`xterm-fg-${INVERTED_DEFAULT_COLOR}`);\n      }\n\n      fragment.appendChild(charElement);\n    }\n    return fragment;\n  }\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types';\nimport { C0 } from 'common/data/EscapeSequences';\n\n// reg + shift key mappings for digits and special chars\nconst KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = {\n  // digits 0-9\n  48: ['0', ')'],\n  49: ['1', '!'],\n  50: ['2', '@'],\n  51: ['3', '#'],\n  52: ['4', '$'],\n  53: ['5', '%'],\n  54: ['6', '^'],\n  55: ['7', '&'],\n  56: ['8', '*'],\n  57: ['9', '('],\n\n  // special chars\n  186: [';', ':'],\n  187: ['=', '+'],\n  188: [',', '<'],\n  189: ['-', '_'],\n  190: ['.', '>'],\n  191: ['/', '?'],\n  192: ['`', '~'],\n  219: ['[', '{'],\n  220: ['\\\\', '|'],\n  221: [']', '}'],\n  222: ['\\'', '\"']\n};\n\nexport function evaluateKeyboardEvent(\n  ev: IKeyboardEvent,\n  applicationCursorMode: boolean,\n  isMac: boolean,\n  macOptionIsMeta: boolean\n): IKeyboardResult {\n  const result: IKeyboardResult = {\n    type: KeyboardResultType.SEND_KEY,\n    // Whether to cancel event propagation (NOTE: this may not be needed since the event is\n    // canceled at the end of keyDown\n    cancel: false,\n    // The new key even to emit\n    key: undefined\n  };\n  const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);\n  switch (ev.keyCode) {\n    case 0:\n      if (ev.key === 'UIKeyInputUpArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OA';\n        } else {\n          result.key = C0.ESC + '[A';\n        }\n      }\n      else if (ev.key === 'UIKeyInputLeftArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OD';\n        } else {\n          result.key = C0.ESC + '[D';\n        }\n      }\n      else if (ev.key === 'UIKeyInputRightArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OC';\n        } else {\n          result.key = C0.ESC + '[C';\n        }\n      }\n      else if (ev.key === 'UIKeyInputDownArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OB';\n        } else {\n          result.key = C0.ESC + '[B';\n        }\n      }\n      break;\n    case 8:\n      // backspace\n      if (ev.shiftKey) {\n        result.key = C0.BS; // ^H\n        break;\n      } else if (ev.altKey) {\n        result.key = C0.ESC + C0.DEL; // \\e ^?\n        break;\n      }\n      result.key = C0.DEL; // ^?\n      break;\n    case 9:\n      // tab\n      if (ev.shiftKey) {\n        result.key = C0.ESC + '[Z';\n        break;\n      }\n      result.key = C0.HT;\n      result.cancel = true;\n      break;\n    case 13:\n      // return/enter\n      result.key = C0.CR;\n      result.cancel = true;\n      break;\n    case 27:\n      // escape\n      result.key = C0.ESC;\n      result.cancel = true;\n      break;\n    case 37:\n      // left-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';\n        // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (result.key === C0.ESC + '[1;3D') {\n          result.key = C0.ESC + (isMac ? 'b' : '[1;5D');\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OD';\n      } else {\n        result.key = C0.ESC + '[D';\n      }\n      break;\n    case 39:\n      // right-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';\n        // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (result.key === C0.ESC + '[1;3C') {\n          result.key = C0.ESC + (isMac ? 'f' : '[1;5C');\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OC';\n      } else {\n        result.key = C0.ESC + '[C';\n      }\n      break;\n    case 38:\n      // up-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';\n        // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (!isMac && result.key === C0.ESC + '[1;3A') {\n          result.key = C0.ESC + '[1;5A';\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OA';\n      } else {\n        result.key = C0.ESC + '[A';\n      }\n      break;\n    case 40:\n      // down-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';\n        // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (!isMac && result.key === C0.ESC + '[1;3B') {\n          result.key = C0.ESC + '[1;5B';\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OB';\n      } else {\n        result.key = C0.ESC + '[B';\n      }\n      break;\n    case 45:\n      // insert\n      if (!ev.shiftKey && !ev.ctrlKey) {\n        // <Ctrl> or <Shift> + <Insert> are used to\n        // copy-paste on some systems.\n        result.key = C0.ESC + '[2~';\n      }\n      break;\n    case 46:\n      // delete\n      if (modifiers) {\n        result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[3~';\n      }\n      break;\n    case 36:\n      // home\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OH';\n      } else {\n        result.key = C0.ESC + '[H';\n      }\n      break;\n    case 35:\n      // end\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OF';\n      } else {\n        result.key = C0.ESC + '[F';\n      }\n      break;\n    case 33:\n      // page up\n      if (ev.shiftKey) {\n        result.type = KeyboardResultType.PAGE_UP;\n      } else {\n        result.key = C0.ESC + '[5~';\n      }\n      break;\n    case 34:\n      // page down\n      if (ev.shiftKey) {\n        result.type = KeyboardResultType.PAGE_DOWN;\n      } else {\n        result.key = C0.ESC + '[6~';\n      }\n      break;\n    case 112:\n      // F1-F12\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';\n      } else {\n        result.key = C0.ESC + 'OP';\n      }\n      break;\n    case 113:\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';\n      } else {\n        result.key = C0.ESC + 'OQ';\n      }\n      break;\n    case 114:\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';\n      } else {\n        result.key = C0.ESC + 'OR';\n      }\n      break;\n    case 115:\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';\n      } else {\n        result.key = C0.ESC + 'OS';\n      }\n      break;\n    case 116:\n      if (modifiers) {\n        result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[15~';\n      }\n      break;\n    case 117:\n      if (modifiers) {\n        result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[17~';\n      }\n      break;\n    case 118:\n      if (modifiers) {\n        result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[18~';\n      }\n      break;\n    case 119:\n      if (modifiers) {\n        result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[19~';\n      }\n      break;\n    case 120:\n      if (modifiers) {\n        result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[20~';\n      }\n      break;\n    case 121:\n      if (modifiers) {\n        result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[21~';\n      }\n      break;\n    case 122:\n      if (modifiers) {\n        result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[23~';\n      }\n      break;\n    case 123:\n      if (modifiers) {\n        result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[24~';\n      }\n      break;\n    default:\n      // a-z and space\n      if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {\n        if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n          result.key = String.fromCharCode(ev.keyCode - 64);\n        } else if (ev.keyCode === 32) {\n          result.key = C0.NUL;\n        } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {\n          // escape, file sep, group sep, record sep, unit sep\n          result.key = String.fromCharCode(ev.keyCode - 51 + 27);\n        } else if (ev.keyCode === 56) {\n          result.key = C0.DEL;\n        } else if (ev.keyCode === 219) {\n          result.key = C0.ESC;\n        } else if (ev.keyCode === 220) {\n          result.key = C0.FS;\n        } else if (ev.keyCode === 221) {\n          result.key = C0.GS;\n        }\n      } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) {\n        // On macOS this is a third level shift when !macOptionIsMeta. Use <Esc> instead.\n        const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];\n        const key = keyMapping && keyMapping[!ev.shiftKey ? 0 : 1];\n        if (key) {\n          result.key = C0.ESC + key;\n        } else if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n          const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;\n          result.key = C0.ESC + String.fromCharCode(keyCode);\n        }\n      } else if (isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {\n        if (ev.keyCode === 65) { // cmd + a\n          result.type = KeyboardResultType.SELECT_ALL;\n        }\n      } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) {\n        // Include only keys that that result in a _single_ character; don't include num lock, volume up, etc.\n        result.key = ev.key;\n      } else if (ev.key && ev.ctrlKey) {\n        if (ev.key === '_') { // ^_\n          result.key = C0.US;\n        }\n      }\n      break;\n  }\n\n  return result;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'xterm';\nimport { ITerminal } from './Types';\nimport { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';\n\nexport function applyWindowsMode(terminal: ITerminal): IDisposable {\n  // Winpty does not support wraparound mode which means that lines will never\n  // be marked as wrapped. This causes issues for things like copying a line\n  // retaining the wrapped new line characters or if consumers are listening\n  // in on the data stream.\n  //\n  // The workaround for this is to listen to every incoming line feed and mark\n  // the line as wrapped if the last character in the previous line is not a\n  // space. This is certainly not without its problems, but generally on\n  // Windows when text reaches the end of the terminal it's likely going to be\n  // wrapped.\n  return terminal.onLineFeed(() => {\n    const line = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y - 1);\n    const lastChar = line.get(terminal.cols - 1);\n\n    const nextLine = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y);\n    nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE);\n  });\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { RenderDebouncer } from 'browser/RenderDebouncer';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { Disposable } from 'common/Lifecycle';\nimport { ScreenDprMonitor } from 'browser/ScreenDprMonitor';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { IColorSet } from 'browser/Types';\nimport { IOptionsService } from 'common/services/Services';\nimport { ICharSizeService, IRenderService } from 'browser/services/Services';\n\nexport class RenderService extends Disposable implements IRenderService {\n  serviceBrand: any;\n\n  private _renderDebouncer: RenderDebouncer;\n  private _screenDprMonitor: ScreenDprMonitor;\n\n  private _isPaused: boolean = false;\n  private _needsFullRefresh: boolean = false;\n  private _canvasWidth: number = 0;\n  private _canvasHeight: number = 0;\n\n  private _onDimensionsChange = new EventEmitter<IRenderDimensions>();\n  public get onDimensionsChange(): IEvent<IRenderDimensions> { return this._onDimensionsChange.event; }\n  private _onRender = new EventEmitter<{ start: number, end: number }>();\n  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }\n  private _onRefreshRequest = new EventEmitter<{ start: number, end: number }>();\n  public get onRefreshRequest(): IEvent<{ start: number, end: number }> { return this._onRefreshRequest.event; }\n\n  public get dimensions(): IRenderDimensions { return this._renderer.dimensions; }\n\n  constructor(\n    private _renderer: IRenderer,\n    private _rowCount: number,\n    readonly screenElement: HTMLElement,\n    @IOptionsService readonly optionsService: IOptionsService,\n    @ICharSizeService readonly charSizeService: ICharSizeService\n  ) {\n    super();\n    this._renderDebouncer = new RenderDebouncer((start, end) => this._renderRows(start, end));\n    this.register(this._renderDebouncer);\n\n    this._screenDprMonitor = new ScreenDprMonitor();\n    this._screenDprMonitor.setListener(() => this.onDevicePixelRatioChange());\n    this.register(this._screenDprMonitor);\n\n    this.register(optionsService.onOptionChange(() => this._renderer.onOptionsChanged()));\n    this.register(charSizeService.onCharSizeChange(() => this.onCharSizeChanged()));\n\n    // dprchange should handle this case, we need this as well for browsers that don't support the\n    // matchMedia query.\n    this.register(addDisposableDomListener(window, 'resize', () => this.onDevicePixelRatioChange()));\n\n    // Detect whether IntersectionObserver is detected and enable renderer pause\n    // and resume based on terminal visibility if so\n    if ('IntersectionObserver' in window) {\n      const observer = new IntersectionObserver(e => this._onIntersectionChange(e[e.length - 1]), { threshold: 0 });\n      observer.observe(screenElement);\n      this.register({ dispose: () => observer.disconnect() });\n    }\n  }\n\n  private _onIntersectionChange(entry: IntersectionObserverEntry): void {\n    this._isPaused = entry.intersectionRatio === 0;\n    if (!this._isPaused && this._needsFullRefresh) {\n      this.refreshRows(0, this._rowCount - 1);\n      this._needsFullRefresh = false;\n    }\n  }\n\n  public refreshRows(start: number, end: number): void {\n    if (this._isPaused) {\n      this._needsFullRefresh = true;\n      return;\n    }\n    this._renderDebouncer.refresh(start, end, this._rowCount);\n  }\n\n  private _renderRows(start: number, end: number): void {\n    this._renderer.renderRows(start, end);\n    this._onRender.fire({ start, end });\n  }\n\n  public resize(cols: number, rows: number): void {\n    this._rowCount = rows;\n    this._fireOnCanvasResize();\n  }\n\n  public changeOptions(): void {\n    this._renderer.onOptionsChanged();\n    this._fireOnCanvasResize();\n  }\n\n  private _fireOnCanvasResize(): void {\n    // Don't fire the event if the dimensions haven't changed\n    if (this._renderer.dimensions.canvasWidth === this._canvasWidth && this._renderer.dimensions.canvasHeight === this._canvasHeight) {\n      return;\n    }\n    this._onDimensionsChange.fire(this._renderer.dimensions);\n  }\n\n  public dispose(): void {\n    this._renderer.dispose();\n  }\n\n  public setRenderer(renderer: IRenderer): void {\n    // TODO: RenderService should be the only one to dispose the renderer\n    this._renderer.dispose();\n    this._renderer = renderer;\n    this.refreshRows(0, this._rowCount - 1);\n  }\n\n  private _fullRefresh(): void {\n    if (this._isPaused) {\n      this._needsFullRefresh = true;\n    } else {\n      this.refreshRows(0, this._rowCount - 1);\n    }\n  }\n\n  public setColors(colors: IColorSet): void {\n    this._renderer.setColors(colors);\n    this._fullRefresh();\n  }\n\n  public onDevicePixelRatioChange(): void {\n    this._renderer.onDevicePixelRatioChange();\n    this.refreshRows(0, this._rowCount - 1);\n  }\n\n  public onResize(cols: number, rows: number): void {\n    this._renderer.onResize(cols, rows);\n    this._fullRefresh();\n  }\n\n  // TODO: Is this useful when we have onResize?\n  public onCharSizeChanged(): void {\n    this._renderer.onCharSizeChanged();\n  }\n\n  public onBlur(): void {\n    this._renderer.onBlur();\n  }\n\n  public onFocus(): void {\n    this._renderer.onFocus();\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {\n    this._renderer.onSelectionChanged(start, end, columnSelectMode);\n  }\n\n  public onCursorMove(): void {\n    this._renderer.onCursorMove();\n  }\n\n  public clear(): void {\n    this._renderer.clear();\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n    return this._renderer.registerCharacterJoiner(handler);\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): boolean {\n    return this._renderer.deregisterCharacterJoiner(joinerId);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService, ITerminalOptions, IPartialTerminalOptions } from 'common/services/Services';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { isMac } from 'common/Platform';\nimport { clone } from 'common/Clone';\n\n// Source: https://freesound.org/people/altemark/sounds/45759/\n// This sound is released under the Creative Commons Attribution 3.0 Unported\n// (CC BY 3.0) license. It was created by 'altemark'. No modifications have been\n// made, apart from the conversion to base64.\nexport const DEFAULT_BELL_SOUND = 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';\n\n// TODO: Freeze?\nexport const DEFAULT_OPTIONS: ITerminalOptions = Object.freeze({\n  cols: 80,\n  rows: 24,\n  cursorBlink: false,\n  cursorStyle: 'block',\n  bellSound:  DEFAULT_BELL_SOUND,\n  bellStyle: 'none',\n  drawBoldTextInBrightColors: true,\n  fastScrollModifier: 'alt',\n  fastScrollSensitivity: 5,\n  fontFamily: 'courier-new, courier, monospace',\n  fontSize: 15,\n  fontWeight: 'normal',\n  fontWeightBold: 'bold',\n  lineHeight: 1.0,\n  letterSpacing: 0,\n  logLevel: 'info',\n  scrollback: 1000,\n  scrollSensitivity: 1,\n  screenReaderMode: false,\n  macOptionIsMeta: false,\n  macOptionClickForcesSelection: false,\n  disableStdin: false,\n  allowTransparency: false,\n  tabStopWidth: 8,\n  theme: {},\n  rightClickSelectsWord: isMac,\n  rendererType: 'canvas',\n  windowsMode: false,\n\n  convertEol: false,\n  termName: 'xterm',\n  screenKeys: false,\n  cancelEvents: false,\n  useFlowControl: false,\n  wordSeparator: ' ()[]{}\\',:;\"'\n});\n\n/**\n * The set of options that only have an effect when set in the Terminal constructor.\n */\nconst CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows'];\n\nexport class OptionsService implements IOptionsService {\n  serviceBrand: any;\n\n  public options: ITerminalOptions;\n\n  private _onOptionChange = new EventEmitter<string>();\n  public get onOptionChange(): IEvent<string> { return this._onOptionChange.event; }\n\n  constructor(options: IPartialTerminalOptions) {\n    this.options = clone(DEFAULT_OPTIONS);\n    Object.keys(options).forEach(k => {\n      if (k in this.options) {\n        const newValue = options[k as keyof IPartialTerminalOptions] as any;\n        this.options[k] = newValue;\n      }\n    });\n  }\n\n  public setOption(key: string, value: any): void {\n    if (!(key in DEFAULT_OPTIONS)) {\n      throw new Error('No option with key \"' + key + '\"');\n    }\n    if (CONSTRUCTOR_ONLY_OPTIONS.indexOf(key) !== -1) {\n      throw new Error(`Option \"${key}\" can only be set in the constructor`);\n    }\n    if (this.options[key] === value) {\n      return;\n    }\n\n    value = this._sanitizeAndValidateOption(key, value);\n\n    // Don't fire an option change event if they didn't change\n    if (this.options[key] === value) {\n      return;\n    }\n\n    this.options[key] = value;\n    this._onOptionChange.fire(key);\n  }\n\n  private _sanitizeAndValidateOption(key: string, value: any): any {\n    switch (key) {\n      case 'bellStyle':\n      case 'cursorStyle':\n      case 'fontWeight':\n      case 'fontWeightBold':\n      case 'rendererType':\n      case 'wordSeparator':\n        if (!value) {\n          value = DEFAULT_OPTIONS[key];\n        }\n        break;\n      case 'lineHeight':\n      case 'tabStopWidth':\n        if (value < 1) {\n          throw new Error(`${key} cannot be less than 1, value: ${value}`);\n        }\n        break;\n      case 'scrollback':\n        value = Math.min(value, 4294967295);\n        if (value < 0) {\n          throw new Error(`${key} cannot be less than 0, value: ${value}`);\n        }\n        break;\n      case 'fastScrollSensitivity':\n      case 'scrollSensitivity':\n        if (value <= 0) {\n          throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`);\n        }\n        break;\n    }\n    return value;\n  }\n\n  public getOption(key: string): any {\n    if (!(key in DEFAULT_OPTIONS)) {\n      throw new Error(`No option with key \"${key}\"`);\n    }\n    return this.options[key];\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService } from 'common/services/Services';\nimport { IEvent, EventEmitter } from 'common/EventEmitter';\nimport { ICharSizeService } from 'browser/services/Services';\n\nexport class CharSizeService implements ICharSizeService {\n  serviceBrand: any;\n\n  public width: number = 0;\n  public height: number = 0;\n  private _measureStrategy: IMeasureStrategy;\n\n  public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; }\n\n  private _onCharSizeChange = new EventEmitter<void>();\n  public get onCharSizeChange(): IEvent<void> { return this._onCharSizeChange.event; }\n\n  constructor(\n    readonly document: Document,\n    readonly parentElement: HTMLElement,\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    this._measureStrategy = new DomMeasureStrategy(document, parentElement, this._optionsService);\n  }\n\n  public measure(): void {\n    const result = this._measureStrategy.measure();\n    if (result.width !== this.width || result.height !== this.height) {\n      this.width = result.width;\n      this.height = result.height;\n      this._onCharSizeChange.fire();\n    }\n  }\n}\n\ninterface IMeasureStrategy {\n  measure(): IReadonlyMeasureResult;\n}\n\ninterface IReadonlyMeasureResult {\n  readonly width: number;\n  readonly height: number;\n}\n\ninterface IMeasureResult {\n  width: number;\n  height: number;\n}\n\n// TODO: For supporting browsers we should also provide a CanvasCharDimensionsProvider that uses ctx.measureText\nclass DomMeasureStrategy implements IMeasureStrategy {\n  private _result: IMeasureResult = { width: 0, height: 0 };\n  private _measureElement: HTMLElement;\n\n  constructor(\n    private _document: Document,\n    private _parentElement: HTMLElement,\n    private _optionsService: IOptionsService\n  ) {\n    this._measureElement = this._document.createElement('span');\n    this._measureElement.classList.add('xterm-char-measure-element');\n    this._measureElement.textContent = 'W';\n    this._measureElement.setAttribute('aria-hidden', 'true');\n    this._parentElement.appendChild(this._measureElement);\n  }\n\n  public measure(): IReadonlyMeasureResult {\n    this._measureElement.style.fontFamily = this._optionsService.options.fontFamily;\n    this._measureElement.style.fontSize = `${this._optionsService.options.fontSize}px`;\n\n    // Note that this triggers a synchronous layout\n    const geometry = this._measureElement.getBoundingClientRect();\n\n    // If values are 0 then the element is likely currently display:none, in which case we should\n    // retain the previous value.\n    if (geometry.width !== 0 && geometry.height !== 0) {\n      this._result.width = geometry.width;\n      this._result.height = Math.ceil(geometry.height);\n    }\n\n    return this._result;\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { BufferSet } from 'common/buffer/BufferSet';\nimport { IBufferSet, IBuffer } from 'common/buffer/Types';\n\nexport const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars\nexport const MINIMUM_ROWS = 1;\n\nexport class BufferService implements IBufferService {\n  serviceBrand: any;\n\n  public cols: number;\n  public rows: number;\n  public buffers: IBufferSet;\n\n  public get buffer(): IBuffer { return this.buffers.active; }\n\n  constructor(\n    @IOptionsService private _optionsService: IOptionsService\n  ) {\n    this.cols = Math.max(_optionsService.options.cols, MINIMUM_COLS);\n    this.rows = Math.max(_optionsService.options.rows, MINIMUM_ROWS);\n    this.buffers = new BufferSet(_optionsService, this);\n  }\n\n  public resize(cols: number, rows: number): void {\n    this.cols = cols;\n    this.rows = rows;\n  }\n\n  public reset(): void {\n    this.buffers = new BufferSet(this._optionsService, this);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IAttributeData } from 'common/Types';\nimport { Buffer } from 'common/buffer/Buffer';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { IOptionsService, IBufferService } from 'common/services/Services';\n\n/**\n * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and\n * provides also utilities for working with them.\n */\nexport class BufferSet implements IBufferSet {\n  private _normal: Buffer;\n  private _alt: Buffer;\n  private _activeBuffer: Buffer;\n\n\n  private _onBufferActivate = new EventEmitter<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}>();\n  public get onBufferActivate(): IEvent<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}> { return this._onBufferActivate.event; }\n\n  /**\n   * Create a new BufferSet for the given terminal.\n   * @param _terminal - The terminal the BufferSet will belong to\n   */\n  constructor(\n    readonly optionsService: IOptionsService,\n    readonly bufferService: IBufferService\n  ) {\n    this._normal = new Buffer(true, optionsService, bufferService);\n    this._normal.fillViewportRows();\n\n    // The alt buffer should never have scrollback.\n    // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer\n    this._alt = new Buffer(false, optionsService, bufferService);\n    this._activeBuffer = this._normal;\n\n    this.setupTabStops();\n  }\n\n  /**\n   * Returns the alt Buffer of the BufferSet\n   */\n  public get alt(): Buffer {\n    return this._alt;\n  }\n\n  /**\n   * Returns the normal Buffer of the BufferSet\n   */\n  public get active(): Buffer {\n    return this._activeBuffer;\n  }\n\n  /**\n   * Returns the currently active Buffer of the BufferSet\n   */\n  public get normal(): Buffer {\n    return this._normal;\n  }\n\n  /**\n   * Sets the normal Buffer of the BufferSet as its currently active Buffer\n   */\n  public activateNormalBuffer(): void {\n    if (this._activeBuffer === this._normal) {\n      return;\n    }\n    this._normal.x = this._alt.x;\n    this._normal.y = this._alt.y;\n    // The alt buffer should always be cleared when we switch to the normal\n    // buffer. This frees up memory since the alt buffer should always be new\n    // when activated.\n    this._alt.clear();\n    this._activeBuffer = this._normal;\n    this._onBufferActivate.fire({\n      activeBuffer: this._normal,\n      inactiveBuffer: this._alt\n    });\n  }\n\n  /**\n   * Sets the alt Buffer of the BufferSet as its currently active Buffer\n   */\n  public activateAltBuffer(fillAttr?: IAttributeData): void {\n    if (this._activeBuffer === this._alt) {\n      return;\n    }\n    // Since the alt buffer is always cleared when the normal buffer is\n    // activated, we want to fill it when switching to it.\n    this._alt.fillViewportRows(fillAttr);\n    this._alt.x = this._normal.x;\n    this._alt.y = this._normal.y;\n    this._activeBuffer = this._alt;\n    this._onBufferActivate.fire({\n      activeBuffer: this._alt,\n      inactiveBuffer: this._normal\n    });\n  }\n\n  /**\n   * Resizes both normal and alt buffers, adjusting their data accordingly.\n   * @param newCols The new number of columns.\n   * @param newRows The new number of rows.\n   */\n  public resize(newCols: number, newRows: number): void {\n    this._normal.resize(newCols, newRows);\n    this._alt.resize(newCols, newRows);\n  }\n\n  /**\n   * Setup the tab stops.\n   * @param i The index to start setting up tab stops from.\n   */\n  public setupTabStops(i?: number): void {\n    this._normal.setupTabStops(i);\n    this._alt.setupTabStops(i);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CircularList, IInsertEvent } from 'common/CircularList';\nimport { IBuffer, BufferIndex, IBufferStringIterator, IBufferStringIteratorResult } from 'common/buffer/Types';\nimport { IBufferLine, ICellData, IAttributeData, ICharset } from 'common/Types';\nimport { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { CellData } from 'common/buffer/CellData';\nimport { NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_CHAR_INDEX } from 'common/buffer/Constants';\nimport { reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths, getWrappedLineTrimmedLength } from 'common/buffer/BufferReflow';\nimport { Marker } from 'common/buffer/Marker';\nimport { IOptionsService, IBufferService } from 'common/services/Services';\nimport { DEFAULT_CHARSET } from 'common/data/Charsets';\n\nexport const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1\n\n/**\n * This class represents a terminal buffer (an internal state of the terminal), where the\n * following information is stored (in high-level):\n *   - text content of this particular buffer\n *   - cursor position\n *   - scroll position\n */\nexport class Buffer implements IBuffer {\n  public lines: CircularList<IBufferLine>;\n  public ydisp: number = 0;\n  public ybase: number = 0;\n  public y: number = 0;\n  public x: number = 0;\n  public scrollBottom: number;\n  public scrollTop: number;\n  // TODO: Type me\n  public tabs: any;\n  public savedY: number = 0;\n  public savedX: number = 0;\n  public savedCurAttrData = DEFAULT_ATTR_DATA.clone();\n  public savedCharset: ICharset | null = DEFAULT_CHARSET;\n  public markers: Marker[] = [];\n  private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n  private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]);\n  private _cols: number;\n  private _rows: number;\n\n  constructor(\n    private _hasScrollback: boolean,\n    private _optionsService: IOptionsService,\n    private _bufferService: IBufferService\n  ) {\n    this._cols = this._bufferService.cols;\n    this._rows = this._bufferService.rows;\n    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));\n    this.scrollTop = 0;\n    this.scrollBottom = this._rows - 1;\n    this.setupTabStops();\n  }\n\n  public getNullCell(attr?: IAttributeData): ICellData {\n    if (attr) {\n      this._nullCell.fg = attr.fg;\n      this._nullCell.bg = attr.bg;\n    } else {\n      this._nullCell.fg = 0;\n      this._nullCell.bg = 0;\n    }\n    return this._nullCell;\n  }\n\n  public getWhitespaceCell(attr?: IAttributeData): ICellData {\n    if (attr) {\n      this._whitespaceCell.fg = attr.fg;\n      this._whitespaceCell.bg = attr.bg;\n    } else {\n      this._whitespaceCell.fg = 0;\n      this._whitespaceCell.bg = 0;\n    }\n    return this._whitespaceCell;\n  }\n\n  public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine {\n    return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped);\n  }\n\n  public get hasScrollback(): boolean {\n    return this._hasScrollback && this.lines.maxLength > this._rows;\n  }\n\n  public get isCursorInViewport(): boolean {\n    const absoluteY = this.ybase + this.y;\n    const relativeY = absoluteY - this.ydisp;\n    return (relativeY >= 0 && relativeY < this._rows);\n  }\n\n  /**\n   * Gets the correct buffer length based on the rows provided, the terminal's\n   * scrollback and whether this buffer is flagged to have scrollback or not.\n   * @param rows The terminal rows to use in the calculation.\n   */\n  private _getCorrectBufferLength(rows: number): number {\n    if (!this._hasScrollback) {\n      return rows;\n    }\n\n    const correctBufferLength = rows + this._optionsService.options.scrollback;\n\n    return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength;\n  }\n\n  /**\n   * Fills the buffer's viewport with blank lines.\n   */\n  public fillViewportRows(fillAttr?: IAttributeData): void {\n    if (this.lines.length === 0) {\n      if (fillAttr === undefined) {\n        fillAttr = DEFAULT_ATTR_DATA;\n      }\n      let i = this._rows;\n      while (i--) {\n        this.lines.push(this.getBlankLine(fillAttr));\n      }\n    }\n  }\n\n  /**\n   * Clears the buffer to it's initial state, discarding all previous data.\n   */\n  public clear(): void {\n    this.ydisp = 0;\n    this.ybase = 0;\n    this.y = 0;\n    this.x = 0;\n    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));\n    this.scrollTop = 0;\n    this.scrollBottom = this._rows - 1;\n    this.setupTabStops();\n  }\n\n  /**\n   * Resizes the buffer, adjusting its data accordingly.\n   * @param newCols The new number of columns.\n   * @param newRows The new number of rows.\n   */\n  public resize(newCols: number, newRows: number): void {\n    // store reference to null cell with default attrs\n    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n\n    // Increase max length if needed before adjustments to allow space to fill\n    // as required.\n    const newMaxLength = this._getCorrectBufferLength(newRows);\n    if (newMaxLength > this.lines.maxLength) {\n      this.lines.maxLength = newMaxLength;\n    }\n\n    // The following adjustments should only happen if the buffer has been\n    // initialized/filled.\n    if (this.lines.length > 0) {\n      // Deal with columns increasing (reducing needs to happen after reflow)\n      if (this._cols < newCols) {\n        for (let i = 0; i < this.lines.length; i++) {\n          this.lines.get(i)!.resize(newCols, nullCell);\n        }\n      }\n\n      // Resize rows in both directions as needed\n      let addToY = 0;\n      if (this._rows < newRows) {\n        for (let y = this._rows; y < newRows; y++) {\n          if (this.lines.length < newRows + this.ybase) {\n            if (this._optionsService.options.windowsMode) {\n              // Just add the new missing rows on Windows as conpty reprints the screen with it's\n              // view of the world. Once a line enters scrollback for conpty it remains there\n              this.lines.push(new BufferLine(newCols, nullCell));\n            } else {\n              if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {\n                // There is room above the buffer and there are no empty elements below the line,\n                // scroll up\n                this.ybase--;\n                addToY++;\n                if (this.ydisp > 0) {\n                  // Viewport is at the top of the buffer, must increase downwards\n                  this.ydisp--;\n                }\n              } else {\n                // Add a blank line if there is no buffer left at the top to scroll to, or if there\n                // are blank lines after the cursor\n                this.lines.push(new BufferLine(newCols, nullCell));\n              }\n            }\n          }\n        }\n      } else { // (this._rows >= newRows)\n        for (let y = this._rows; y > newRows; y--) {\n          if (this.lines.length > newRows + this.ybase) {\n            if (this.lines.length > this.ybase + this.y + 1) {\n              // The line is a blank line below the cursor, remove it\n              this.lines.pop();\n            } else {\n              // The line is the cursor, scroll down\n              this.ybase++;\n              this.ydisp++;\n            }\n          }\n        }\n      }\n\n      // Reduce max length if needed after adjustments, this is done after as it\n      // would otherwise cut data from the bottom of the buffer.\n      if (newMaxLength < this.lines.maxLength) {\n        // Trim from the top of the buffer and adjust ybase and ydisp.\n        const amountToTrim = this.lines.length - newMaxLength;\n        if (amountToTrim > 0) {\n          this.lines.trimStart(amountToTrim);\n          this.ybase = Math.max(this.ybase - amountToTrim, 0);\n          this.ydisp = Math.max(this.ydisp - amountToTrim, 0);\n          this.savedY = Math.max(this.savedY - amountToTrim, 0);\n        }\n        this.lines.maxLength = newMaxLength;\n      }\n\n      // Make sure that the cursor stays on screen\n      this.x = Math.min(this.x, newCols - 1);\n      this.y = Math.min(this.y, newRows - 1);\n      if (addToY) {\n        this.y += addToY;\n      }\n      this.savedX = Math.min(this.savedX, newCols - 1);\n\n      this.scrollTop = 0;\n    }\n\n    this.scrollBottom = newRows - 1;\n\n    if (this._isReflowEnabled) {\n      this._reflow(newCols, newRows);\n\n      // Trim the end of the line off if cols shrunk\n      if (this._cols > newCols) {\n        for (let i = 0; i < this.lines.length; i++) {\n          this.lines.get(i)!.resize(newCols, nullCell);\n        }\n      }\n    }\n\n    this._cols = newCols;\n    this._rows = newRows;\n  }\n\n  private get _isReflowEnabled(): boolean {\n    return this._hasScrollback && !this._optionsService.options.windowsMode;\n  }\n\n  private _reflow(newCols: number, newRows: number): void {\n    if (this._cols === newCols) {\n      return;\n    }\n\n    // Iterate through rows, ignore the last one as it cannot be wrapped\n    if (newCols > this._cols) {\n      this._reflowLarger(newCols, newRows);\n    } else {\n      this._reflowSmaller(newCols, newRows);\n    }\n  }\n\n  private _reflowLarger(newCols: number, newRows: number): void {\n    const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA));\n    if (toRemove.length > 0) {\n      const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove);\n      reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout);\n      this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved);\n    }\n  }\n\n  private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void {\n    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n    // Adjust viewport based on number of items removed\n    let viewportAdjustments = countRemoved;\n    while (viewportAdjustments-- > 0) {\n      if (this.ybase === 0) {\n        if (this.y > 0) {\n          this.y--;\n        }\n        if (this.lines.length < newRows) {\n          // Add an extra row at the bottom of the viewport\n          this.lines.push(new BufferLine(newCols, nullCell));\n        }\n      } else {\n        if (this.ydisp === this.ybase) {\n          this.ydisp--;\n        }\n        this.ybase--;\n      }\n    }\n    this.savedY = Math.max(this.savedY - countRemoved, 0);\n  }\n\n  private _reflowSmaller(newCols: number, newRows: number): void {\n    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n    // Gather all BufferLines that need to be inserted into the Buffer here so that they can be\n    // batched up and only committed once\n    const toInsert = [];\n    let countToInsert = 0;\n    // Go backwards as many lines may be trimmed and this will avoid considering them\n    for (let y = this.lines.length - 1; y >= 0; y--) {\n      // Check whether this line is a problem\n      let nextLine = this.lines.get(y) as BufferLine;\n      if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) {\n        continue;\n      }\n\n      // Gather wrapped lines and adjust y to be the starting line\n      const wrappedLines: BufferLine[] = [nextLine];\n      while (nextLine.isWrapped && y > 0) {\n        nextLine = this.lines.get(--y) as BufferLine;\n        wrappedLines.unshift(nextLine);\n      }\n\n      // If these lines contain the cursor don't touch them, the program will handle fixing up\n      // wrapped lines with the cursor\n      const absoluteY = this.ybase + this.y;\n      if (absoluteY >= y && absoluteY < y + wrappedLines.length) {\n        continue;\n      }\n\n      const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength();\n      const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols);\n      const linesToAdd = destLineLengths.length - wrappedLines.length;\n      let trimmedLines: number;\n      if (this.ybase === 0 && this.y !== this.lines.length - 1) {\n        // If the top section of the buffer is not yet filled\n        trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd);\n      } else {\n        trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd);\n      }\n\n      // Add the new lines\n      const newLines: BufferLine[] = [];\n      for (let i = 0; i < linesToAdd; i++) {\n        const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine;\n        newLines.push(newLine);\n      }\n      if (newLines.length > 0) {\n        toInsert.push({\n          // countToInsert here gets the actual index, taking into account other inserted items.\n          // using this we can iterate through the list forwards\n          start: y + wrappedLines.length + countToInsert,\n          newLines\n        });\n        countToInsert += newLines.length;\n      }\n      wrappedLines.push(...newLines);\n\n      // Copy buffer data to new locations, this needs to happen backwards to do in-place\n      let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols);\n      let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols;\n      if (destCol === 0) {\n        destLineIndex--;\n        destCol = destLineLengths[destLineIndex];\n      }\n      let srcLineIndex = wrappedLines.length - linesToAdd - 1;\n      let srcCol = lastLineLength;\n      while (srcLineIndex >= 0) {\n        const cellsToCopy = Math.min(srcCol, destCol);\n        wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true);\n        destCol -= cellsToCopy;\n        if (destCol === 0) {\n          destLineIndex--;\n          destCol = destLineLengths[destLineIndex];\n        }\n        srcCol -= cellsToCopy;\n        if (srcCol === 0) {\n          srcLineIndex--;\n          const wrappedLinesIndex = Math.max(srcLineIndex, 0);\n          srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols);\n        }\n      }\n\n      // Null out the end of the line ends if a wide character wrapped to the following line\n      for (let i = 0; i < wrappedLines.length; i++) {\n        if (destLineLengths[i] < newCols) {\n          wrappedLines[i].setCell(destLineLengths[i], nullCell);\n        }\n      }\n\n      // Adjust viewport as needed\n      let viewportAdjustments = linesToAdd - trimmedLines;\n      while (viewportAdjustments-- > 0) {\n        if (this.ybase === 0) {\n          if (this.y < newRows - 1) {\n            this.y++;\n            this.lines.pop();\n          } else {\n            this.ybase++;\n            this.ydisp++;\n          }\n        } else {\n          // Ensure ybase does not exceed its maximum value\n          if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) {\n            if (this.ybase === this.ydisp) {\n              this.ydisp++;\n            }\n            this.ybase++;\n          }\n        }\n      }\n      this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1);\n    }\n\n    // Rearrange lines in the buffer if there are any insertions, this is done at the end rather\n    // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many\n    // costly calls to CircularList.splice.\n    if (toInsert.length > 0) {\n      // Record buffer insert events and then play them back backwards so that the indexes are\n      // correct\n      const insertEvents: IInsertEvent[] = [];\n\n      // Record original lines so they don't get overridden when we rearrange the list\n      const originalLines: BufferLine[] = [];\n      for (let i = 0; i < this.lines.length; i++) {\n        originalLines.push(this.lines.get(i) as BufferLine);\n      }\n      const originalLinesLength = this.lines.length;\n\n      let originalLineIndex = originalLinesLength - 1;\n      let nextToInsertIndex = 0;\n      let nextToInsert = toInsert[nextToInsertIndex];\n      this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert);\n      let countInsertedSoFar = 0;\n      for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) {\n        if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) {\n          // Insert extra lines here, adjusting i as needed\n          for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) {\n            this.lines.set(i--, nextToInsert.newLines[nextI]);\n          }\n          i++;\n\n          // Create insert events for later\n          insertEvents.push({\n            index: originalLineIndex + 1,\n            amount: nextToInsert.newLines.length\n          });\n\n          countInsertedSoFar += nextToInsert.newLines.length;\n          nextToInsert = toInsert[++nextToInsertIndex];\n        } else {\n          this.lines.set(i, originalLines[originalLineIndex--]);\n        }\n      }\n\n      // Update markers\n      let insertCountEmitted = 0;\n      for (let i = insertEvents.length - 1; i >= 0; i--) {\n        insertEvents[i].index += insertCountEmitted;\n        this.lines.onInsertEmitter.fire(insertEvents[i]);\n        insertCountEmitted += insertEvents[i].amount;\n      }\n      const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength);\n      if (amountToTrim > 0) {\n        this.lines.onTrimEmitter.fire(amountToTrim);\n      }\n    }\n  }\n\n  // private _reflowSmallerGetLinesNeeded()\n\n  /**\n   * Translates a string index back to a BufferIndex.\n   * To get the correct buffer position the string must start at `startCol` 0\n   * (default in translateBufferLineToString).\n   * The method also works on wrapped line strings given rows were not trimmed.\n   * The method operates on the CharData string length, there are no\n   * additional content or boundary checks. Therefore the string and the buffer\n   * should not be altered in between.\n   * TODO: respect trim flag after fixing #1685\n   * @param lineIndex line index the string was retrieved from\n   * @param stringIndex index within the string\n   * @param startCol column offset the string was retrieved from\n   */\n  public stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight: boolean = false): BufferIndex {\n    while (stringIndex) {\n      const line = this.lines.get(lineIndex);\n      if (!line) {\n        return [-1, -1];\n      }\n      const length = (trimRight) ? line.getTrimmedLength() : line.length;\n      for (let i = 0; i < length; ++i) {\n        if (line.get(i)[CHAR_DATA_WIDTH_INDEX]) {\n          // empty cells report a string length of 0, but get replaced\n          // with a whitespace in translateToString, thus replace with 1\n          stringIndex -= line.get(i)[CHAR_DATA_CHAR_INDEX].length || 1;\n        }\n        if (stringIndex < 0) {\n          return [lineIndex, i];\n        }\n      }\n      lineIndex++;\n    }\n    return [lineIndex, 0];\n  }\n\n  /**\n   * Translates a buffer line to a string, with optional start and end columns.\n   * Wide characters will count as two columns in the resulting string. This\n   * function is useful for getting the actual text underneath the raw selection\n   * position.\n   * @param line The line being translated.\n   * @param trimRight Whether to trim whitespace to the right.\n   * @param startCol The column to start at.\n   * @param endCol The column to end at.\n   */\n  public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string {\n    const line = this.lines.get(lineIndex);\n    if (!line) {\n      return '';\n    }\n    return line.translateToString(trimRight, startCol, endCol);\n  }\n\n  public getWrappedRangeForLine(y: number): { first: number, last: number } {\n    let first = y;\n    let last = y;\n    // Scan upwards for wrapped lines\n    while (first > 0 && this.lines.get(first)!.isWrapped) {\n      first--;\n    }\n    // Scan downwards for wrapped lines\n    while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) {\n      last++;\n    }\n    return { first, last };\n  }\n\n  /**\n   * Setup the tab stops.\n   * @param i The index to start setting up tab stops from.\n   */\n  public setupTabStops(i?: number): void {\n    if (i !== null && i !== undefined) {\n      if (!this.tabs[i]) {\n        i = this.prevStop(i);\n      }\n    } else {\n      this.tabs = {};\n      i = 0;\n    }\n\n    for (; i < this._cols; i += this._optionsService.options.tabStopWidth) {\n      this.tabs[i] = true;\n    }\n  }\n\n  /**\n   * Move the cursor to the previous tab stop from the given position (default is current).\n   * @param x The position to move the cursor to the previous tab stop.\n   */\n  public prevStop(x?: number): number {\n    if (x === null || x === undefined) {\n      x = this.x;\n    }\n    while (!this.tabs[--x] && x > 0);\n    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n  }\n\n  /**\n   * Move the cursor one tab stop forward from the given position (default is current).\n   * @param x The position to move the cursor one tab stop forward.\n   */\n  public nextStop(x?: number): number {\n    if (x === null || x === undefined) {\n      x = this.x;\n    }\n    while (!this.tabs[++x] && x < this._cols);\n    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n  }\n\n  public addMarker(y: number): Marker {\n    const marker = new Marker(y);\n    this.markers.push(marker);\n    marker.register(this.lines.onTrim(amount => {\n      marker.line -= amount;\n      // The marker should be disposed when the line is trimmed from the buffer\n      if (marker.line < 0) {\n        marker.dispose();\n      }\n    }));\n    marker.register(this.lines.onInsert(event => {\n      if (marker.line >= event.index) {\n        marker.line += event.amount;\n      }\n    }));\n    marker.register(this.lines.onDelete(event => {\n      // Delete the marker if it's within the range\n      if (marker.line >= event.index && marker.line < event.index + event.amount) {\n        marker.dispose();\n      }\n\n      // Shift the marker if it's after the deleted range\n      if (marker.line > event.index) {\n        marker.line -= event.amount;\n      }\n    }));\n    marker.register(marker.onDispose(() => this._removeMarker(marker)));\n    return marker;\n  }\n\n  private _removeMarker(marker: Marker): void {\n    this.markers.splice(this.markers.indexOf(marker), 1);\n  }\n\n  public iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator {\n    return new BufferStringIterator(this, trimRight, startIndex, endIndex, startOverscan, endOverscan);\n  }\n}\n\n/**\n * Iterator to get unwrapped content strings from the buffer.\n * The iterator returns at least the string data between the borders\n * `startIndex` and `endIndex` (exclusive) and will expand the lines\n * by `startOverscan` to the top and by `endOverscan` to the bottom,\n * if no new line was found in between.\n * It will never read/return string data beyond `startIndex - startOverscan`\n * or `endIndex + endOverscan`. Therefore the first and last line might be truncated.\n * It is possible to always get the full string for the first and last line as well\n * by setting the overscan values to the actual buffer length. This not recommended\n * since it might return the whole buffer within a single string in a worst case scenario.\n */\nexport class BufferStringIterator implements IBufferStringIterator {\n  private _current: number;\n\n  constructor (\n    private _buffer: IBuffer,\n    private _trimRight: boolean,\n    private _startIndex: number = 0,\n    private _endIndex: number = _buffer.lines.length,\n    private _startOverscan: number = 0,\n    private _endOverscan: number = 0\n  ) {\n    if (this._startIndex < 0) {\n      this._startIndex = 0;\n    }\n    if (this._endIndex > this._buffer.lines.length) {\n      this._endIndex = this._buffer.lines.length;\n    }\n    this._current = this._startIndex;\n  }\n\n  public hasNext(): boolean {\n    return this._current < this._endIndex;\n  }\n\n  public next(): IBufferStringIteratorResult {\n    const range = this._buffer.getWrappedRangeForLine(this._current);\n    // limit search window to overscan value at both borders\n    if (range.first < this._startIndex - this._startOverscan) {\n      range.first = this._startIndex - this._startOverscan;\n    }\n    if (range.last > this._endIndex + this._endOverscan) {\n      range.last = this._endIndex + this._endOverscan;\n    }\n    // limit to current buffer length\n    range.first = Math.max(range.first, 0);\n    range.last = Math.min(range.last, this._buffer.lines.length);\n    let result = '';\n    for (let i = range.first; i <= range.last; ++i) {\n      result += this._buffer.translateBufferLineToString(i, this._trimRight);\n    }\n    this._current = range.last + 1;\n    return {range: range, content: result};\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICircularList } from 'common/Types';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\n\nexport interface IInsertEvent {\n  index: number;\n  amount: number;\n}\n\nexport interface IDeleteEvent {\n  index: number;\n  amount: number;\n}\n\n/**\n * Represents a circular list; a list with a maximum size that wraps around when push is called,\n * overriding values at the start of the list.\n */\nexport class CircularList<T> implements ICircularList<T> {\n  protected _array: (T | undefined)[];\n  private _startIndex: number;\n  private _length: number;\n\n  public onDeleteEmitter = new EventEmitter<IDeleteEvent>();\n  public get onDelete(): IEvent<IDeleteEvent> { return this.onDeleteEmitter.event; }\n  public onInsertEmitter = new EventEmitter<IInsertEvent>();\n  public get onInsert(): IEvent<IInsertEvent> { return this.onInsertEmitter.event; }\n  public onTrimEmitter = new EventEmitter<number>();\n  public get onTrim(): IEvent<number> { return this.onTrimEmitter.event; }\n\n  constructor(\n    private _maxLength: number\n  ) {\n    this._array = new Array<T>(this._maxLength);\n    this._startIndex = 0;\n    this._length = 0;\n  }\n\n  public get maxLength(): number {\n    return this._maxLength;\n  }\n\n  public set maxLength(newMaxLength: number) {\n    // There was no change in maxLength, return early.\n    if (this._maxLength === newMaxLength) {\n      return;\n    }\n\n    // Reconstruct array, starting at index 0. Only transfer values from the\n    // indexes 0 to length.\n    const newArray = new Array<T | undefined>(newMaxLength);\n    for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {\n      newArray[i] = this._array[this._getCyclicIndex(i)];\n    }\n    this._array = newArray;\n    this._maxLength = newMaxLength;\n    this._startIndex = 0;\n  }\n\n  public get length(): number {\n    return this._length;\n  }\n\n  public set length(newLength: number) {\n    if (newLength > this._length) {\n      for (let i = this._length; i < newLength; i++) {\n        this._array[i] = undefined;\n      }\n    }\n    this._length = newLength;\n  }\n\n  /**\n   * Gets the value at an index.\n   *\n   * Note that for performance reasons there is no bounds checking here, the index reference is\n   * circular so this should always return a value and never throw.\n   * @param index The index of the value to get.\n   * @return The value corresponding to the index.\n   */\n  public get(index: number): T | undefined {\n    return this._array[this._getCyclicIndex(index)];\n  }\n\n  /**\n   * Sets the value at an index.\n   *\n   * Note that for performance reasons there is no bounds checking here, the index reference is\n   * circular so this should always return a value and never throw.\n   * @param index The index to set.\n   * @param value The value to set.\n   */\n  public set(index: number, value: T | undefined): void {\n    this._array[this._getCyclicIndex(index)] = value;\n  }\n\n  /**\n   * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0\n   * if the maximum length is reached.\n   * @param value The value to push onto the list.\n   */\n  public push(value: T): void {\n    this._array[this._getCyclicIndex(this._length)] = value;\n    if (this._length === this._maxLength) {\n      this._startIndex = ++this._startIndex % this._maxLength;\n      this.onTrimEmitter.fire(1);\n    } else {\n      this._length++;\n    }\n  }\n\n  /**\n   * Advance ringbuffer index and return current element for recycling.\n   * Note: The buffer must be full for this method to work.\n   * @throws When the buffer is not full.\n   */\n  public recycle(): T {\n    if (this._length !== this._maxLength) {\n      throw new Error('Can only recycle when the buffer is full');\n    }\n    this._startIndex = ++this._startIndex % this._maxLength;\n    this.onTrimEmitter.fire(1);\n    return this._array[this._getCyclicIndex(this._length - 1)]!;\n  }\n\n  /**\n   * Ringbuffer is at max length.\n   */\n  public get isFull(): boolean {\n    return this._length === this._maxLength;\n  }\n\n  /**\n   * Removes and returns the last value on the list.\n   * @return The popped value.\n   */\n  public pop(): T | undefined {\n    return this._array[this._getCyclicIndex(this._length-- - 1)];\n  }\n\n  /**\n   * Deletes and/or inserts items at a particular index (in that order). Unlike\n   * Array.prototype.splice, this operation does not return the deleted items as a new array in\n   * order to save creating a new array. Note that this operation may shift all values in the list\n   * in the worst case.\n   * @param start The index to delete and/or insert.\n   * @param deleteCount The number of elements to delete.\n   * @param items The items to insert.\n   */\n  public splice(start: number, deleteCount: number, ...items: T[]): void {\n    // Delete items\n    if (deleteCount) {\n      for (let i = start; i < this._length - deleteCount; i++) {\n        this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];\n      }\n      this._length -= deleteCount;\n    }\n\n    // Add items\n    for (let i = this._length - 1; i >= start; i--) {\n      this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];\n    }\n    for (let i = 0; i < items.length; i++) {\n      this._array[this._getCyclicIndex(start + i)] = items[i];\n    }\n\n    // Adjust length as needed\n    if (this._length + items.length > this._maxLength) {\n      const countToTrim = (this._length + items.length) - this._maxLength;\n      this._startIndex += countToTrim;\n      this._length = this._maxLength;\n      this.onTrimEmitter.fire(countToTrim);\n    } else {\n      this._length += items.length;\n    }\n  }\n\n  /**\n   * Trims a number of items from the start of the list.\n   * @param count The number of items to remove.\n   */\n  public trimStart(count: number): void {\n    if (count > this._length) {\n      count = this._length;\n    }\n    this._startIndex += count;\n    this._length -= count;\n    this.onTrimEmitter.fire(count);\n  }\n\n  public shiftElements(start: number, count: number, offset: number): void {\n    if (count <= 0) {\n      return;\n    }\n    if (start < 0 || start >= this._length) {\n      throw new Error('start argument out of range');\n    }\n    if (start + offset < 0) {\n      throw new Error('Cannot shift elements in list beyond index 0');\n    }\n\n    if (offset > 0) {\n      for (let i = count - 1; i >= 0; i--) {\n        this.set(start + i + offset, this.get(start + i));\n      }\n      const expandListBy = (start + count + offset) - this._length;\n      if (expandListBy > 0) {\n        this._length += expandListBy;\n        while (this._length > this._maxLength) {\n          this._length--;\n          this._startIndex++;\n          this.onTrimEmitter.fire(1);\n        }\n      }\n    } else {\n      for (let i = 0; i < count; i++) {\n        this.set(start + i + offset, this.get(start + i));\n      }\n    }\n  }\n\n  /**\n   * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the\n   * backing array to get the element associated with the regular index.\n   * @param index The regular index.\n   * @returns The cyclic index.\n   */\n  private _getCyclicIndex(index: number): number {\n    return (this._startIndex + index) % this._maxLength;\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { BufferLine } from 'common/buffer/BufferLine';\nimport { CircularList } from 'common/CircularList';\nimport { IBufferLine, ICellData } from 'common/Types';\n\nexport interface INewLayoutResult {\n  layout: number[];\n  countRemoved: number;\n}\n\n/**\n * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed\n * when a wrapped line unwraps.\n * @param lines The buffer lines.\n * @param newCols The columns after resize.\n */\nexport function reflowLargerGetLinesToRemove(lines: CircularList<IBufferLine>, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData): number[] {\n  // Gather all BufferLines that need to be removed from the Buffer here so that they can be\n  // batched up and only committed once\n  const toRemove: number[] = [];\n\n  for (let y = 0; y < lines.length - 1; y++) {\n    // Check if this row is wrapped\n    let i = y;\n    let nextLine = lines.get(++i) as BufferLine;\n    if (!nextLine.isWrapped) {\n      continue;\n    }\n\n    // Check how many lines it's wrapped for\n    const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine];\n    while (i < lines.length && nextLine.isWrapped) {\n      wrappedLines.push(nextLine);\n      nextLine = lines.get(++i) as BufferLine;\n    }\n\n    // If these lines contain the cursor don't touch them, the program will handle fixing up wrapped\n    // lines with the cursor\n    if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {\n      y += wrappedLines.length - 1;\n      continue;\n    }\n\n    // Copy buffer data to new locations\n    let destLineIndex = 0;\n    let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols);\n    let srcLineIndex = 1;\n    let srcCol = 0;\n    while (srcLineIndex < wrappedLines.length) {\n      const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols);\n      const srcRemainingCells = srcTrimmedTineLength - srcCol;\n      const destRemainingCells = newCols - destCol;\n      const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells);\n\n      wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false);\n\n      destCol += cellsToCopy;\n      if (destCol === newCols) {\n        destLineIndex++;\n        destCol = 0;\n      }\n      srcCol += cellsToCopy;\n      if (srcCol === srcTrimmedTineLength) {\n        srcLineIndex++;\n        srcCol = 0;\n      }\n\n      // Make sure the last cell isn't wide, if it is copy it to the current dest\n      if (destCol === 0 && destLineIndex !== 0) {\n        if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) {\n          wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false);\n          // Null out the end of the last row\n          wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell);\n        }\n      }\n    }\n\n    // Clear out remaining cells or fragments could remain;\n    wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell);\n\n    // Work backwards and remove any rows at the end that only contain null cells\n    let countToRemove = 0;\n    for (let i = wrappedLines.length - 1; i > 0; i--) {\n      if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) {\n        countToRemove++;\n      } else {\n        break;\n      }\n    }\n\n    if (countToRemove > 0) {\n      toRemove.push(y + wrappedLines.length - countToRemove); // index\n      toRemove.push(countToRemove);\n    }\n\n    y += wrappedLines.length - 1;\n  }\n  return toRemove;\n}\n\n/**\n * Creates and return the new layout for lines given an array of indexes to be removed.\n * @param lines The buffer lines.\n * @param toRemove The indexes to remove.\n */\nexport function reflowLargerCreateNewLayout(lines: CircularList<IBufferLine>, toRemove: number[]): INewLayoutResult {\n  const layout: number[] = [];\n  // First iterate through the list and get the actual indexes to use for rows\n  let nextToRemoveIndex = 0;\n  let nextToRemoveStart = toRemove[nextToRemoveIndex];\n  let countRemovedSoFar = 0;\n  for (let i = 0; i < lines.length; i++) {\n    if (nextToRemoveStart === i) {\n      const countToRemove = toRemove[++nextToRemoveIndex];\n\n      // Tell markers that there was a deletion\n      lines.onDeleteEmitter.fire({\n        index: i - countRemovedSoFar,\n        amount: countToRemove\n      });\n\n      i += countToRemove - 1;\n      countRemovedSoFar += countToRemove;\n      nextToRemoveStart = toRemove[++nextToRemoveIndex];\n    } else {\n      layout.push(i);\n    }\n  }\n  return {\n    layout,\n    countRemoved: countRemovedSoFar\n  };\n}\n\n/**\n * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's\n * done all at once in a single iteration through the list since splice is very expensive.\n * @param lines The buffer lines.\n * @param newLayout The new layout to apply.\n */\nexport function reflowLargerApplyNewLayout(lines: CircularList<IBufferLine>, newLayout: number[]): void {\n  // Record original lines so they don't get overridden when we rearrange the list\n  const newLayoutLines: BufferLine[] = [];\n  for (let i = 0; i < newLayout.length; i++) {\n    newLayoutLines.push(lines.get(newLayout[i]) as BufferLine);\n  }\n\n  // Rearrange the list\n  for (let i = 0; i < newLayoutLines.length; i++) {\n    lines.set(i, newLayoutLines[i]);\n  }\n  lines.length = newLayout.length;\n}\n\n/**\n * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-\n * compute the wrapping points since wide characters may need to be wrapped onto the following line.\n * This function will return an array of numbers of where each line wraps to, the resulting array\n * will only contain the values `newCols` (when the line does not end with a wide character) and\n * `newCols - 1` (when the line does end with a wide character), except for the last value which\n * will contain the remaining items to fill the line.\n *\n * Calling this with a `newCols` value of `1` will lock up.\n *\n * @param wrappedLines The wrapped lines to evaluate.\n * @param oldCols The columns before resize.\n * @param newCols The columns after resize.\n */\nexport function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] {\n  const newLineLengths: number[] = [];\n  const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c);\n\n  // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and\n  // linesNeeded\n  let srcCol = 0;\n  let srcLine = 0;\n  let cellsAvailable = 0;\n  while (cellsAvailable < cellsNeeded) {\n    if (cellsNeeded - cellsAvailable < newCols) {\n      // Add the final line and exit the loop\n      newLineLengths.push(cellsNeeded - cellsAvailable);\n      break;\n    }\n    srcCol += newCols;\n    const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols);\n    if (srcCol > oldTrimmedLength) {\n      srcCol -= oldTrimmedLength;\n      srcLine++;\n    }\n    const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2;\n    if (endsWithWide) {\n      srcCol--;\n    }\n    const lineLength = endsWithWide ? newCols - 1 : newCols;\n    newLineLengths.push(lineLength);\n    cellsAvailable += lineLength;\n  }\n\n  return newLineLengths;\n}\n\nexport function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number {\n  // If this is the last row in the wrapped line, get the actual trimmed length\n  if (i === lines.length - 1) {\n    return lines[i].getTrimmedLength();\n  }\n  // Detect whether the following line starts with a wide character and the end of the current line\n  // is null, if so then we can be pretty sure the null character should be excluded from the line\n  // length]\n  const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1;\n  const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2;\n  if (endsInNull && followingLineStartsWithWide) {\n    return cols - 1;\n  }\n  return cols;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { Disposable } from 'common/Lifecycle';\nimport { IMarker } from 'common/Types';\n\nexport class Marker extends Disposable implements IMarker {\n  private static _nextId = 1;\n\n  private _id: number = Marker._nextId++;\n  public isDisposed: boolean = false;\n\n  public get id(): number { return this._id; }\n\n  private _onDispose = new EventEmitter<void>();\n  public get onDispose(): IEvent<void> { return this._onDispose.event; }\n\n  constructor(\n    public line: number\n  ) {\n    super();\n  }\n\n  public dispose(): void {\n    if (this.isDisposed) {\n      return;\n    }\n    this.isDisposed = true;\n    this.line = -1;\n    // Emit before super.dispose such that dispose listeners get a change to react\n    this._onDispose.fire();\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharSizeService, IRenderService, IMouseService } from './Services';\nimport { getCoords, getRawByteCoords } from 'browser/input/Mouse';\n\nexport class MouseService implements IMouseService {\n  serviceBrand: any;\n\n  constructor(\n    @IRenderService private readonly _renderService: IRenderService,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService\n  ) {\n  }\n\n  public getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined {\n    return getCoords(\n      event,\n      element,\n      colCount,\n      rowCount,\n      this._charSizeService.hasValidSize,\n      this._renderService.dimensions.actualCellWidth,\n      this._renderService.dimensions.actualCellHeight,\n      isSelection\n    );\n  }\n\n  public getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined {\n    const coords = this.getCoords(event, element, colCount, rowCount);\n    return getRawByteCoords(coords);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreService, ILogService, IOptionsService, IBufferService } from 'common/services/Services';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { IDecPrivateModes } from 'common/Types';\nimport { clone } from 'common/Clone';\n\nconst DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({\n  applicationCursorKeys: false\n});\n\nexport class CoreService implements ICoreService {\n  serviceBrand: any;\n\n  public decPrivateModes: IDecPrivateModes;\n\n  private _onData = new EventEmitter<string>();\n  public get onData(): IEvent<string> { return this._onData.event; }\n  private _onUserInput = new EventEmitter<void>();\n  public get onUserInput(): IEvent<void> { return this._onUserInput.event; }\n\n  constructor(\n    // TODO: Move this into a service\n    private readonly _scrollToBottom: () => void,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @ILogService private readonly _logService: ILogService,\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n  }\n\n  public reset(): void {\n    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n  }\n\n  public triggerDataEvent(data: string, wasUserInput: boolean = false): void {\n    // Prevents all events to pty process if stdin is disabled\n    if (this._optionsService.options.disableStdin) {\n      return;\n    }\n\n    // Input is being sent to the terminal, the terminal should focus the prompt.\n    const buffer = this._bufferService.buffer;\n    if (buffer.ybase !== buffer.ydisp) {\n      this._scrollToBottom();\n    }\n\n    // Fire onUserInput so listeners can react as well (eg. clear selection)\n    if (wasUserInput) {\n      this._onUserInput.fire();\n    }\n\n    // Fire onData API\n    this._logService.debug(`sending data \"${data}\"`, () => data.split('').map(e => e.charCodeAt(0)));\n    this._onData.fire(data);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ILogService, IOptionsService } from 'common/services/Services';\n\ntype LogType = (message?: any, ...optionalParams: any[]) => void;\n\ninterface IConsole {\n  log: LogType;\n  error: LogType;\n  info: LogType;\n  trace: LogType;\n  warn: LogType;\n}\n\n// console is available on both node.js and browser contexts but the common\n// module doesn't depend on them so we need to explicitly declare it.\ndeclare const console: IConsole;\n\n\nexport enum LogLevel {\n  DEBUG = 0,\n  INFO = 1,\n  WARN = 2,\n  ERROR = 3,\n  OFF = 4\n}\n\nconst optionsKeyToLogLevel: { [key: string]: LogLevel } = {\n  debug: LogLevel.DEBUG,\n  info: LogLevel.INFO,\n  warn: LogLevel.WARN,\n  error: LogLevel.ERROR,\n  off: LogLevel.OFF\n};\n\nconst LOG_PREFIX = 'xterm.js: ';\n\nexport class LogService implements ILogService {\n  serviceBrand: any;\n\n  private _logLevel!: LogLevel;\n\n  constructor(\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    this._updateLogLevel();\n    this._optionsService.onOptionChange(key => {\n      if (key === 'logLevel') {\n        this._updateLogLevel();\n      }\n    });\n  }\n\n  private _updateLogLevel(): void {\n    this._logLevel = optionsKeyToLogLevel[this._optionsService.options.logLevel];\n  }\n\n  private _evalLazyOptionalParams(optionalParams: any[]): void {\n    for (let i = 0; i < optionalParams.length; i++) {\n      if (typeof optionalParams[i] === 'function') {\n        optionalParams[i] = optionalParams[i]();\n      }\n    }\n  }\n\n  private _log(type: LogType, message: string, optionalParams: any[]): void {\n    this._evalLazyOptionalParams(optionalParams);\n    type.call(console, LOG_PREFIX + message, ...optionalParams);\n  }\n\n  debug(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.DEBUG) {\n      this._log(console.log, message, optionalParams);\n    }\n  }\n\n  info(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.INFO) {\n      this._log(console.info, message, optionalParams);\n    }\n  }\n\n  warn(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.WARN) {\n      this._log(console.warn, message, optionalParams);\n    }\n  }\n\n  error(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.ERROR) {\n      this._log(console.error, message, optionalParams);\n    }\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService, IDirtyRowService } from 'common/services/Services';\n\nexport class DirtyRowService implements IDirtyRowService {\n  serviceBrand: any;\n\n  private _start!: number;\n  private _end!: number;\n\n  public get start(): number { return this._start; }\n  public get end(): number { return this._end; }\n\n  constructor(\n    @IBufferService private readonly _bufferService: IBufferService\n  ) {\n    this.clearRange();\n  }\n\n  public clearRange(): void {\n    this._start = this._bufferService.buffer.y;\n    this._end = this._bufferService.buffer.y;\n  }\n\n  public markDirty(y: number): void {\n    if (y < this._start) {\n      this._start = y;\n    } else if (y > this._end) {\n      this._end = y;\n    }\n  }\n\n  public markRangeDirty(y1: number, y2: number): void {\n    if (y1 > y2) {\n      const temp = y1;\n      y1 = y2;\n      y2 = temp;\n    }\n    if (y1 < this._start) {\n      this._start = y1;\n    }\n    if (y2 > this._end) {\n      this._end = y2;\n    }\n  }\n\n  public markAllDirty(): void {\n    this.markRangeDirty(0, this._bufferService.rows - 1);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IInstantiationService, IServiceIdentifier } from 'common/services/Services';\nimport { getServiceDependencies } from 'common/services/ServiceRegistry';\n\nexport class ServiceCollection {\n\n  private _entries = new Map<IServiceIdentifier<any>, any>();\n\n  constructor(...entries: [IServiceIdentifier<any>, any][]) {\n    for (const [id, service] of entries) {\n      this.set(id, service);\n    }\n  }\n\n  set<T>(id: IServiceIdentifier<T>, instance: T): T {\n    const result = this._entries.get(id);\n    this._entries.set(id, instance);\n    return result;\n  }\n\n  forEach(callback: (id: IServiceIdentifier<any>, instance: any) => any): void {\n    this._entries.forEach((value, key) => callback(key, value));\n  }\n\n  has(id: IServiceIdentifier<any>): boolean {\n    return this._entries.has(id);\n  }\n\n  get<T>(id: IServiceIdentifier<T>): T {\n    return this._entries.get(id);\n  }\n}\n\nexport class InstantiationService implements IInstantiationService {\n  private readonly _services: ServiceCollection = new ServiceCollection();\n\n  constructor() {\n    this._services.set(IInstantiationService, this);\n  }\n\n  public setService<T>(id: IServiceIdentifier<T>, instance: T): void {\n    this._services.set(id, instance);\n  }\n\n  public createInstance<T>(ctor: any, ...args: any[]): any {\n    const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index);\n\n    const serviceArgs: any[] = [];\n    for (const dependency of serviceDependencies) {\n      const service = this._services.get(dependency.id);\n      if (!service) {\n        throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`);\n      }\n      serviceArgs.push(service);\n    }\n\n    const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;\n\n    // check for argument mismatches, adjust static args if needed\n    if (args.length !== firstServiceArgPos) {\n      throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);\n    }\n\n    // now create the instance\n    return <T>new ctor(...[...args, ...serviceArgs]);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IBufferService, ICoreService, ICoreMouseService } from 'common/services/Services';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';\n\n/**\n * Supported default protocols.\n */\nconst DEFAULT_PROTOCOLS: {[key: string]: ICoreMouseProtocol} = {\n  /**\n   * NONE\n   * Events: none\n   * Modifiers: none\n   */\n  NONE: {\n    events: CoreMouseEventType.NONE,\n    restrict: () => false\n  },\n  /**\n   * X10\n   * Events: mousedown\n   * Modifiers: none\n   */\n  X10: {\n    events: CoreMouseEventType.DOWN,\n    restrict: (e: ICoreMouseEvent) => {\n      // no wheel, no move, no up\n      if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) {\n        return false;\n      }\n      // no modifiers\n      e.ctrl = false;\n      e.alt = false;\n      e.shift = false;\n      return true;\n    }\n  },\n  /**\n   * VT200\n   * Events: mousedown / mouseup / wheel\n   * Modifiers: all\n   */\n  VT200: {\n    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL,\n    restrict: (e: ICoreMouseEvent) => {\n      // no move\n      if (e.action === CoreMouseAction.MOVE) {\n        return false;\n      }\n      return true;\n    }\n  },\n  /**\n   * DRAG\n   * Events: mousedown / mouseup / wheel / mousedrag\n   * Modifiers: all\n   */\n  DRAG: {\n    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG,\n    restrict: (e: ICoreMouseEvent) => {\n      // no move without button\n      if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) {\n        return false;\n      }\n      return true;\n    }\n  },\n  /**\n   * ANY\n   * Events: all mouse related events\n   * Modifiers: all\n   */\n  ANY: {\n    events:\n      CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL\n      | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE,\n    restrict: (e: ICoreMouseEvent) => true\n  }\n};\n\nconst enum Modifiers {\n  SHIFT = 4,\n  ALT = 8,\n  CTRL = 16\n}\n\n// helper for default encoders to generate the event code.\nfunction eventCode(e: ICoreMouseEvent, isSGR: boolean): number {\n  let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0);\n  if (e.button === CoreMouseButton.WHEEL) {\n    code |= 64;\n    code |= e.action;\n  } else {\n    code |= e.button & 3;\n    if (e.button & 4) {\n      code |= 64;\n    }\n    if (e.button & 8) {\n      code |= 128;\n    }\n    if (e.action === CoreMouseAction.MOVE) {\n      code |= CoreMouseAction.MOVE;\n    } else if (e.action === CoreMouseAction.UP && !isSGR) {\n      // special case - only SGR can report button on release\n      // all others have to go with NONE\n      code |= CoreMouseButton.NONE;\n    }\n  }\n  return code;\n}\n\nconst S = String.fromCharCode;\n\n/**\n * Supported default encodings.\n */\nconst DEFAULT_ENCODINGS: {[key: string]: CoreMouseEncoding} = {\n  /**\n   * DEFAULT - CSI M Pb Px Py\n   * Single byte encoding for coords and event code.\n   * Can encode values up to 223. The Encoding of higher\n   * values is not UTF-8 compatible (and currently limited\n   * to 95 in xterm.js).\n   */\n  DEFAULT: (e: ICoreMouseEvent) => {\n    let params = [eventCode(e, false) + 32, e.col + 32, e.row + 32];\n    // FIXME: we are currently limited to ASCII range\n    params = params.map(v => (v > 127) ? 127 : v);\n    // FIXED: params = params.map(v => (v > 255) ? 0 : value);\n    return `\\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`;\n  },\n  /**\n   * SGR - CSI < Pb ; Px ; Py M|m\n   * No encoding limitation.\n   * Can report button on release and works with a well formed sequence.\n   */\n  SGR: (e: ICoreMouseEvent) => {\n    const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';\n    return `\\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`;\n  }\n};\n\n/**\n * CoreMouseService\n *\n * Provides mouse tracking reports with different protocols and encodings.\n *  - protocols: NONE (default), X10, VT200, DRAG, ANY\n *  - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507)\n *\n * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`.\n * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`.\n * Switching a protocol will send a notification event `onProtocolChange`\n * with a list of needed events to track.\n *\n * The service handles the mouse tracking state and decides whether to send\n * a tracking report to the backend based on protocol and encoding limitations.\n * To send a mouse event call `triggerMouseEvent`.\n */\nexport class CoreMouseService implements ICoreMouseService {\n  private _protocols: {[name: string]: ICoreMouseProtocol} = {};\n  private _encodings: {[name: string]: CoreMouseEncoding} = {};\n  private _activeProtocol: string = '';\n  private _activeEncoding: string = '';\n  private _onProtocolChange = new EventEmitter<CoreMouseEventType>();\n  private _lastEvent: ICoreMouseEvent | null = null;\n\n  constructor(\n    @IBufferService private readonly _bufferService: IBufferService,\n    @ICoreService private readonly _coreService: ICoreService\n  ) {\n    // register default protocols and encodings\n    Object.keys(DEFAULT_PROTOCOLS).forEach(name => this.addProtocol(name, DEFAULT_PROTOCOLS[name]));\n    Object.keys(DEFAULT_ENCODINGS).forEach(name => this.addEncoding(name, DEFAULT_ENCODINGS[name]));\n    // call reset to set defaults\n    this.reset();\n  }\n\n  public addProtocol(name: string, protocol: ICoreMouseProtocol): void {\n    this._protocols[name] = protocol;\n  }\n\n  public addEncoding(name: string, encoding: CoreMouseEncoding): void {\n    this._encodings[name] = encoding;\n  }\n\n  public get activeProtocol(): string {\n    return this._activeProtocol;\n  }\n\n  public set activeProtocol(name: string) {\n    if (!this._protocols[name]) {\n      throw new Error(`unknown protocol \"${name}\"`);\n    }\n    this._activeProtocol = name;\n    this._onProtocolChange.fire(this._protocols[name].events);\n  }\n\n  public get activeEncoding(): string {\n    return this._activeEncoding;\n  }\n\n  public set activeEncoding(name: string) {\n    if (!this._encodings[name]) {\n      throw new Error(`unknown encoding \"${name}\"`);\n    }\n    this._activeEncoding = name;\n  }\n\n  public reset(): void {\n    this.activeProtocol = 'NONE';\n    this.activeEncoding = 'DEFAULT';\n    this._lastEvent = null;\n  }\n\n  /**\n   * Event to announce changes in mouse tracking.\n   */\n  public get onProtocolChange(): IEvent<CoreMouseEventType> {\n    return this._onProtocolChange.event;\n  }\n\n  /**\n   * Triggers a mouse event to be sent.\n   *\n   * Returns true if the event passed all protocol restrictions and a report\n   * was sent, otherwise false. The return value may be used to decide whether\n   * the default event action in the bowser component should be omitted.\n   *\n   * Note: The method will change values of the given event object\n   * to fullfill protocol and encoding restrictions.\n   */\n  public triggerMouseEvent(e: ICoreMouseEvent): boolean {\n    // range check for col/row\n    if (e.col < 0 || e.col >= this._bufferService.cols\n        || e.row < 0 || e.row >= this._bufferService.rows) {\n      return false;\n    }\n\n    // filter nonsense combinations of button + action\n    if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) {\n      return false;\n    }\n    if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) {\n      return false;\n    }\n    if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) {\n      return false;\n    }\n\n    // report 1-based coords\n    e.col++;\n    e.row++;\n\n    // debounce move at grid level\n    if (e.action === CoreMouseAction.MOVE && this._lastEvent && this._compareEvents(this._lastEvent, e)) {\n      return false;\n    }\n\n    // apply protocol restrictions\n    if (!this._protocols[this._activeProtocol].restrict(e)) {\n      return false;\n    }\n\n    // encode report and send\n    const report = this._encodings[this._activeEncoding](e);\n    this._coreService.triggerDataEvent(report, true);\n\n    this._lastEvent = e;\n\n    return true;\n  }\n\n  public explainEvents(events: CoreMouseEventType): {[event: string]: boolean} {\n    return {\n      DOWN: !!(events & CoreMouseEventType.DOWN),\n      UP: !!(events & CoreMouseEventType.UP),\n      DRAG: !!(events & CoreMouseEventType.DRAG),\n      MOVE: !!(events & CoreMouseEventType.MOVE),\n      WHEEL: !!(events & CoreMouseEventType.WHEEL)\n    };\n  }\n\n  private _compareEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent): boolean {\n    if (e1.col !== e2.col) return false;\n    if (e1.row !== e2.row) return false;\n    if (e1.button !== e2.button) return false;\n    if (e1.action !== e2.action) return false;\n    if (e1.ctrl !== e2.ctrl) return false;\n    if (e1.alt !== e2.alt) return false;\n    if (e1.shift !== e2.shift) return false;\n    return true;\n  }\n}\n","\n/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ndeclare const setTimeout: (handler: () => void, timeout?: number) => void;\n\n/**\n * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input.\n * Enable flow control to avoid this limit and make sure that your backend correctly\n * propagates this to the underlying pty. (see docs for further instructions)\n * Since this limit is meant as a safety parachute to prevent browser crashs,\n * it is set to a very high number. Typically xterm.js gets unresponsive with\n * a 100 times lower number (>500 kB).\n */\nconst DISCARD_WATERMARK = 50000000; // ~50 MB\n\n/**\n * The max number of ms to spend on writes before allowing the renderer to\n * catch up with a 0ms setTimeout. A value of < 33 to keep us close to\n * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS\n * depends on the time it takes for the renderer to draw the frame.\n */\nconst WRITE_TIMEOUT_MS = 12;\n\n/**\n * Threshold of max held chunks in the write buffer, that were already processed.\n * This is a tradeoff between extensive write buffer shifts (bad runtime) and high\n * memory consumption by data thats not used anymore.\n */\nconst WRITE_BUFFER_LENGTH_THRESHOLD = 50;\n\nexport class WriteBuffer {\n  private _writeBuffer: (string | Uint8Array)[] = [];\n  private _callbacks: ((() => void) | undefined)[] = [];\n  private _pendingData = 0;\n  private _bufferOffset = 0;\n\n  constructor(private _action: (data: string | Uint8Array) => void) { }\n\n  public writeSync(data: string | Uint8Array): void {\n    // force sync processing on pending data chunks to avoid in-band data scrambling\n    // does the same as innerWrite but without event loop\n    if (this._writeBuffer.length) {\n      for (let i = this._bufferOffset; i < this._writeBuffer.length; ++i) {\n        const data = this._writeBuffer[i];\n        const cb = this._callbacks[i];\n        this._action(data);\n        if (cb) cb();\n      }\n      // reset all to avoid reprocessing of chunks with scheduled innerWrite call\n      this._writeBuffer = [];\n      this._callbacks = [];\n      this._pendingData = 0;\n      // stop scheduled innerWrite by offset > length condition\n      this._bufferOffset = 0x7FFFFFFF;\n    }\n    // handle current data chunk\n    this._action(data);\n  }\n\n  public write(data: string | Uint8Array, callback?: () => void): void {\n    if (this._pendingData > DISCARD_WATERMARK) {\n      throw new Error('write data discarded, use flow control to avoid losing data');\n    }\n\n    // schedule chunk processing for next event loop run\n    if (!this._writeBuffer.length) {\n      this._bufferOffset = 0;\n      setTimeout(() => this._innerWrite());\n    }\n\n    this._pendingData += data.length;\n    this._writeBuffer.push(data);\n    this._callbacks.push(callback);\n  }\n\n  protected _innerWrite(): void {\n    const startTime = Date.now();\n    while (this._writeBuffer.length > this._bufferOffset) {\n      const data = this._writeBuffer[this._bufferOffset];\n      const cb = this._callbacks[this._bufferOffset];\n      this._bufferOffset++;\n\n      this._action(data);\n      this._pendingData -= data.length;\n      if (cb) cb();\n\n      if (Date.now() - startTime >= WRITE_TIMEOUT_MS) {\n        break;\n      }\n    }\n    if (this._writeBuffer.length > this._bufferOffset) {\n      // Allow renderer to catch up before processing the next batch\n      // trim already processed chunks if we are above threshold\n      if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) {\n        this._writeBuffer = this._writeBuffer.slice(this._bufferOffset);\n        this._callbacks = this._callbacks.slice(this._bufferOffset);\n        this._bufferOffset = 0;\n      }\n      setTimeout(() => this._innerWrite(), 0);\n    } else {\n      this._writeBuffer = [];\n      this._callbacks = [];\n      this._pendingData = 0;\n      this._bufferOffset = 0;\n    }\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ITerminalAddon, IDisposable, Terminal } from 'xterm';\n\nexport interface ILoadedAddon {\n  instance: ITerminalAddon;\n  dispose: () => void;\n  isDisposed: boolean;\n}\n\nexport class AddonManager implements IDisposable {\n  protected _addons: ILoadedAddon[] = [];\n\n  constructor() {\n  }\n\n  public dispose(): void {\n    for (let i = this._addons.length - 1; i >= 0; i--) {\n      this._addons[i].instance.dispose();\n    }\n  }\n\n  public loadAddon(terminal: Terminal, instance: ITerminalAddon): void {\n    const loadedAddon: ILoadedAddon = {\n      instance,\n      dispose: instance.dispose,\n      isDisposed: false\n    };\n    this._addons.push(loadedAddon);\n    instance.dispose = () => this._wrappedAddonDispose(loadedAddon);\n    instance.activate(<any>terminal);\n  }\n\n  private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void {\n    if (loadedAddon.isDisposed) {\n      // Do nothing if already disposed\n      return;\n    }\n    let index = -1;\n    for (let i = 0; i < this._addons.length; i++) {\n      if (this._addons[i] === loadedAddon) {\n        index = i;\n        break;\n      }\n    }\n    if (index === -1) {\n      throw new Error('Could not dispose an addon that has not been loaded');\n    }\n    loadedAddon.isDisposed = true;\n    loadedAddon.dispose.apply(loadedAddon.instance);\n    this._addons.splice(index, 1);\n  }\n}\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/node_modules/xterm/package.json b/node_modules/xterm/package.json
new file mode 100644 (file)
index 0000000..1a629e7
--- /dev/null
@@ -0,0 +1,99 @@
+{
+  "name": "xterm",
+  "description": "Full xterm terminal, in your browser",
+  "version": "4.2.0",
+  "main": "lib/xterm.js",
+  "style": "css/xterm.css",
+  "types": "typings/xterm.d.ts",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/xtermjs/xterm.js.git"
+  },
+  "license": "MIT",
+  "scripts": {
+    "prepackage": "npm run build",
+    "package": "webpack",
+    "start": "node demo/start",
+    "lint": "tslint 'src/**/*.ts' 'addons/**/*.ts'",
+    "test": "npm run test-unit",
+    "posttest": "npm run lint",
+    "test-api": "mocha \"**/*.api.js\"",
+    "test-unit": "node ./bin/test.js",
+    "build": "tsc -b ./tsconfig.all.json",
+    "prepare": "npm run build",
+    "prepublishOnly": "npm run package",
+    "watch": "tsc -b -w ./tsconfig.all.json --preserveWatchOutput",
+    "benchmark": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json",
+    "benchmark-baseline": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --baseline out-test/benchmark/test/benchmark/*benchmark.js",
+    "benchmark-eval": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --eval out-test/benchmark/test/benchmark/*benchmark.js",
+    "clean": "rm -rf lib out addons/*/lib addons/*/out"
+  },
+  "devDependencies": {
+    "@types/chai": "^3.4.34",
+    "@types/glob": "^5.0.35",
+    "@types/jsdom": "11.0.1",
+    "@types/mocha": "^2.2.33",
+    "@types/node": "6.0.108",
+    "@types/puppeteer": "^1.12.4",
+    "@types/utf8": "^2.1.6",
+    "@types/webpack": "^4.4.11",
+    "@types/ws": "^6.0.1",
+    "chai": "3.5.0",
+    "express": "^4.17.1",
+    "express-ws": "^4.0.0",
+    "glob": "^7.0.5",
+    "jsdom": "^11.11.0",
+    "mocha": "^6.1.4",
+    "node-pty": "0.7.6",
+    "puppeteer": "^1.15.0",
+    "source-map-loader": "^0.2.4",
+    "ts-loader": "^6.0.4",
+    "tslint": "^5.18.0",
+    "tslint-consistent-codestyle": "^1.13.0",
+    "typescript": "3.6",
+    "utf8": "^3.0.0",
+    "webpack": "^4.35.3",
+    "webpack-cli": "^3.1.0",
+    "ws": "^7.0.0",
+    "xterm-benchmark": "^0.1.3"
+  },
+  "gitHead": "f30c38f7735c37dc13faed52e8423d71014d922c",
+  "bugs": {
+    "url": "https://github.com/xtermjs/xterm.js/issues"
+  },
+  "homepage": "https://github.com/xtermjs/xterm.js#readme",
+  "_id": "xterm@4.2.0",
+  "_npmVersion": "6.4.1",
+  "_nodeVersion": "8.16.2",
+  "_npmUser": {
+    "name": "tyriar",
+    "email": "tyriar@tyriar.com"
+  },
+  "dist": {
+    "integrity": "sha512-oNfLqt+LmghLPOt5UcskP5Km1fXpTBHsTZ99nxJKY2N0MNFXBKIVXUcNNhHCa74JGZFMGhLT58A/UN3HcPXSfg==",
+    "shasum": "b9980b2ae18c64ed31bcc95eace3bcecffebbbd9",
+    "tarball": "https://registry.npmjs.org/xterm/-/xterm-4.2.0.tgz",
+    "fileCount": 97,
+    "unpackedSize": 1815805,
+    "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdsvJCCRA9TVsSAnZWagAAx38P/RnG2mtxLM6oTPHg95Ee\nbqGn0x/Ja/q27lOgD+hL9q1kNvDDkDTI46LFNIo+ExFTluU6CDszD3trFelc\nZb4SNrptgpLmjBpSfzfs1TYu8Je1rDwgeemXRFyA+8gJd1vOZIn3reH9G81U\nVfpE70Zt4MFzzZ+pzyTWpbFionCnpfB9ml9/hRonnhlLn3WITZMzoCuojV+y\nBfFkP/scTZPiR6F3DVpAKPYaK4qWdqQm2Ht/CfpM3ik+hjjJRUEWp0qZhBS6\nE/CnyuRQtbNO8nwqIUNJU0V7kBP06JmjZ4KFxS833Pc1UJ2g900XhOQuu1Qj\nDj3Qu3Wb25pDH+fX4xFwQEo19A/DJPvznmPTF4YtUgDKX9Foi5Yqt8eiFdVP\nQxgZ+3QRva7XwCL45UG1s8fL2BBmFDSvGHXnBtjAOB/V1DqgA2xYYQ8XCcS1\nOcIgRXqusALMjw/eyJr28fqG8gTtvbU3w+DJc+OI/FTxIL/4hUYFmc/+L8S7\nrtxczBh8dOv6OSLfDVE9hkKnFQH1wAcKMfDwXIEbyPIJpry7jdzxXWdve2t7\nrw7wct6NIIygLW2rjjBiUSgAEFoJzfn+rGexw0Vh/ZiKHBdp84KOFyLmIity\nJmZ4kmW5EZbd+4XpiljlT+ISOExxkCAnFZSe7RYSP7l9ZxmvXMPwNee3Qow1\nT4Cl\r\n=mf2Q\r\n-----END PGP SIGNATURE-----\r\n"
+  },
+  "maintainers": [
+    {
+      "name": "paris",
+      "email": "pariskasidiaris@gmail.com"
+    },
+    {
+      "name": "tyriar",
+      "email": "tyriar@tyriar.com"
+    }
+  ],
+  "directories": {},
+  "_npmOperationalInternal": {
+    "host": "s3://npm-registry-packages",
+    "tmp": "tmp/xterm_4.2.0_1572008514012_0.1190934233728087"
+  },
+  "_hasShrinkwrap": false,
+  "_shasum": "b9980b2ae18c64ed31bcc95eace3bcecffebbbd9",
+  "_from": "xterm@",
+  "_resolved": "https://registry.npmjs.org/xterm/-/xterm-4.2.0.tgz"
+}
diff --git a/node_modules/xterm/src/AccessibilityManager.ts b/node_modules/xterm/src/AccessibilityManager.ts
new file mode 100644 (file)
index 0000000..75393ea
--- /dev/null
@@ -0,0 +1,297 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import * as Strings from './browser/LocalizableStrings';
+import { ITerminal } from './Types';
+import { IBuffer } from 'common/buffer/Types';
+import { isMac } from 'common/Platform';
+import { RenderDebouncer } from 'browser/RenderDebouncer';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { Disposable } from 'common/Lifecycle';
+import { ScreenDprMonitor } from 'browser/ScreenDprMonitor';
+import { IRenderService } from 'browser/services/Services';
+
+const MAX_ROWS_TO_READ = 20;
+
+const enum BoundaryPosition {
+  TOP,
+  BOTTOM
+}
+
+export class AccessibilityManager extends Disposable {
+  private _accessibilityTreeRoot: HTMLElement;
+  private _rowContainer: HTMLElement;
+  private _rowElements: HTMLElement[];
+  private _liveRegion: HTMLElement;
+  private _liveRegionLineCount: number = 0;
+
+  private _renderRowsDebouncer: RenderDebouncer;
+  private _screenDprMonitor: ScreenDprMonitor;
+
+  private _topBoundaryFocusListener: (e: FocusEvent) => void;
+  private _bottomBoundaryFocusListener: (e: FocusEvent) => void;
+
+  /**
+   * This queue has a character pushed to it for keys that are pressed, if the
+   * next character added to the terminal is equal to the key char then it is
+   * not announced (added to live region) because it has already been announced
+   * by the textarea event (which cannot be canceled). There are some race
+   * condition cases if there is typing while data is streaming, but this covers
+   * the main case of typing into the prompt and inputting the answer to a
+   * question (Y/N, etc.).
+   */
+  private _charsToConsume: string[] = [];
+
+  private _charsToAnnounce: string = '';
+
+  constructor(
+    private readonly _terminal: ITerminal,
+    private readonly _renderService: IRenderService
+  ) {
+    super();
+    this._accessibilityTreeRoot = document.createElement('div');
+    this._accessibilityTreeRoot.classList.add('xterm-accessibility');
+
+    this._rowContainer = document.createElement('div');
+    this._rowContainer.classList.add('xterm-accessibility-tree');
+    this._rowElements = [];
+    for (let i = 0; i < this._terminal.rows; i++) {
+      this._rowElements[i] = this._createAccessibilityTreeNode();
+      this._rowContainer.appendChild(this._rowElements[i]);
+    }
+
+    this._topBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.TOP);
+    this._bottomBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.BOTTOM);
+    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);
+    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
+
+    this._refreshRowsDimensions();
+    this._accessibilityTreeRoot.appendChild(this._rowContainer);
+
+    this._renderRowsDebouncer = new RenderDebouncer(this._renderRows.bind(this));
+    this._refreshRows();
+
+    this._liveRegion = document.createElement('div');
+    this._liveRegion.classList.add('live-region');
+    this._liveRegion.setAttribute('aria-live', 'assertive');
+    this._accessibilityTreeRoot.appendChild(this._liveRegion);
+
+    this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityTreeRoot);
+
+    this.register(this._renderRowsDebouncer);
+    this.register(this._terminal.onResize(e => this._onResize(e.rows)));
+    this.register(this._terminal.onRender(e => this._refreshRows(e.start, e.end)));
+    this.register(this._terminal.onScroll(() => this._refreshRows()));
+    // Line feed is an issue as the prompt won't be read out after a command is run
+    this.register(this._terminal.onA11yChar(char => this._onChar(char)));
+    this.register(this._terminal.onLineFeed(() => this._onChar('\n')));
+    this.register(this._terminal.onA11yTab(spaceCount => this._onTab(spaceCount)));
+    this.register(this._terminal.onKey(e => this._onKey(e.key)));
+    this.register(this._terminal.onBlur(() => this._clearLiveRegion()));
+    this.register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions()));
+
+    this._screenDprMonitor = new ScreenDprMonitor();
+    this.register(this._screenDprMonitor);
+    this._screenDprMonitor.setListener(() => this._refreshRowsDimensions());
+    // This shouldn't be needed on modern browsers but is present in case the
+    // media query that drives the ScreenDprMonitor isn't supported
+    this.register(addDisposableDomListener(window, 'resize', () => this._refreshRowsDimensions()));
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this._terminal.element.removeChild(this._accessibilityTreeRoot);
+    this._rowElements.length = 0;
+  }
+
+  private _onBoundaryFocus(e: FocusEvent, position: BoundaryPosition): void {
+    const boundaryElement = <HTMLElement>e.target;
+    const beforeBoundaryElement = this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2];
+
+    // Don't scroll if the buffer top has reached the end in that direction
+    const posInSet = boundaryElement.getAttribute('aria-posinset');
+    const lastRowPos = position === BoundaryPosition.TOP ? '1' : `${this._terminal.buffer.lines.length}`;
+    if (posInSet === lastRowPos) {
+      return;
+    }
+
+    // Don't scroll when the last focused item was not the second row (focus is going the other
+    // direction)
+    if (e.relatedTarget !== beforeBoundaryElement) {
+      return;
+    }
+
+    // Remove old boundary element from array
+    let topBoundaryElement: HTMLElement;
+    let bottomBoundaryElement: HTMLElement;
+    if (position === BoundaryPosition.TOP) {
+      topBoundaryElement = boundaryElement;
+      bottomBoundaryElement = this._rowElements.pop()!;
+      this._rowContainer.removeChild(bottomBoundaryElement);
+    } else {
+      topBoundaryElement = this._rowElements.shift()!;
+      bottomBoundaryElement = boundaryElement;
+      this._rowContainer.removeChild(topBoundaryElement);
+    }
+
+    // Remove listeners from old boundary elements
+    topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener);
+    bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener);
+
+    // Add new element to array/DOM
+    if (position === BoundaryPosition.TOP) {
+      const newElement = this._createAccessibilityTreeNode();
+      this._rowElements.unshift(newElement);
+      this._rowContainer.insertAdjacentElement('afterbegin', newElement);
+    } else {
+      const newElement = this._createAccessibilityTreeNode();
+      this._rowElements.push(newElement);
+      this._rowContainer.appendChild(newElement);
+    }
+
+    // Add listeners to new boundary elements
+    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);
+    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
+
+    // Scroll up
+    this._terminal.scrollLines(position === BoundaryPosition.TOP ? -1 : 1);
+
+    // Focus new boundary before element
+    this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2].focus();
+
+    // Prevent the standard behavior
+    e.preventDefault();
+    e.stopImmediatePropagation();
+  }
+
+  private _onResize(rows: number): void {
+    // Remove bottom boundary listener
+    this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener);
+
+    // Grow rows as required
+    for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) {
+      this._rowElements[i] = this._createAccessibilityTreeNode();
+      this._rowContainer.appendChild(this._rowElements[i]);
+    }
+    // Shrink rows as required
+    while (this._rowElements.length > rows) {
+      this._rowContainer.removeChild(this._rowElements.pop()!);
+    }
+
+    // Add bottom boundary listener
+    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
+
+    this._refreshRowsDimensions();
+  }
+
+  private _createAccessibilityTreeNode(): HTMLElement {
+    const element = document.createElement('div');
+    element.setAttribute('role', 'listitem');
+    element.tabIndex = -1;
+    this._refreshRowDimensions(element);
+    return element;
+  }
+
+  private _onTab(spaceCount: number): void {
+    for (let i = 0; i < spaceCount; i++) {
+      this._onChar(' ');
+    }
+  }
+
+  private _onChar(char: string): void {
+    if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) {
+      if (this._charsToConsume.length > 0) {
+        // Have the screen reader ignore the char if it was just input
+        const shiftedChar = this._charsToConsume.shift();
+        if (shiftedChar !== char) {
+          this._charsToAnnounce += char;
+        }
+      } else {
+        this._charsToAnnounce += char;
+      }
+
+      if (char === '\n') {
+        this._liveRegionLineCount++;
+        if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) {
+          this._liveRegion.textContent += Strings.tooMuchOutput;
+        }
+      }
+
+      // Only detach/attach on mac as otherwise messages can go unaccounced
+      if (isMac) {
+        if (this._liveRegion.textContent && this._liveRegion.textContent.length > 0 && !this._liveRegion.parentNode) {
+          setTimeout(() => {
+            this._accessibilityTreeRoot.appendChild(this._liveRegion);
+          }, 0);
+        }
+      }
+    }
+  }
+
+  private _clearLiveRegion(): void {
+    this._liveRegion.textContent = '';
+    this._liveRegionLineCount = 0;
+
+    // Only detach/attach on mac as otherwise messages can go unaccounced
+    if (isMac) {
+      if (this._liveRegion.parentNode) {
+        this._accessibilityTreeRoot.removeChild(this._liveRegion);
+      }
+    }
+  }
+
+  private _onKey(keyChar: string): void {
+    this._clearLiveRegion();
+    this._charsToConsume.push(keyChar);
+  }
+
+  private _refreshRows(start?: number, end?: number): void {
+    this._renderRowsDebouncer.refresh(start, end, this._terminal.rows);
+  }
+
+  private _renderRows(start: number, end: number): void {
+    const buffer: IBuffer = this._terminal.buffer;
+    const setSize = buffer.lines.length.toString();
+    for (let i = start; i <= end; i++) {
+      const lineData = buffer.translateBufferLineToString(buffer.ydisp + i, true);
+      const posInSet = (buffer.ydisp + i + 1).toString();
+      const element = this._rowElements[i];
+      if (element) {
+        if (lineData.length === 0) {
+          element.innerHTML = '&nbsp;';
+        } else {
+          element.textContent = lineData;
+        }
+        element.setAttribute('aria-posinset', posInSet);
+        element.setAttribute('aria-setsize', setSize);
+      }
+    }
+    this._announceCharacters();
+  }
+
+  private _refreshRowsDimensions(): void {
+    if (!this._renderService.dimensions.actualCellHeight) {
+      return;
+    }
+    if (this._rowElements.length !== this._terminal.rows) {
+      this._onResize(this._terminal.rows);
+    }
+    for (let i = 0; i < this._terminal.rows; i++) {
+      this._refreshRowDimensions(this._rowElements[i]);
+    }
+  }
+
+  private _refreshRowDimensions(element: HTMLElement): void {
+    element.style.height = `${this._renderService.dimensions.actualCellHeight}px`;
+  }
+
+  private _announceCharacters(): void {
+    if (this._charsToAnnounce.length === 0) {
+      return;
+    }
+    this._liveRegion.textContent += this._charsToAnnounce;
+    this._charsToAnnounce = '';
+  }
+}
diff --git a/node_modules/xterm/src/InputHandler.ts b/node_modules/xterm/src/InputHandler.ts
new file mode 100644 (file)
index 0000000..7b6ea1f
--- /dev/null
@@ -0,0 +1,2242 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * @license MIT
+ */
+
+import { IInputHandler, IInputHandlingTerminal } from './Types';
+import { C0, C1 } from 'common/data/EscapeSequences';
+import { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';
+import { wcwidth } from 'common/CharWidth';
+import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';
+import { Disposable } from 'common/Lifecycle';
+import { concat } from 'common/TypedArrayUtils';
+import { StringToUtf32, stringFromCodePoint, utf32ToString, Utf8ToUtf32 } from 'common/input/TextDecoder';
+import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';
+import { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { IAttributeData, IDisposable } from 'common/Types';
+import { ICoreService, IBufferService, IOptionsService, ILogService, IDirtyRowService, ICoreMouseService } from 'common/services/Services';
+import { OscHandler } from 'common/parser/OscParser';
+import { DcsHandler } from 'common/parser/DcsParser';
+
+/**
+ * Map collect to glevel. Used in `selectCharset`.
+ */
+const GLEVEL: {[key: string]: number} = {'(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2};
+
+/**
+ * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher.
+ */
+const MAX_PARSEBUFFER_LENGTH = 131072;
+
+
+/**
+ * DCS subparser implementations
+ */
+
+/**
+ * DCS $ q Pt ST
+ *   DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html)
+ *   Request Status String (DECRQSS), VT420 and up.
+ *   Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html)
+ */
+class DECRQSS implements IDcsHandler {
+  private _data: Uint32Array = new Uint32Array(0);
+
+  constructor(
+    private _bufferService: IBufferService,
+    private _coreService: ICoreService,
+    private _logService: ILogService,
+    private _optionsService: IOptionsService
+  ) { }
+
+  hook(params: IParams): void {
+    this._data = new Uint32Array(0);
+  }
+
+  put(data: Uint32Array, start: number, end: number): void {
+    this._data = concat(this._data, data.subarray(start, end));
+  }
+
+  unhook(success: boolean): void {
+    if (!success) {
+      this._data = new Uint32Array(0);
+      return;
+    }
+    const data = utf32ToString(this._data);
+    this._data = new Uint32Array(0);
+    switch (data) {
+      // valid: DCS 1 $ r Pt ST (xterm)
+      case '"q': // DECSCA
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0"q${C0.ESC}\\`);
+      case '"p': // DECSCL
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r61"p${C0.ESC}\\`);
+      case 'r': // DECSTBM
+        const pt = '' + (this._bufferService.buffer.scrollTop + 1) +
+                ';' + (this._bufferService.buffer.scrollBottom + 1) + 'r';
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${pt}${C0.ESC}\\`);
+      case 'm': // SGR
+        // TODO: report real settings instead of 0m
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0m${C0.ESC}\\`);
+      case ' q': // DECSCUSR
+        const STYLES: {[key: string]: number} = {'block': 2, 'underline': 4, 'bar': 6};
+        let style = STYLES[this._optionsService.options.cursorStyle];
+        style -= this._optionsService.options.cursorBlink ? 1 : 0;
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${style} q${C0.ESC}\\`);
+      default:
+        // invalid: DCS 0 $ r Pt ST (xterm)
+        this._logService.debug('Unknown DCS $q %s', data);
+        this._coreService.triggerDataEvent(`${C0.ESC}P0$r${C0.ESC}\\`);
+    }
+  }
+}
+
+/**
+ * DCS Ps; Ps| Pt ST
+ *   DECUDK (https://vt100.net/docs/vt510-rm/DECUDK.html)
+ *   not supported
+ */
+
+/**
+ * DCS + q Pt ST (xterm)
+ *   Request Terminfo String
+ *   not implemented
+ */
+
+/**
+ * DCS + p Pt ST (xterm)
+ *   Set Terminfo Data
+ *   not supported
+ */
+
+
+
+/**
+ * The terminal's standard implementation of IInputHandler, this handles all
+ * input from the Parser.
+ *
+ * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand
+ * each function's header comment.
+ */
+export class InputHandler extends Disposable implements IInputHandler {
+  private _parseBuffer: Uint32Array = new Uint32Array(4096);
+  private _stringDecoder: StringToUtf32 = new StringToUtf32();
+  private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32();
+  private _workCell: CellData = new CellData();
+
+  private _onCursorMove = new EventEmitter<void>();
+  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }
+  private _onLineFeed = new EventEmitter<void>();
+  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }
+  private _onScroll = new EventEmitter<number>();
+  public get onScroll(): IEvent<number> { return this._onScroll.event; }
+
+  constructor(
+    protected _terminal: IInputHandlingTerminal,
+    private readonly _bufferService: IBufferService,
+    private readonly _coreService: ICoreService,
+    private readonly _dirtyRowService: IDirtyRowService,
+    private readonly _logService: ILogService,
+    private readonly _optionsService: IOptionsService,
+    private readonly _coreMouseService: ICoreMouseService,
+    private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser())
+  {
+    super();
+
+    this.register(this._parser);
+
+    /**
+     * custom fallback handlers
+     */
+    this._parser.setCsiHandlerFallback((ident, params) => {
+      this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() });
+    });
+    this._parser.setEscHandlerFallback(ident => {
+      this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) });
+    });
+    this._parser.setExecuteHandlerFallback(code => {
+      this._logService.debug('Unknown EXECUTE code: ', { code });
+    });
+    this._parser.setOscHandlerFallback((identifier, action, data) => {
+      this._logService.debug('Unknown OSC code: ', { identifier, action, data });
+    });
+    this._parser.setDcsHandlerFallback((ident, action, payload) => {
+      if (action === 'HOOK') {
+        payload = payload.toArray();
+      }
+      this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload });
+    });
+
+    /**
+     * print handler
+     */
+    this._parser.setPrintHandler((data, start, end) => this.print(data, start, end));
+
+    /**
+     * CSI handler
+     */
+    this._parser.setCsiHandler({final: '@'}, params => this.insertChars(params));
+    this._parser.setCsiHandler({intermediates: ' ', final: '@'}, params => this.scrollLeft(params));
+    this._parser.setCsiHandler({final: 'A'}, params => this.cursorUp(params));
+    this._parser.setCsiHandler({intermediates: ' ', final: 'A'}, params => this.scrollRight(params));
+    this._parser.setCsiHandler({final: 'B'}, params => this.cursorDown(params));
+    this._parser.setCsiHandler({final: 'C'}, params => this.cursorForward(params));
+    this._parser.setCsiHandler({final: 'D'}, params => this.cursorBackward(params));
+    this._parser.setCsiHandler({final: 'E'}, params => this.cursorNextLine(params));
+    this._parser.setCsiHandler({final: 'F'}, params => this.cursorPrecedingLine(params));
+    this._parser.setCsiHandler({final: 'G'}, params => this.cursorCharAbsolute(params));
+    this._parser.setCsiHandler({final: 'H'}, params => this.cursorPosition(params));
+    this._parser.setCsiHandler({final: 'I'}, params => this.cursorForwardTab(params));
+    this._parser.setCsiHandler({final: 'J'}, params => this.eraseInDisplay(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'J'}, params => this.eraseInDisplay(params));
+    this._parser.setCsiHandler({final: 'K'}, params => this.eraseInLine(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'K'}, params => this.eraseInLine(params));
+    this._parser.setCsiHandler({final: 'L'}, params => this.insertLines(params));
+    this._parser.setCsiHandler({final: 'M'}, params => this.deleteLines(params));
+    this._parser.setCsiHandler({final: 'P'}, params => this.deleteChars(params));
+    this._parser.setCsiHandler({final: 'S'}, params => this.scrollUp(params));
+    this._parser.setCsiHandler({final: 'T'}, params => this.scrollDown(params));
+    this._parser.setCsiHandler({final: 'X'}, params => this.eraseChars(params));
+    this._parser.setCsiHandler({final: 'Z'}, params => this.cursorBackwardTab(params));
+    this._parser.setCsiHandler({final: '`'}, params => this.charPosAbsolute(params));
+    this._parser.setCsiHandler({final: 'a'}, params => this.hPositionRelative(params));
+    this._parser.setCsiHandler({final: 'b'}, params => this.repeatPrecedingCharacter(params));
+    this._parser.setCsiHandler({final: 'c'}, params => this.sendDeviceAttributesPrimary(params));
+    this._parser.setCsiHandler({prefix: '>', final: 'c'}, params => this.sendDeviceAttributesSecondary(params));
+    this._parser.setCsiHandler({final: 'd'}, params => this.linePosAbsolute(params));
+    this._parser.setCsiHandler({final: 'e'}, params => this.vPositionRelative(params));
+    this._parser.setCsiHandler({final: 'f'}, params => this.hVPosition(params));
+    this._parser.setCsiHandler({final: 'g'}, params => this.tabClear(params));
+    this._parser.setCsiHandler({final: 'h'}, params => this.setMode(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'h'}, params => this.setModePrivate(params));
+    this._parser.setCsiHandler({final: 'l'}, params => this.resetMode(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'l'}, params => this.resetModePrivate(params));
+    this._parser.setCsiHandler({final: 'm'}, params => this.charAttributes(params));
+    this._parser.setCsiHandler({final: 'n'}, params => this.deviceStatus(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'n'}, params => this.deviceStatusPrivate(params));
+    this._parser.setCsiHandler({intermediates: '!', final: 'p'}, params => this.softReset(params));
+    this._parser.setCsiHandler({intermediates: ' ', final: 'q'}, params => this.setCursorStyle(params));
+    this._parser.setCsiHandler({final: 'r'}, params => this.setScrollRegion(params));
+    this._parser.setCsiHandler({final: 's'}, params => this.saveCursor(params));
+    this._parser.setCsiHandler({final: 'u'}, params => this.restoreCursor(params));
+    this._parser.setCsiHandler({intermediates: '\'', final: '}'}, params => this.insertColumns(params));
+    this._parser.setCsiHandler({intermediates: '\'', final: '~'}, params => this.deleteColumns(params));
+
+    /**
+     * execute handler
+     */
+    this._parser.setExecuteHandler(C0.BEL, () => this.bell());
+    this._parser.setExecuteHandler(C0.LF, () => this.lineFeed());
+    this._parser.setExecuteHandler(C0.VT, () => this.lineFeed());
+    this._parser.setExecuteHandler(C0.FF, () => this.lineFeed());
+    this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn());
+    this._parser.setExecuteHandler(C0.BS, () => this.backspace());
+    this._parser.setExecuteHandler(C0.HT, () => this.tab());
+    this._parser.setExecuteHandler(C0.SO, () => this.shiftOut());
+    this._parser.setExecuteHandler(C0.SI, () => this.shiftIn());
+    // FIXME:   What do to with missing? Old code just added those to print.
+
+    this._parser.setExecuteHandler(C1.IND, () => this.index());
+    this._parser.setExecuteHandler(C1.NEL, () => this.nextLine());
+    this._parser.setExecuteHandler(C1.HTS, () => this.tabSet());
+
+    /**
+     * OSC handler
+     */
+    //   0 - icon name + title
+    this._parser.setOscHandler(0, new OscHandler((data: string) => this.setTitle(data)));
+    //   1 - icon name
+    //   2 - title
+    this._parser.setOscHandler(2, new OscHandler((data: string) => this.setTitle(data)));
+    //   3 - set property X in the form "prop=value"
+    //   4 - Change Color Number
+    //   5 - Change Special Color Number
+    //   6 - Enable/disable Special Color Number c
+    //   7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939)
+    //  10 - Change VT100 text foreground color to Pt.
+    //  11 - Change VT100 text background color to Pt.
+    //  12 - Change text cursor color to Pt.
+    //  13 - Change mouse foreground color to Pt.
+    //  14 - Change mouse background color to Pt.
+    //  15 - Change Tektronix foreground color to Pt.
+    //  16 - Change Tektronix background color to Pt.
+    //  17 - Change highlight background color to Pt.
+    //  18 - Change Tektronix cursor color to Pt.
+    //  19 - Change highlight foreground color to Pt.
+    //  46 - Change Log File to Pt.
+    //  50 - Set Font to Pt.
+    //  51 - reserved for Emacs shell.
+    //  52 - Manipulate Selection Data.
+    // 104 ; c - Reset Color Number c.
+    // 105 ; c - Reset Special Color Number c.
+    // 106 ; c; f - Enable/disable Special Color Number c.
+    // 110 - Reset VT100 text foreground color.
+    // 111 - Reset VT100 text background color.
+    // 112 - Reset text cursor color.
+    // 113 - Reset mouse foreground color.
+    // 114 - Reset mouse background color.
+    // 115 - Reset Tektronix foreground color.
+    // 116 - Reset Tektronix background color.
+    // 117 - Reset highlight color.
+    // 118 - Reset Tektronix cursor color.
+    // 119 - Reset highlight foreground color.
+
+    /**
+     * ESC handlers
+     */
+    this._parser.setEscHandler({final: '7'}, () => this.saveCursor());
+    this._parser.setEscHandler({final: '8'}, () => this.restoreCursor());
+    this._parser.setEscHandler({final: 'D'}, () => this.index());
+    this._parser.setEscHandler({final: 'E'}, () => this.nextLine());
+    this._parser.setEscHandler({final: 'H'}, () => this.tabSet());
+    this._parser.setEscHandler({final: 'M'}, () => this.reverseIndex());
+    this._parser.setEscHandler({final: '='}, () => this.keypadApplicationMode());
+    this._parser.setEscHandler({final: '>'}, () => this.keypadNumericMode());
+    this._parser.setEscHandler({final: 'c'}, () => this.reset());
+    this._parser.setEscHandler({final: 'n'}, () => this.setgLevel(2));
+    this._parser.setEscHandler({final: 'o'}, () => this.setgLevel(3));
+    this._parser.setEscHandler({final: '|'}, () => this.setgLevel(3));
+    this._parser.setEscHandler({final: '}'}, () => this.setgLevel(2));
+    this._parser.setEscHandler({final: '~'}, () => this.setgLevel(1));
+    this._parser.setEscHandler({intermediates: '%', final: '@'}, () => this.selectDefaultCharset());
+    this._parser.setEscHandler({intermediates: '%', final: 'G'}, () => this.selectDefaultCharset());
+    for (const flag in CHARSETS) {
+      this._parser.setEscHandler({intermediates: '(', final: flag}, () => this.selectCharset('(' + flag));
+      this._parser.setEscHandler({intermediates: ')', final: flag}, () => this.selectCharset(')' + flag));
+      this._parser.setEscHandler({intermediates: '*', final: flag}, () => this.selectCharset('*' + flag));
+      this._parser.setEscHandler({intermediates: '+', final: flag}, () => this.selectCharset('+' + flag));
+      this._parser.setEscHandler({intermediates: '-', final: flag}, () => this.selectCharset('-' + flag));
+      this._parser.setEscHandler({intermediates: '.', final: flag}, () => this.selectCharset('.' + flag));
+      this._parser.setEscHandler({intermediates: '/', final: flag}, () => this.selectCharset('/' + flag)); // TODO: supported?
+    }
+    this._parser.setEscHandler({intermediates: '#', final: '8'}, () => this.screenAlignmentPattern());
+
+    /**
+     * error handler
+     */
+    this._parser.setErrorHandler((state: IParsingState) => {
+      this._logService.error('Parsing error: ', state);
+      return state;
+    });
+
+    /**
+     * DCS handler
+     */
+    this._parser.setDcsHandler({intermediates: '$', final: 'q'}, new DECRQSS(this._bufferService, this._coreService, this._logService, this._optionsService));
+  }
+
+  public dispose(): void {
+    super.dispose();
+  }
+
+  public parse(data: string | Uint8Array): void {
+    let buffer = this._bufferService.buffer;
+    const cursorStartX = buffer.x;
+    const cursorStartY = buffer.y;
+
+    this._logService.debug('parsing data', data);
+
+    // resize input buffer if needed
+    if (this._parseBuffer.length < data.length) {
+      if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) {
+        this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH));
+      }
+    }
+
+    // process big data in smaller chunks
+    if (data.length > MAX_PARSEBUFFER_LENGTH) {
+      for (let i = 0; i < data.length; i += MAX_PARSEBUFFER_LENGTH) {
+        const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length;
+        const len = (typeof data === 'string')
+          ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer)
+          : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer);
+        this._parser.parse(this._parseBuffer, len);
+      }
+    } else {
+      const len = (typeof data === 'string')
+        ? this._stringDecoder.decode(data, this._parseBuffer)
+        : this._utf8Decoder.decode(data, this._parseBuffer);
+      this._parser.parse(this._parseBuffer, len);
+    }
+
+    buffer = this._bufferService.buffer;
+    if (buffer.x !== cursorStartX || buffer.y !== cursorStartY) {
+      this._onCursorMove.fire();
+    }
+    this._terminal.refresh(this._dirtyRowService.start, this._dirtyRowService.end);
+  }
+
+  public print(data: Uint32Array, start: number, end: number): void {
+    let code: number;
+    let chWidth: number;
+    const buffer = this._bufferService.buffer;
+    const charset = this._terminal.charset;
+    const screenReaderMode = this._optionsService.options.screenReaderMode;
+    const cols = this._bufferService.cols;
+    const wraparoundMode = this._terminal.wraparoundMode;
+    const insertMode = this._terminal.insertMode;
+    const curAttr = this._terminal.curAttrData;
+    let bufferRow = buffer.lines.get(buffer.y + buffer.ybase);
+
+    this._dirtyRowService.markDirty(buffer.y);
+    for (let pos = start; pos < end; ++pos) {
+      code = data[pos];
+
+      // calculate print space
+      // expensive call, therefore we save width in line buffer
+      chWidth = wcwidth(code);
+
+      // get charset replacement character
+      // charset is only defined for ASCII, therefore we only
+      // search for an replacement char if code < 127
+      if (code < 127 && charset) {
+        const ch = charset[String.fromCharCode(code)];
+        if (ch) {
+          code = ch.charCodeAt(0);
+        }
+      }
+
+      if (screenReaderMode) {
+        this._terminal.onA11yCharEmitter.fire(stringFromCodePoint(code));
+      }
+
+      // insert combining char at last cursor position
+      // FIXME: needs handling after cursor jumps
+      // buffer.x should never be 0 for a combining char
+      // since they always follow a cell consuming char
+      // therefore we can test for buffer.x to avoid overflow left
+      if (!chWidth && buffer.x) {
+        if (!bufferRow.getWidth(buffer.x - 1)) {
+          // found empty cell after fullwidth, need to go 2 cells back
+          // it is save to step 2 cells back here
+          // since an empty cell is only set by fullwidth chars
+          bufferRow.addCodepointToCell(buffer.x - 2, code);
+        } else {
+          bufferRow.addCodepointToCell(buffer.x - 1, code);
+        }
+        continue;
+      }
+
+      // goto next line if ch would overflow
+      // TODO: needs a global min terminal width of 2
+      // FIXME: additionally ensure chWidth fits into a line
+      //   -->  maybe forbid cols<xy at higher level as it would
+      //        introduce a bad runtime penalty here
+      if (buffer.x + chWidth - 1 >= cols) {
+        // autowrap - DECAWM
+        // automatically wraps to the beginning of the next line
+        if (wraparoundMode) {
+          buffer.x = 0;
+          buffer.y++;
+          if (buffer.y === buffer.scrollBottom + 1) {
+            buffer.y--;
+            this._terminal.scroll(true);
+          } else {
+            if (buffer.y >= this._bufferService.rows) {
+              buffer.y = this._bufferService.rows - 1;
+            }
+            // The line already exists (eg. the initial viewport), mark it as a
+            // wrapped line
+            buffer.lines.get(buffer.y).isWrapped = true;
+          }
+          // row changed, get it again
+          bufferRow = buffer.lines.get(buffer.y + buffer.ybase);
+        } else {
+          buffer.x = cols - 1;
+          if (chWidth === 2) {
+            // FIXME: check for xterm behavior
+            // What to do here? We got a wide char that does not fit into last cell
+            continue;
+          }
+        }
+      }
+
+      // insert mode: move characters to right
+      if (insertMode) {
+        // right shift cells according to the width
+        bufferRow.insertCells(buffer.x, chWidth, buffer.getNullCell(curAttr));
+        // test last cell - since the last cell has only room for
+        // a halfwidth char any fullwidth shifted there is lost
+        // and will be set to empty cell
+        if (bufferRow.getWidth(cols - 1) === 2) {
+          bufferRow.setCellFromCodePoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr.fg, curAttr.bg);
+        }
+      }
+
+      // write current char to buffer and advance cursor
+      bufferRow.setCellFromCodePoint(buffer.x++, code, chWidth, curAttr.fg, curAttr.bg);
+
+      // fullwidth char - also set next cell to placeholder stub and advance cursor
+      // for graphemes bigger than fullwidth we can simply loop to zero
+      // we already made sure above, that buffer.x + chWidth will not overflow right
+      if (chWidth > 0) {
+        while (--chWidth) {
+          // other than a regular empty cell a cell following a wide char has no width
+          bufferRow.setCellFromCodePoint(buffer.x++, 0, 0, curAttr.fg, curAttr.bg);
+        }
+      }
+    }
+    // store last char in Parser.precedingCodepoint for REP to work correctly
+    // This needs to check whether:
+    //  - fullwidth + surrogates: reset
+    //  - combining: only base char gets carried on (bug in xterm?)
+    if (end) {
+      bufferRow.loadCell(buffer.x - 1, this._workCell);
+      if (this._workCell.getWidth() === 2 || this._workCell.getCode() > 0xFFFF) {
+        this._parser.precedingCodepoint = 0;
+      } else if (this._workCell.isCombined()) {
+        this._parser.precedingCodepoint = this._workCell.getChars().charCodeAt(0);
+      } else {
+        this._parser.precedingCodepoint = this._workCell.content;
+      }
+    }
+    this._dirtyRowService.markDirty(buffer.y);
+  }
+
+  /**
+   * Forward addCsiHandler from parser.
+   */
+  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {
+    return this._parser.addCsiHandler(id, callback);
+  }
+
+  /**
+   * Forward addDcsHandler from parser.
+   */
+  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {
+    return this._parser.addDcsHandler(id, new DcsHandler(callback));
+  }
+
+  /**
+   * Forward addEscHandler from parser.
+   */
+  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {
+    return this._parser.addEscHandler(id, callback);
+  }
+
+  /**
+   * Forward addOscHandler from parser.
+   */
+  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {
+    return this._parser.addOscHandler(ident, new OscHandler(callback));
+  }
+
+  /**
+   * BEL
+   * Bell (Ctrl-G).
+   */
+  public bell(): void {
+    this._terminal.bell();
+  }
+
+  /**
+   * LF
+   * Line Feed or New Line (NL).  (LF  is Ctrl-J).
+   */
+  public lineFeed(): void {
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    if (this._optionsService.options.convertEol) {
+      buffer.x = 0;
+    }
+    buffer.y++;
+    if (buffer.y === buffer.scrollBottom + 1) {
+      buffer.y--;
+      this._terminal.scroll();
+    } else if (buffer.y >= this._bufferService.rows) {
+      buffer.y = this._bufferService.rows - 1;
+    }
+    // If the end of the line is hit, prevent this action from wrapping around to the next line.
+    if (buffer.x >= this._bufferService.cols) {
+      buffer.x--;
+    }
+
+    this._onLineFeed.fire();
+  }
+
+  /**
+   * CR
+   * Carriage Return (Ctrl-M).
+   */
+  public carriageReturn(): void {
+    this._bufferService.buffer.x = 0;
+  }
+
+  /**
+   * BS
+   * Backspace (Ctrl-H).
+   */
+  public backspace(): void {
+    this._restrictCursor();
+    if (this._bufferService.buffer.x > 0) {
+      this._bufferService.buffer.x--;
+    }
+  }
+
+  /**
+   * TAB
+   * Horizontal Tab (HT) (Ctrl-I).
+   */
+  public tab(): void {
+    if (this._bufferService.buffer.x >= this._bufferService.cols) {
+      return;
+    }
+    const originalX = this._bufferService.buffer.x;
+    this._bufferService.buffer.x = this._bufferService.buffer.nextStop();
+    if (this._optionsService.options.screenReaderMode) {
+      this._terminal.onA11yTabEmitter.fire(this._bufferService.buffer.x - originalX);
+    }
+  }
+
+  /**
+   * SO
+   * Shift Out (Ctrl-N) -> Switch to Alternate Character Set.  This invokes the
+   * G1 character set.
+   */
+  public shiftOut(): void {
+    this._terminal.setgLevel(1);
+  }
+
+  /**
+   * SI
+   * Shift In (Ctrl-O) -> Switch to Standard Character Set.  This invokes the G0
+   * character set (the default).
+   */
+  public shiftIn(): void {
+    this._terminal.setgLevel(0);
+  }
+
+  /**
+   * Restrict cursor to viewport size / scroll margin (origin mode).
+   */
+  private _restrictCursor(): void {
+    this._bufferService.buffer.x = Math.min(this._bufferService.cols - 1, Math.max(0, this._bufferService.buffer.x));
+    this._bufferService.buffer.y = this._terminal.originMode
+      ? Math.min(this._bufferService.buffer.scrollBottom, Math.max(this._bufferService.buffer.scrollTop, this._bufferService.buffer.y))
+      : Math.min(this._bufferService.rows - 1, Math.max(0, this._bufferService.buffer.y));
+  }
+
+  /**
+   * Set absolute cursor position.
+   */
+  private _setCursor(x: number, y: number): void {
+    if (this._terminal.originMode) {
+      this._bufferService.buffer.x = x;
+      this._bufferService.buffer.y = this._bufferService.buffer.scrollTop + y;
+    } else {
+      this._bufferService.buffer.x = x;
+      this._bufferService.buffer.y = y;
+    }
+    this._restrictCursor();
+  }
+
+  /**
+   * Set relative cursor position.
+   */
+  private _moveCursor(x: number, y: number): void {
+    // for relative changes we have to make sure we are within 0 .. cols/rows - 1
+    // before calculating the new position
+    this._restrictCursor();
+    this._setCursor(this._bufferService.buffer.x + x, this._bufferService.buffer.y + y);
+  }
+
+  /**
+   * CSI Ps A
+   * Cursor Up Ps Times (default = 1) (CUU).
+   */
+  public cursorUp(params: IParams): void {
+    // stop at scrollTop
+    const diffToTop = this._bufferService.buffer.y - this._bufferService.buffer.scrollTop;
+    if (diffToTop >= 0) {
+      this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1));
+    } else {
+      this._moveCursor(0, -(params.params[0] || 1));
+    }
+  }
+
+  /**
+   * CSI Ps B
+   * Cursor Down Ps Times (default = 1) (CUD).
+   */
+  public cursorDown(params: IParams): void {
+    // stop at scrollBottom
+    const diffToBottom = this._bufferService.buffer.scrollBottom - this._bufferService.buffer.y;
+    if (diffToBottom >= 0) {
+      this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1));
+    } else {
+      this._moveCursor(0, params.params[0] || 1);
+    }
+  }
+
+  /**
+   * CSI Ps C
+   * Cursor Forward Ps Times (default = 1) (CUF).
+   */
+  public cursorForward(params: IParams): void {
+    this._moveCursor(params.params[0] || 1, 0);
+  }
+
+  /**
+   * CSI Ps D
+   * Cursor Backward Ps Times (default = 1) (CUB).
+   */
+  public cursorBackward(params: IParams): void {
+    this._moveCursor(-(params.params[0] || 1), 0);
+  }
+
+  /**
+   * CSI Ps E
+   * Cursor Next Line Ps Times (default = 1) (CNL).
+   * Other than cursorDown (CUD) also set the cursor to first column.
+   */
+  public cursorNextLine(params: IParams): void {
+    this.cursorDown(params);
+    this._bufferService.buffer.x = 0;
+  }
+
+  /**
+   * CSI Ps F
+   * Cursor Previous Line Ps Times (default = 1) (CPL).
+   * Other than cursorUp (CUU) also set the cursor to first column.
+   */
+  public cursorPrecedingLine(params: IParams): void {
+    this.cursorUp(params);
+    this._bufferService.buffer.x = 0;
+  }
+
+  /**
+   * CSI Ps G
+   * Cursor Character Absolute  [column] (default = [row,1]) (CHA).
+   */
+  public cursorCharAbsolute(params: IParams): void {
+    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);
+  }
+
+  /**
+   * CSI Ps ; Ps H
+   * Cursor Position [row;column] (default = [1,1]) (CUP).
+   */
+  public cursorPosition(params: IParams): void {
+    this._setCursor(
+      // col
+      (params.length >= 2) ? (params.params[1] || 1) - 1 : 0,
+      // row
+      (params.params[0] || 1) - 1);
+  }
+
+  /**
+   * CSI Pm `  Character Position Absolute
+   *   [column] (default = [row,1]) (HPA).
+   * Currently same functionality as CHA.
+   */
+  public charPosAbsolute(params: IParams): void {
+    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);
+  }
+
+  /**
+   * CSI Pm a  Character Position Relative
+   *   [columns] (default = [row,col+1]) (HPR)
+   * Currently same functionality as CUF.
+   */
+  public hPositionRelative(params: IParams): void {
+    this._moveCursor(params.params[0] || 1, 0);
+  }
+
+  /**
+   * CSI Pm d  Vertical Position Absolute (VPA)
+   *   [row] (default = [1,column])
+   */
+  public linePosAbsolute(params: IParams): void {
+    this._setCursor(this._bufferService.buffer.x, (params.params[0] || 1) - 1);
+  }
+
+  /**
+   * CSI Pm e  Vertical Position Relative (VPR)
+   *   [rows] (default = [row+1,column])
+   * reuse CSI Ps B ?
+   */
+  public vPositionRelative(params: IParams): void {
+    this._moveCursor(0, params.params[0] || 1);
+  }
+
+  /**
+   * CSI Ps ; Ps f
+   *   Horizontal and Vertical Position [row;column] (default =
+   *   [1,1]) (HVP).
+   *   Same as CUP.
+   */
+  public hVPosition(params: IParams): void {
+    this.cursorPosition(params);
+  }
+
+  /**
+   * CSI Ps g  Tab Clear (TBC).
+   *     Ps = 0  -> Clear Current Column (default).
+   *     Ps = 3  -> Clear All.
+   * Potentially:
+   *   Ps = 2  -> Clear Stops on Line.
+   *   http://vt100.net/annarbor/aaa-ug/section6.html
+   */
+  public tabClear(params: IParams): void {
+    const param = params.params[0];
+    if (param === 0) {
+      delete this._bufferService.buffer.tabs[this._bufferService.buffer.x];
+    } else if (param === 3) {
+      this._bufferService.buffer.tabs = {};
+    }
+  }
+
+  /**
+   * CSI Ps I
+   *   Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
+   */
+  public cursorForwardTab(params: IParams): void {
+    if (this._bufferService.buffer.x >= this._bufferService.cols) {
+      return;
+    }
+    let param = params.params[0] || 1;
+    while (param--) {
+      this._bufferService.buffer.x = this._bufferService.buffer.nextStop();
+    }
+  }
+
+  /**
+   * CSI Ps Z  Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
+   */
+  public cursorBackwardTab(params: IParams): void {
+    if (this._bufferService.buffer.x >= this._bufferService.cols) {
+      return;
+    }
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    while (param--) {
+      buffer.x = buffer.prevStop();
+    }
+  }
+
+
+  /**
+   * Helper method to erase cells in a terminal row.
+   * The cell gets replaced with the eraseChar of the terminal.
+   * @param y row index
+   * @param start first cell index to be erased
+   * @param end   end - 1 is last erased cell
+   */
+  private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false): void {
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);
+    line.replaceCells(
+      start,
+      end,
+      this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+    );
+    if (clearWrap) {
+      line.isWrapped = false;
+    }
+  }
+
+  /**
+   * Helper method to reset cells in a terminal row.
+   * The cell gets replaced with the eraseChar of the terminal and the isWrapped property is set to false.
+   * @param y row index
+   */
+  private _resetBufferLine(y: number): void {
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);
+    line.fill(this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData()));
+    line.isWrapped = false;
+  }
+
+  /**
+   * CSI Ps J  Erase in Display (ED).
+   *     Ps = 0  -> Erase Below (default).
+   *     Ps = 1  -> Erase Above.
+   *     Ps = 2  -> Erase All.
+   *     Ps = 3  -> Erase Saved Lines (xterm).
+   * CSI ? Ps J
+   *   Erase in Display (DECSED).
+   *     Ps = 0  -> Selective Erase Below (default).
+   *     Ps = 1  -> Selective Erase Above.
+   *     Ps = 2  -> Selective Erase All.
+   */
+  public eraseInDisplay(params: IParams): void {
+    this._restrictCursor();
+    let j;
+    switch (params.params[0]) {
+      case 0:
+        j = this._bufferService.buffer.y;
+        this._dirtyRowService.markDirty(j);
+        this._eraseInBufferLine(j++, this._bufferService.buffer.x, this._bufferService.cols, this._bufferService.buffer.x === 0);
+        for (; j < this._bufferService.rows; j++) {
+          this._resetBufferLine(j);
+        }
+        this._dirtyRowService.markDirty(j);
+        break;
+      case 1:
+        j = this._bufferService.buffer.y;
+        this._dirtyRowService.markDirty(j);
+        // Deleted front part of line and everything before. This line will no longer be wrapped.
+        this._eraseInBufferLine(j, 0, this._bufferService.buffer.x + 1, true);
+        if (this._bufferService.buffer.x + 1 >= this._bufferService.cols) {
+          // Deleted entire previous line. This next line can no longer be wrapped.
+          this._bufferService.buffer.lines.get(j + 1).isWrapped = false;
+        }
+        while (j--) {
+          this._resetBufferLine(j);
+        }
+        this._dirtyRowService.markDirty(0);
+        break;
+      case 2:
+        j = this._bufferService.rows;
+        this._dirtyRowService.markDirty(j - 1);
+        while (j--) {
+          this._resetBufferLine(j);
+        }
+        this._dirtyRowService.markDirty(0);
+        break;
+      case 3:
+        // Clear scrollback (everything not in viewport)
+        const scrollBackSize = this._bufferService.buffer.lines.length - this._bufferService.rows;
+        if (scrollBackSize > 0) {
+          this._bufferService.buffer.lines.trimStart(scrollBackSize);
+          this._bufferService.buffer.ybase = Math.max(this._bufferService.buffer.ybase - scrollBackSize, 0);
+          this._bufferService.buffer.ydisp = Math.max(this._bufferService.buffer.ydisp - scrollBackSize, 0);
+          // Force a scroll event to refresh viewport
+          this._onScroll.fire(0);
+        }
+        break;
+    }
+  }
+
+  /**
+   * CSI Ps K  Erase in Line (EL).
+   *     Ps = 0  -> Erase to Right (default).
+   *     Ps = 1  -> Erase to Left.
+   *     Ps = 2  -> Erase All.
+   * CSI ? Ps K
+   *   Erase in Line (DECSEL).
+   *     Ps = 0  -> Selective Erase to Right (default).
+   *     Ps = 1  -> Selective Erase to Left.
+   *     Ps = 2  -> Selective Erase All.
+   */
+  public eraseInLine(params: IParams): void {
+    this._restrictCursor();
+    switch (params.params[0]) {
+      case 0:
+        this._eraseInBufferLine(this._bufferService.buffer.y, this._bufferService.buffer.x, this._bufferService.cols);
+        break;
+      case 1:
+        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.buffer.x + 1);
+        break;
+      case 2:
+        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.cols);
+        break;
+    }
+    this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+  }
+
+  /**
+   * CSI Ps L
+   * Insert Ps Line(s) (default = 1) (IL).
+   */
+  public insertLines(params: IParams): void {
+    this._restrictCursor();
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+
+    const row: number = buffer.y + buffer.ybase;
+
+    const scrollBottomRowsOffset = this._bufferService.rows - 1 - buffer.scrollBottom;
+    const scrollBottomAbsolute = this._bufferService.rows - 1 + buffer.ybase - scrollBottomRowsOffset + 1;
+    while (param--) {
+      // test: echo -e '\e[44m\e[1L\e[0m'
+      // blankLine(true) - xterm/linux behavior
+      buffer.lines.splice(scrollBottomAbsolute - 1, 1);
+      buffer.lines.splice(row, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));
+    }
+
+    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);
+    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?
+  }
+
+  /**
+   * CSI Ps M
+   * Delete Ps Line(s) (default = 1) (DL).
+   */
+  public deleteLines(params: IParams): void {
+    this._restrictCursor();
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+
+    const row: number = buffer.y + buffer.ybase;
+
+    let j: number;
+    j = this._bufferService.rows - 1 - buffer.scrollBottom;
+    j = this._bufferService.rows - 1 + buffer.ybase - j;
+    while (param--) {
+      // test: echo -e '\e[44m\e[1M\e[0m'
+      // blankLine(true) - xterm/linux behavior
+      buffer.lines.splice(row, 1);
+      buffer.lines.splice(j, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));
+    }
+
+    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);
+    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?
+  }
+
+  /**
+   * CSI Ps @
+   * Insert Ps (Blank) Character(s) (default = 1) (ICH).
+   */
+  public insertChars(params: IParams): void {
+    this._restrictCursor();
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);
+    if (line) {
+      line.insertCells(
+        this._bufferService.buffer.x,
+        params.params[0] || 1,
+        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+      );
+      this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+    }
+  }
+
+  /**
+   * CSI Ps P
+   * Delete Ps Character(s) (default = 1) (DCH).
+   */
+  public deleteChars(params: IParams): void {
+    this._restrictCursor();
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);
+    if (line) {
+      line.deleteCells(
+        this._bufferService.buffer.x,
+        params.params[0] || 1,
+        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+      );
+      this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+    }
+  }
+
+  /**
+   * CSI Ps S  Scroll up Ps lines (default = 1) (SU).
+   */
+  public scrollUp(params: IParams): void {
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    while (param--) {
+      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 1);
+      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps T  Scroll down Ps lines (default = 1) (SD).
+   */
+  public scrollDown(params: IParams): void {
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    while (param--) {
+      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 1);
+      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 0, buffer.getBlankLine(DEFAULT_ATTR_DATA));
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps SP @  Scroll left Ps columns (default = 1) (SL) ECMA-48
+   *
+   * Notation: (Pn)
+   * Representation: CSI Pn 02/00 04/00
+   * Parameter default value: Pn = 1
+   * SL causes the data in the presentation component to be moved by n character positions
+   * if the line orientation is horizontal, or by n line positions if the line orientation
+   * is vertical, such that the data appear to move to the left; where n equals the value of Pn.
+   * The active presentation position is not affected by this control function.
+   *
+   * Supported:
+   *   - always left shift (no line orientation setting respected)
+   */
+  public scrollLeft(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = buffer.lines.get(buffer.ybase + y);
+      line.deleteCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps SP A  Scroll right Ps columns (default = 1) (SR) ECMA-48
+   *
+   * Notation: (Pn)
+   * Representation: CSI Pn 02/00 04/01
+   * Parameter default value: Pn = 1
+   * SR causes the data in the presentation component to be moved by n character positions
+   * if the line orientation is horizontal, or by n line positions if the line orientation
+   * is vertical, such that the data appear to move to the right; where n equals the value of Pn.
+   * The active presentation position is not affected by this control function.
+   *
+   * Supported:
+   *   - always right shift (no line orientation setting respected)
+   */
+  public scrollRight(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = buffer.lines.get(buffer.ybase + y);
+      line.insertCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Pm ' }
+   * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.
+   */
+  public insertColumns(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = this._bufferService.buffer.lines.get(buffer.ybase + y);
+      line.insertCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Pm ' ~
+   * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.
+   */
+  public deleteColumns(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = buffer.lines.get(buffer.ybase + y);
+      line.deleteCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps X
+   * Erase Ps Character(s) (default = 1) (ECH).
+   */
+  public eraseChars(params: IParams): void {
+    this._restrictCursor();
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);
+    if (line) {
+      line.replaceCells(
+        this._bufferService.buffer.x,
+        this._bufferService.buffer.x + (params.params[0] || 1),
+        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+      );
+      this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+    }
+  }
+
+  /**
+   * CSI Ps b  Repeat the preceding graphic character Ps times (REP).
+   * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf)
+   *    Notation: (Pn)
+   *    Representation: CSI Pn 06/02
+   *    Parameter default value: Pn = 1
+   *    REP is used to indicate that the preceding character in the data stream,
+   *    if it is a graphic character (represented by one or more bit combinations) including SPACE,
+   *    is to be repeated n times, where n equals the value of Pn.
+   *    If the character preceding REP is a control function or part of a control function,
+   *    the effect of REP is not defined by this Standard.
+   *
+   * Since we propagate the terminal as xterm-256color we have to follow xterm's behavior:
+   *    - fullwidth + surrogate chars are ignored
+   *    - for combining chars only the base char gets repeated
+   *    - text attrs are applied normally
+   *    - wrap around is respected
+   *    - any valid sequence resets the carried forward char
+   *
+   * Note: To get reset on a valid sequence working correctly without much runtime penalty,
+   * the preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`.
+   */
+  public repeatPrecedingCharacter(params: IParams): void {
+    if (!this._parser.precedingCodepoint) {
+      return;
+    }
+    // call print to insert the chars and handle correct wrapping
+    const length = params.params[0] || 1;
+    const data = new Uint32Array(length);
+    for (let i = 0; i < length; ++i) {
+      data[i] = this._parser.precedingCodepoint;
+    }
+    this.print(data, 0, data.length);
+  }
+
+  /**
+   * CSI Ps c  Send Device Attributes (Primary DA).
+   *     Ps = 0  or omitted -> request attributes from terminal.  The
+   *     response depends on the decTerminalID resource setting.
+   *     -> CSI ? 1 ; 2 c  (``VT100 with Advanced Video Option'')
+   *     -> CSI ? 1 ; 0 c  (``VT101 with No Options'')
+   *     -> CSI ? 6 c  (``VT102'')
+   *     -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c  (``VT220'')
+   *   The VT100-style response parameters do not mean anything by
+   *   themselves.  VT220 parameters do, telling the host what fea-
+   *   tures the terminal supports:
+   *     Ps = 1  -> 132-columns.
+   *     Ps = 2  -> Printer.
+   *     Ps = 6  -> Selective erase.
+   *     Ps = 8  -> User-defined keys.
+   *     Ps = 9  -> National replacement character sets.
+   *     Ps = 1 5  -> Technical characters.
+   *     Ps = 2 2  -> ANSI color, e.g., VT525.
+   *     Ps = 2 9  -> ANSI text locator (i.e., DEC Locator mode).
+   * CSI > Ps c
+   *   Send Device Attributes (Secondary DA).
+   *     Ps = 0  or omitted -> request the terminal's identification
+   *     code.  The response depends on the decTerminalID resource set-
+   *     ting.  It should apply only to VT220 and up, but xterm extends
+   *     this to VT100.
+   *     -> CSI  > Pp ; Pv ; Pc c
+   *   where Pp denotes the terminal type
+   *     Pp = 0  -> ``VT100''.
+   *     Pp = 1  -> ``VT220''.
+   *   and Pv is the firmware version (for xterm, this was originally
+   *   the XFree86 patch number, starting with 95).  In a DEC termi-
+   *   nal, Pc indicates the ROM cartridge registration number and is
+   *   always zero.
+   * More information:
+   *   xterm/charproc.c - line 2012, for more information.
+   *   vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
+   */
+  public sendDeviceAttributesPrimary(params: IParams): void {
+    if (params.params[0] > 0) {
+      return;
+    }
+    if (this._terminal.is('xterm') || this._terminal.is('rxvt-unicode') || this._terminal.is('screen')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[?1;2c');
+    } else if (this._terminal.is('linux')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[?6c');
+    }
+  }
+  public sendDeviceAttributesSecondary(params: IParams): void {
+    if (params.params[0] > 0) {
+      return;
+    }
+    // xterm and urxvt
+    // seem to spit this
+    // out around ~370 times (?).
+    if (this._terminal.is('xterm')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c');
+    } else if (this._terminal.is('rxvt-unicode')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c');
+    } else if (this._terminal.is('linux')) {
+      // not supported by linux console.
+      // linux console echoes parameters.
+      this._coreService.triggerDataEvent(params.params[0] + 'c');
+    } else if (this._terminal.is('screen')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c');
+    }
+  }
+
+  /**
+   * CSI Pm h  Set Mode (SM).
+   *     Ps = 2  -> Keyboard Action Mode (AM).
+   *     Ps = 4  -> Insert Mode (IRM).
+   *     Ps = 1 2  -> Send/receive (SRM).
+   *     Ps = 2 0  -> Automatic Newline (LNM).
+   * CSI ? Pm h
+   *   DEC Private Mode Set (DECSET).
+   *     Ps = 1  -> Application Cursor Keys (DECCKM).
+   *     Ps = 2  -> Designate USASCII for character sets G0-G3
+   *     (DECANM), and set VT100 mode.
+   *     Ps = 3  -> 132 Column Mode (DECCOLM).
+   *     Ps = 4  -> Smooth (Slow) Scroll (DECSCLM).
+   *     Ps = 5  -> Reverse Video (DECSCNM).
+   *     Ps = 6  -> Origin Mode (DECOM).
+   *     Ps = 7  -> Wraparound Mode (DECAWM).
+   *     Ps = 8  -> Auto-repeat Keys (DECARM).
+   *     Ps = 9  -> Send Mouse X & Y on button press.  See the sec-
+   *     tion Mouse Tracking.
+   *     Ps = 1 0  -> Show toolbar (rxvt).
+   *     Ps = 1 2  -> Start Blinking Cursor (att610).
+   *     Ps = 1 8  -> Print form feed (DECPFF).
+   *     Ps = 1 9  -> Set print extent to full screen (DECPEX).
+   *     Ps = 2 5  -> Show Cursor (DECTCEM).
+   *     Ps = 3 0  -> Show scrollbar (rxvt).
+   *     Ps = 3 5  -> Enable font-shifting functions (rxvt).
+   *     Ps = 3 8  -> Enter Tektronix Mode (DECTEK).
+   *     Ps = 4 0  -> Allow 80 -> 132 Mode.
+   *     Ps = 4 1  -> more(1) fix (see curses resource).
+   *     Ps = 4 2  -> Enable Nation Replacement Character sets (DECN-
+   *     RCM).
+   *     Ps = 4 4  -> Turn On Margin Bell.
+   *     Ps = 4 5  -> Reverse-wraparound Mode.
+   *     Ps = 4 6  -> Start Logging.  This is normally disabled by a
+   *     compile-time option.
+   *     Ps = 4 7  -> Use Alternate Screen Buffer.  (This may be dis-
+   *     abled by the titeInhibit resource).
+   *     Ps = 6 6  -> Application keypad (DECNKM).
+   *     Ps = 6 7  -> Backarrow key sends backspace (DECBKM).
+   *     Ps = 1 0 0 0  -> Send Mouse X & Y on button press and
+   *     release.  See the section Mouse Tracking.
+   *     Ps = 1 0 0 1  -> Use Hilite Mouse Tracking.
+   *     Ps = 1 0 0 2  -> Use Cell Motion Mouse Tracking.
+   *     Ps = 1 0 0 3  -> Use All Motion Mouse Tracking.
+   *     Ps = 1 0 0 4  -> Send FocusIn/FocusOut events.
+   *     Ps = 1 0 0 5  -> Enable Extended Mouse Mode.
+   *     Ps = 1 0 1 0  -> Scroll to bottom on tty output (rxvt).
+   *     Ps = 1 0 1 1  -> Scroll to bottom on key press (rxvt).
+   *     Ps = 1 0 3 4  -> Interpret "meta" key, sets eighth bit.
+   *     (enables the eightBitInput resource).
+   *     Ps = 1 0 3 5  -> Enable special modifiers for Alt and Num-
+   *     Lock keys.  (This enables the numLock resource).
+   *     Ps = 1 0 3 6  -> Send ESC   when Meta modifies a key.  (This
+   *     enables the metaSendsEscape resource).
+   *     Ps = 1 0 3 7  -> Send DEL from the editing-keypad Delete
+   *     key.
+   *     Ps = 1 0 3 9  -> Send ESC  when Alt modifies a key.  (This
+   *     enables the altSendsEscape resource).
+   *     Ps = 1 0 4 0  -> Keep selection even if not highlighted.
+   *     (This enables the keepSelection resource).
+   *     Ps = 1 0 4 1  -> Use the CLIPBOARD selection.  (This enables
+   *     the selectToClipboard resource).
+   *     Ps = 1 0 4 2  -> Enable Urgency window manager hint when
+   *     Control-G is received.  (This enables the bellIsUrgent
+   *     resource).
+   *     Ps = 1 0 4 3  -> Enable raising of the window when Control-G
+   *     is received.  (enables the popOnBell resource).
+   *     Ps = 1 0 4 7  -> Use Alternate Screen Buffer.  (This may be
+   *     disabled by the titeInhibit resource).
+   *     Ps = 1 0 4 8  -> Save cursor as in DECSC.  (This may be dis-
+   *     abled by the titeInhibit resource).
+   *     Ps = 1 0 4 9  -> Save cursor as in DECSC and use Alternate
+   *     Screen Buffer, clearing it first.  (This may be disabled by
+   *     the titeInhibit resource).  This combines the effects of the 1
+   *     0 4 7  and 1 0 4 8  modes.  Use this with terminfo-based
+   *     applications rather than the 4 7  mode.
+   *     Ps = 1 0 5 0  -> Set terminfo/termcap function-key mode.
+   *     Ps = 1 0 5 1  -> Set Sun function-key mode.
+   *     Ps = 1 0 5 2  -> Set HP function-key mode.
+   *     Ps = 1 0 5 3  -> Set SCO function-key mode.
+   *     Ps = 1 0 6 0  -> Set legacy keyboard emulation (X11R6).
+   *     Ps = 1 0 6 1  -> Set VT220 keyboard emulation.
+   *     Ps = 2 0 0 4  -> Set bracketed paste mode.
+   * Modes:
+   *   http: *vt100.net/docs/vt220-rm/chapter4.html
+   */
+  public setMode(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 4:
+          this._terminal.insertMode = true;
+          break;
+        case 20:
+          // this._t.convertEol = true;
+          break;
+      }
+    }
+  }
+  public setModePrivate(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 1:
+          this._coreService.decPrivateModes.applicationCursorKeys = true;
+          break;
+        case 2:
+          this._terminal.setgCharset(0, DEFAULT_CHARSET);
+          this._terminal.setgCharset(1, DEFAULT_CHARSET);
+          this._terminal.setgCharset(2, DEFAULT_CHARSET);
+          this._terminal.setgCharset(3, DEFAULT_CHARSET);
+          // set VT100 mode here
+          break;
+        case 3: // 132 col mode
+          // TODO: move DECCOLM into compat addon
+          this._terminal.savedCols = this._bufferService.cols;
+          this._terminal.resize(132, this._bufferService.rows);
+          this._terminal.reset();
+          break;
+        case 6:
+          this._terminal.originMode = true;
+          this._setCursor(0, 0);
+          break;
+        case 7:
+          this._terminal.wraparoundMode = true;
+          break;
+        case 12:
+          // this.cursorBlink = true;
+          break;
+        case 66:
+          this._logService.debug('Serial port requested application keypad.');
+          this._terminal.applicationKeypad = true;
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          break;
+        case 9: // X10 Mouse
+          // no release, no motion, no wheel, no modifiers.
+          this._coreMouseService.activeProtocol = 'X10';
+          break;
+        case 1000: // vt200 mouse
+          // no motion.
+          this._coreMouseService.activeProtocol = 'VT200';
+          break;
+        case 1002: // button event mouse
+          this._coreMouseService.activeProtocol = 'DRAG';
+          break;
+        case 1003: // any event mouse
+          // any event - sends motion events,
+          // even if there is no button held down.
+          this._coreMouseService.activeProtocol = 'ANY';
+          break;
+        case 1004: // send focusin/focusout events
+          // focusin: ^[[I
+          // focusout: ^[[O
+          this._terminal.sendFocus = true;
+          break;
+        case 1005: // utf8 ext mode mouse - removed in #2507
+          this._logService.debug('DECSET 1005 not supported (see #2507)');
+          break;
+        case 1006: // sgr ext mode mouse
+          this._coreMouseService.activeEncoding = 'SGR';
+          break;
+        case 1015: // urxvt ext mode mouse - removed in #2507
+          this._logService.debug('DECSET 1015 not supported (see #2507)');
+          break;
+        case 25: // show cursor
+          this._terminal.cursorHidden = false;
+          break;
+        case 1048: // alt screen cursor
+          this.saveCursor();
+          break;
+        case 1049: // alt screen buffer cursor
+          this.saveCursor();
+          // FALL-THROUGH
+        case 47: // alt screen buffer
+        case 1047: // alt screen buffer
+          this._bufferService.buffers.activateAltBuffer(this._terminal.eraseAttrData());
+          this._terminal.refresh(0, this._bufferService.rows - 1);
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          this._terminal.showCursor();
+          break;
+        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)
+          this._terminal.bracketedPasteMode = true;
+          break;
+      }
+    }
+  }
+
+
+  /**
+   * CSI Pm l  Reset Mode (RM).
+   *     Ps = 2  -> Keyboard Action Mode (AM).
+   *     Ps = 4  -> Replace Mode (IRM).
+   *     Ps = 1 2  -> Send/receive (SRM).
+   *     Ps = 2 0  -> Normal Linefeed (LNM).
+   * CSI ? Pm l
+   *   DEC Private Mode Reset (DECRST).
+   *     Ps = 1  -> Normal Cursor Keys (DECCKM).
+   *     Ps = 2  -> Designate VT52 mode (DECANM).
+   *     Ps = 3  -> 80 Column Mode (DECCOLM).
+   *     Ps = 4  -> Jump (Fast) Scroll (DECSCLM).
+   *     Ps = 5  -> Normal Video (DECSCNM).
+   *     Ps = 6  -> Normal Cursor Mode (DECOM).
+   *     Ps = 7  -> No Wraparound Mode (DECAWM).
+   *     Ps = 8  -> No Auto-repeat Keys (DECARM).
+   *     Ps = 9  -> Don't send Mouse X & Y on button press.
+   *     Ps = 1 0  -> Hide toolbar (rxvt).
+   *     Ps = 1 2  -> Stop Blinking Cursor (att610).
+   *     Ps = 1 8  -> Don't print form feed (DECPFF).
+   *     Ps = 1 9  -> Limit print to scrolling region (DECPEX).
+   *     Ps = 2 5  -> Hide Cursor (DECTCEM).
+   *     Ps = 3 0  -> Don't show scrollbar (rxvt).
+   *     Ps = 3 5  -> Disable font-shifting functions (rxvt).
+   *     Ps = 4 0  -> Disallow 80 -> 132 Mode.
+   *     Ps = 4 1  -> No more(1) fix (see curses resource).
+   *     Ps = 4 2  -> Disable Nation Replacement Character sets (DEC-
+   *     NRCM).
+   *     Ps = 4 4  -> Turn Off Margin Bell.
+   *     Ps = 4 5  -> No Reverse-wraparound Mode.
+   *     Ps = 4 6  -> Stop Logging.  (This is normally disabled by a
+   *     compile-time option).
+   *     Ps = 4 7  -> Use Normal Screen Buffer.
+   *     Ps = 6 6  -> Numeric keypad (DECNKM).
+   *     Ps = 6 7  -> Backarrow key sends delete (DECBKM).
+   *     Ps = 1 0 0 0  -> Don't send Mouse X & Y on button press and
+   *     release.  See the section Mouse Tracking.
+   *     Ps = 1 0 0 1  -> Don't use Hilite Mouse Tracking.
+   *     Ps = 1 0 0 2  -> Don't use Cell Motion Mouse Tracking.
+   *     Ps = 1 0 0 3  -> Don't use All Motion Mouse Tracking.
+   *     Ps = 1 0 0 4  -> Don't send FocusIn/FocusOut events.
+   *     Ps = 1 0 0 5  -> Disable Extended Mouse Mode.
+   *     Ps = 1 0 1 0  -> Don't scroll to bottom on tty output
+   *     (rxvt).
+   *     Ps = 1 0 1 1  -> Don't scroll to bottom on key press (rxvt).
+   *     Ps = 1 0 3 4  -> Don't interpret "meta" key.  (This disables
+   *     the eightBitInput resource).
+   *     Ps = 1 0 3 5  -> Disable special modifiers for Alt and Num-
+   *     Lock keys.  (This disables the numLock resource).
+   *     Ps = 1 0 3 6  -> Don't send ESC  when Meta modifies a key.
+   *     (This disables the metaSendsEscape resource).
+   *     Ps = 1 0 3 7  -> Send VT220 Remove from the editing-keypad
+   *     Delete key.
+   *     Ps = 1 0 3 9  -> Don't send ESC  when Alt modifies a key.
+   *     (This disables the altSendsEscape resource).
+   *     Ps = 1 0 4 0  -> Do not keep selection when not highlighted.
+   *     (This disables the keepSelection resource).
+   *     Ps = 1 0 4 1  -> Use the PRIMARY selection.  (This disables
+   *     the selectToClipboard resource).
+   *     Ps = 1 0 4 2  -> Disable Urgency window manager hint when
+   *     Control-G is received.  (This disables the bellIsUrgent
+   *     resource).
+   *     Ps = 1 0 4 3  -> Disable raising of the window when Control-
+   *     G is received.  (This disables the popOnBell resource).
+   *     Ps = 1 0 4 7  -> Use Normal Screen Buffer, clearing screen
+   *     first if in the Alternate Screen.  (This may be disabled by
+   *     the titeInhibit resource).
+   *     Ps = 1 0 4 8  -> Restore cursor as in DECRC.  (This may be
+   *     disabled by the titeInhibit resource).
+   *     Ps = 1 0 4 9  -> Use Normal Screen Buffer and restore cursor
+   *     as in DECRC.  (This may be disabled by the titeInhibit
+   *     resource).  This combines the effects of the 1 0 4 7  and 1 0
+   *     4 8  modes.  Use this with terminfo-based applications rather
+   *     than the 4 7  mode.
+   *     Ps = 1 0 5 0  -> Reset terminfo/termcap function-key mode.
+   *     Ps = 1 0 5 1  -> Reset Sun function-key mode.
+   *     Ps = 1 0 5 2  -> Reset HP function-key mode.
+   *     Ps = 1 0 5 3  -> Reset SCO function-key mode.
+   *     Ps = 1 0 6 0  -> Reset legacy keyboard emulation (X11R6).
+   *     Ps = 1 0 6 1  -> Reset keyboard emulation to Sun/PC style.
+   *     Ps = 2 0 0 4  -> Reset bracketed paste mode.
+   */
+  public resetMode(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 4:
+          this._terminal.insertMode = false;
+          break;
+        case 20:
+          // this._t.convertEol = false;
+          break;
+      }
+    }
+  }
+  public resetModePrivate(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 1:
+          this._coreService.decPrivateModes.applicationCursorKeys = false;
+          break;
+        case 3:
+          // TODO: move DECCOLM into compat addon
+          // Note: This impl currently does not enforce col 80, instead reverts
+          // to previous terminal width before entering DECCOLM 132
+          if (this._bufferService.cols === 132 && this._terminal.savedCols) {
+            this._terminal.resize(this._terminal.savedCols, this._bufferService.rows);
+          }
+          delete this._terminal.savedCols;
+          this._terminal.reset();
+          break;
+        case 6:
+          this._terminal.originMode = false;
+          this._setCursor(0, 0);
+          break;
+        case 7:
+          this._terminal.wraparoundMode = false;
+          break;
+        case 12:
+          // this.cursorBlink = false;
+          break;
+        case 66:
+          this._logService.debug('Switching back to normal keypad.');
+          this._terminal.applicationKeypad = false;
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          break;
+        case 9: // X10 Mouse
+        case 1000: // vt200 mouse
+        case 1002: // button event mouse
+        case 1003: // any event mouse
+          this._coreMouseService.activeProtocol = 'NONE';
+          break;
+        case 1004: // send focusin/focusout events
+          this._terminal.sendFocus = false;
+          break;
+        case 1005: // utf8 ext mode mouse - removed in #2507
+          this._logService.debug('DECRST 1005 not supported (see #2507)');
+          break;
+        case 1006: // sgr ext mode mouse
+          this._coreMouseService.activeEncoding = 'DEFAULT';
+          break;
+        case 1015: // urxvt ext mode mouse - removed in #2507
+        this._logService.debug('DECRST 1015 not supported (see #2507)');
+          break;
+        case 25: // hide cursor
+          this._terminal.cursorHidden = true;
+          break;
+        case 1048: // alt screen cursor
+          this.restoreCursor();
+          break;
+        case 1049: // alt screen buffer cursor
+           // FALL-THROUGH
+        case 47: // normal screen buffer
+        case 1047: // normal screen buffer - clearing it first
+          // Ensure the selection manager has the correct buffer
+          this._bufferService.buffers.activateNormalBuffer();
+          if (params.params[i] === 1049) {
+            this.restoreCursor();
+          }
+          this._terminal.refresh(0, this._bufferService.rows - 1);
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          this._terminal.showCursor();
+          break;
+        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)
+          this._terminal.bracketedPasteMode = false;
+          break;
+      }
+    }
+  }
+
+  /**
+   * Helper to extract and apply color params/subparams.
+   * Returns advance for params index.
+   */
+  private _extractColor(params: IParams, pos: number, attr: IAttributeData): number {
+    // normalize params
+    // meaning: [target, CM, ign, val, val, val]
+    // RGB    : [ 38/48,  2, ign,   r,   g,   b]
+    // P256   : [ 38/48,  5, ign,   v, ign, ign]
+    const accu = [0, 0, -1, 0, 0, 0];
+
+    // alignment placeholder for non color space sequences
+    let cSpace = 0;
+
+    // return advance we took in params
+    let advance = 0;
+
+    do {
+      accu[advance + cSpace] = params.params[pos + advance];
+      if (params.hasSubParams(pos + advance)) {
+        const subparams = params.getSubParams(pos + advance);
+        let i = 0;
+        do {
+          if (accu[1] === 5) {
+            cSpace = 1;
+          }
+          accu[advance + i + 1 + cSpace] = subparams[i];
+        } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length);
+        break;
+      }
+      // exit early if can decide color mode with semicolons
+      if ((accu[1] === 5 && advance + cSpace >= 2)
+          || (accu[1] === 2 && advance + cSpace >= 5)) {
+        break;
+      }
+      // offset colorSpace slot for semicolon mode
+      if (accu[1]) {
+        cSpace = 1;
+      }
+    } while (++advance + pos < params.length && advance + cSpace < accu.length);
+
+    // set default values to 0
+    for (let i = 2; i < accu.length; ++i) {
+      if (accu[i] === -1) {
+        accu[i] = 0;
+      }
+    }
+
+    // apply colors
+    if (accu[0] === 38) {
+      if (accu[1] === 2) {
+        attr.fg |= Attributes.CM_RGB;
+        attr.fg &= ~Attributes.RGB_MASK;
+        attr.fg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);
+      } else if (accu[1] === 5) {
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.fg |= Attributes.CM_P256 | (accu[3] & 0xff);
+      }
+    } else if (accu[0] === 48) {
+      if (accu[1] === 2) {
+        attr.bg |= Attributes.CM_RGB;
+        attr.bg &= ~Attributes.RGB_MASK;
+        attr.bg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);
+      } else if (accu[1] === 5) {
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.bg |= Attributes.CM_P256 | (accu[3] & 0xff);
+      }
+    }
+
+    return advance;
+  }
+
+  /**
+   * CSI Pm m  Character Attributes (SGR).
+   *     Ps = 0  -> Normal (default).
+   *     Ps = 1  -> Bold.
+   *     Ps = 2  -> Faint, decreased intensity (ISO 6429).
+   *     Ps = 4  -> Underlined.
+   *     Ps = 5  -> Blink (appears as Bold).
+   *     Ps = 7  -> Inverse.
+   *     Ps = 8  -> Invisible, i.e., hidden (VT300).
+   *     Ps = 2 2  -> Normal (neither bold nor faint).
+   *     Ps = 2 4  -> Not underlined.
+   *     Ps = 2 5  -> Steady (not blinking).
+   *     Ps = 2 7  -> Positive (not inverse).
+   *     Ps = 2 8  -> Visible, i.e., not hidden (VT300).
+   *     Ps = 3 0  -> Set foreground color to Black.
+   *     Ps = 3 1  -> Set foreground color to Red.
+   *     Ps = 3 2  -> Set foreground color to Green.
+   *     Ps = 3 3  -> Set foreground color to Yellow.
+   *     Ps = 3 4  -> Set foreground color to Blue.
+   *     Ps = 3 5  -> Set foreground color to Magenta.
+   *     Ps = 3 6  -> Set foreground color to Cyan.
+   *     Ps = 3 7  -> Set foreground color to White.
+   *     Ps = 3 9  -> Set foreground color to default (original).
+   *     Ps = 4 0  -> Set background color to Black.
+   *     Ps = 4 1  -> Set background color to Red.
+   *     Ps = 4 2  -> Set background color to Green.
+   *     Ps = 4 3  -> Set background color to Yellow.
+   *     Ps = 4 4  -> Set background color to Blue.
+   *     Ps = 4 5  -> Set background color to Magenta.
+   *     Ps = 4 6  -> Set background color to Cyan.
+   *     Ps = 4 7  -> Set background color to White.
+   *     Ps = 4 9  -> Set background color to default (original).
+   *
+   *   If 16-color support is compiled, the following apply.  Assume
+   *   that xterm's resources are set so that the ISO color codes are
+   *   the first 8 of a set of 16.  Then the aixterm colors are the
+   *   bright versions of the ISO colors:
+   *     Ps = 9 0  -> Set foreground color to Black.
+   *     Ps = 9 1  -> Set foreground color to Red.
+   *     Ps = 9 2  -> Set foreground color to Green.
+   *     Ps = 9 3  -> Set foreground color to Yellow.
+   *     Ps = 9 4  -> Set foreground color to Blue.
+   *     Ps = 9 5  -> Set foreground color to Magenta.
+   *     Ps = 9 6  -> Set foreground color to Cyan.
+   *     Ps = 9 7  -> Set foreground color to White.
+   *     Ps = 1 0 0  -> Set background color to Black.
+   *     Ps = 1 0 1  -> Set background color to Red.
+   *     Ps = 1 0 2  -> Set background color to Green.
+   *     Ps = 1 0 3  -> Set background color to Yellow.
+   *     Ps = 1 0 4  -> Set background color to Blue.
+   *     Ps = 1 0 5  -> Set background color to Magenta.
+   *     Ps = 1 0 6  -> Set background color to Cyan.
+   *     Ps = 1 0 7  -> Set background color to White.
+   *
+   *   If xterm is compiled with the 16-color support disabled, it
+   *   supports the following, from rxvt:
+   *     Ps = 1 0 0  -> Set foreground and background color to
+   *     default.
+   *
+   *   If 88- or 256-color support is compiled, the following apply.
+   *     Ps = 3 8  ; 5  ; Ps -> Set foreground color to the second
+   *     Ps.
+   *     Ps = 4 8  ; 5  ; Ps -> Set background color to the second
+   *     Ps.
+   */
+  public charAttributes(params: IParams): void {
+    // Optimize a single SGR0.
+    if (params.length === 1 && params.params[0] === 0) {
+      this._terminal.curAttrData.fg = DEFAULT_ATTR_DATA.fg;
+      this._terminal.curAttrData.bg = DEFAULT_ATTR_DATA.bg;
+      return;
+    }
+
+    const l = params.length;
+    let p;
+    const attr = this._terminal.curAttrData;
+
+    for (let i = 0; i < l; i++) {
+      p = params.params[i];
+      if (p >= 30 && p <= 37) {
+        // fg color 8
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.fg |= Attributes.CM_P16 | (p - 30);
+      } else if (p >= 40 && p <= 47) {
+        // bg color 8
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.bg |= Attributes.CM_P16 | (p - 40);
+      } else if (p >= 90 && p <= 97) {
+        // fg color 16
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.fg |= Attributes.CM_P16 | (p - 90) | 8;
+      } else if (p >= 100 && p <= 107) {
+        // bg color 16
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.bg |= Attributes.CM_P16 | (p - 100) | 8;
+      } else if (p === 0) {
+        // default
+        attr.fg = DEFAULT_ATTR_DATA.fg;
+        attr.bg = DEFAULT_ATTR_DATA.bg;
+      } else if (p === 1) {
+        // bold text
+        attr.fg |= FgFlags.BOLD;
+      } else if (p === 3) {
+        // italic text
+        attr.bg |= BgFlags.ITALIC;
+      } else if (p === 4) {
+        // underlined text
+        attr.fg |= FgFlags.UNDERLINE;
+      } else if (p === 5) {
+        // blink
+        attr.fg |= FgFlags.BLINK;
+      } else if (p === 7) {
+        // inverse and positive
+        // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
+        attr.fg |= FgFlags.INVERSE;
+      } else if (p === 8) {
+        // invisible
+        attr.fg |= FgFlags.INVISIBLE;
+      } else if (p === 2) {
+        // dimmed text
+        attr.bg |= BgFlags.DIM;
+      } else if (p === 22) {
+        // not bold nor faint
+        attr.fg &= ~FgFlags.BOLD;
+        attr.bg &= ~BgFlags.DIM;
+      } else if (p === 23) {
+        // not italic
+        attr.bg &= ~BgFlags.ITALIC;
+      } else if (p === 24) {
+        // not underlined
+        attr.fg &= ~FgFlags.UNDERLINE;
+      } else if (p === 25) {
+        // not blink
+        attr.fg &= ~FgFlags.BLINK;
+      } else if (p === 27) {
+        // not inverse
+        attr.fg &= ~FgFlags.INVERSE;
+      } else if (p === 28) {
+        // not invisible
+        attr.fg &= ~FgFlags.INVISIBLE;
+      } else if (p === 39) {
+        // reset fg
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+      } else if (p === 49) {
+        // reset bg
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+      } else if (p === 38 || p === 48) {
+        // fg color 256 and RGB
+        i += this._extractColor(params, i, attr);
+      } else if (p === 100) {
+        // reset fg/bg
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+      } else {
+        this._logService.debug('Unknown SGR attribute: %d.', p);
+      }
+    }
+  }
+
+  /**
+   * CSI Ps n  Device Status Report (DSR).
+   *     Ps = 5  -> Status Report.  Result (``OK'') is
+   *   CSI 0 n
+   *     Ps = 6  -> Report Cursor Position (CPR) [row;column].
+   *   Result is
+   *   CSI r ; c R
+   * CSI ? Ps n
+   *   Device Status Report (DSR, DEC-specific).
+   *     Ps = 6  -> Report Cursor Position (CPR) [row;column] as CSI
+   *     ? r ; c R (assumes page is zero).
+   *     Ps = 1 5  -> Report Printer status as CSI ? 1 0  n  (ready).
+   *     or CSI ? 1 1  n  (not ready).
+   *     Ps = 2 5  -> Report UDK status as CSI ? 2 0  n  (unlocked)
+   *     or CSI ? 2 1  n  (locked).
+   *     Ps = 2 6  -> Report Keyboard status as
+   *   CSI ? 2 7  ;  1  ;  0  ;  0  n  (North American).
+   *   The last two parameters apply to VT400 & up, and denote key-
+   *   board ready and LK01 respectively.
+   *     Ps = 5 3  -> Report Locator status as
+   *   CSI ? 5 3  n  Locator available, if compiled-in, or
+   *   CSI ? 5 0  n  No Locator, if not.
+   */
+  public deviceStatus(params: IParams): void {
+    switch (params.params[0]) {
+      case 5:
+        // status report
+        this._coreService.triggerDataEvent(`${C0.ESC}[0n`);
+        break;
+      case 6:
+        // cursor position
+        const y = this._bufferService.buffer.y + 1;
+        const x = this._bufferService.buffer.x + 1;
+        this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`);
+        break;
+    }
+  }
+
+  public deviceStatusPrivate(params: IParams): void {
+    // modern xterm doesnt seem to
+    // respond to any of these except ?6, 6, and 5
+    switch (params.params[0]) {
+      case 6:
+        // cursor position
+        const y = this._bufferService.buffer.y + 1;
+        const x = this._bufferService.buffer.x + 1;
+        this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`);
+        break;
+      case 15:
+        // no printer
+        // this.handler(C0.ESC + '[?11n');
+        break;
+      case 25:
+        // dont support user defined keys
+        // this.handler(C0.ESC + '[?21n');
+        break;
+      case 26:
+        // north american keyboard
+        // this.handler(C0.ESC + '[?27;1;0;0n');
+        break;
+      case 53:
+        // no dec locator/mouse
+        // this.handler(C0.ESC + '[?50n');
+        break;
+    }
+  }
+
+  /**
+   * CSI ! p   Soft terminal reset (DECSTR).
+   * http://vt100.net/docs/vt220-rm/table4-10.html
+   */
+  public softReset(params: IParams): void {
+    this._terminal.cursorHidden = false;
+    this._terminal.insertMode = false;
+    this._terminal.originMode = false;
+    this._terminal.wraparoundMode = true;  // defaults: xterm - true, vt100 - false
+    this._terminal.applicationKeypad = false; // ?
+    if (this._terminal.viewport) {
+      this._terminal.viewport.syncScrollArea();
+    }
+    this._coreService.decPrivateModes.applicationCursorKeys = false;
+    this._bufferService.buffer.scrollTop = 0;
+    this._bufferService.buffer.scrollBottom = this._bufferService.rows - 1;
+    this._terminal.curAttrData = DEFAULT_ATTR_DATA.clone();
+    this._bufferService.buffer.x = this._bufferService.buffer.y = 0; // ?
+    this._terminal.charset = null;
+    this._terminal.glevel = 0; // ??
+    this._terminal.charsets = [null]; // ??
+  }
+
+  /**
+   * CSI Ps SP q  Set cursor style (DECSCUSR, VT520).
+   *   Ps = 0  -> blinking block.
+   *   Ps = 1  -> blinking block (default).
+   *   Ps = 2  -> steady block.
+   *   Ps = 3  -> blinking underline.
+   *   Ps = 4  -> steady underline.
+   *   Ps = 5  -> blinking bar (xterm).
+   *   Ps = 6  -> steady bar (xterm).
+   */
+  public setCursorStyle(params: IParams): void {
+    const param = params.params[0] || 1;
+    switch (param) {
+      case 1:
+      case 2:
+        this._optionsService.options.cursorStyle = 'block';
+        break;
+      case 3:
+      case 4:
+        this._optionsService.options.cursorStyle = 'underline';
+        break;
+      case 5:
+      case 6:
+        this._optionsService.options.cursorStyle = 'bar';
+        break;
+    }
+    const isBlinking = param % 2 === 1;
+    this._optionsService.options.cursorBlink = isBlinking;
+  }
+
+  /**
+   * CSI Ps ; Ps r
+   *   Set Scrolling Region [top;bottom] (default = full size of win-
+   *   dow) (DECSTBM).
+   */
+  public setScrollRegion(params: IParams): void {
+    const top = params.params[0] || 1;
+    let bottom: number;
+
+    if (params.length < 2 || (bottom = params.params[1]) >  this._bufferService.rows || bottom === 0) {
+      bottom = this._bufferService.rows;
+    }
+
+    if (bottom > top) {
+      this._bufferService.buffer.scrollTop = top - 1;
+      this._bufferService.buffer.scrollBottom = bottom - 1;
+      this._setCursor(0, 0);
+    }
+  }
+
+
+  /**
+   * CSI s
+   * ESC 7
+   *   Save cursor (ANSI.SYS).
+   */
+  public saveCursor(params?: IParams): void {
+    this._bufferService.buffer.savedX = this._bufferService.buffer.x;
+    this._bufferService.buffer.savedY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;
+    this._bufferService.buffer.savedCurAttrData.fg = this._terminal.curAttrData.fg;
+    this._bufferService.buffer.savedCurAttrData.bg = this._terminal.curAttrData.bg;
+    this._bufferService.buffer.savedCharset = this._terminal.charset;
+  }
+
+
+  /**
+   * CSI u
+   * ESC 8
+   *   Restore cursor (ANSI.SYS).
+   */
+  public restoreCursor(params?: IParams): void {
+    this._bufferService.buffer.x = this._bufferService.buffer.savedX || 0;
+    this._bufferService.buffer.y = Math.max(this._bufferService.buffer.savedY - this._bufferService.buffer.ybase, 0);
+    this._terminal.curAttrData.fg = this._bufferService.buffer.savedCurAttrData.fg;
+    this._terminal.curAttrData.bg = this._bufferService.buffer.savedCurAttrData.bg;
+    this._terminal.charset = (this as any)._savedCharset;
+    if (this._bufferService.buffer.savedCharset) {
+      this._terminal.charset = this._bufferService.buffer.savedCharset;
+    }
+    this._restrictCursor();
+  }
+
+
+  /**
+   * OSC 0; <data> ST (set icon name + window title)
+   * OSC 2; <data> ST (set window title)
+   *   Proxy to set window title. Icon name is not supported.
+   */
+  public setTitle(data: string): void {
+    this._terminal.handleTitle(data);
+  }
+
+  /**
+   * ESC E
+   * C1.NEL
+   *   DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL)
+   *   Moves cursor to first position on next line.
+   */
+  public nextLine(): void {
+    this._bufferService.buffer.x = 0;
+    this.index();
+  }
+
+  /**
+   * ESC =
+   *   DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html)
+   *   Enables the numeric keypad to send application sequences to the host.
+   */
+  public keypadApplicationMode(): void {
+    this._logService.debug('Serial port requested application keypad.');
+    this._terminal.applicationKeypad = true;
+    if (this._terminal.viewport) {
+      this._terminal.viewport.syncScrollArea();
+    }
+  }
+
+  /**
+   * ESC >
+   *   DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html)
+   *   Enables the keypad to send numeric characters to the host.
+   */
+  public keypadNumericMode(): void {
+    this._logService.debug('Switching back to normal keypad.');
+    this._terminal.applicationKeypad = false;
+    if (this._terminal.viewport) {
+      this._terminal.viewport.syncScrollArea();
+    }
+  }
+
+  /**
+   * ESC % @
+   * ESC % G
+   *   Select default character set. UTF-8 is not supported (string are unicode anyways)
+   *   therefore ESC % G does the same.
+   */
+  public selectDefaultCharset(): void {
+    this._terminal.setgLevel(0);
+    this._terminal.setgCharset(0, DEFAULT_CHARSET); // US (default)
+  }
+
+  /**
+   * ESC ( C
+   *   Designate G0 Character Set, VT100, ISO 2022.
+   * ESC ) C
+   *   Designate G1 Character Set (ISO 2022, VT100).
+   * ESC * C
+   *   Designate G2 Character Set (ISO 2022, VT220).
+   * ESC + C
+   *   Designate G3 Character Set (ISO 2022, VT220).
+   * ESC - C
+   *   Designate G1 Character Set (VT300).
+   * ESC . C
+   *   Designate G2 Character Set (VT300).
+   * ESC / C
+   *   Designate G3 Character Set (VT300). C = A  -> ISO Latin-1 Supplemental. - Supported?
+   */
+  public selectCharset(collectAndFlag: string): void {
+    if (collectAndFlag.length !== 2) {
+      this.selectDefaultCharset();
+      return;
+    }
+    if (collectAndFlag[0] === '/') {
+      return;  // TODO: Is this supported?
+    }
+    this._terminal.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET);
+    return;
+  }
+
+  /**
+   * ESC D
+   * C1.IND
+   *   DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html)
+   *   Moves the cursor down one line in the same column.
+   */
+  public index(): void {
+    this._restrictCursor();
+    const buffer = this._bufferService.buffer;
+    this._bufferService.buffer.y++;
+    if (buffer.y === buffer.scrollBottom + 1) {
+      buffer.y--;
+      this._terminal.scroll();
+    } else if (buffer.y >= this._bufferService.rows) {
+      buffer.y = this._bufferService.rows - 1;
+    }
+    this._restrictCursor();
+  }
+
+  /**
+   * ESC H
+   * C1.HTS
+   *   DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html)
+   *   Sets a horizontal tab stop at the column position indicated by
+   *   the value of the active column when the terminal receives an HTS.
+   */
+  public tabSet(): void {
+    this._bufferService.buffer.tabs[this._bufferService.buffer.x] = true;
+  }
+
+  /**
+   * ESC M
+   * C1.RI
+   *   DEC mnemonic: HTS
+   *   Moves the cursor up one line in the same column. If the cursor is at the top margin,
+   *   the page scrolls down.
+   */
+  public reverseIndex(): void {
+    this._restrictCursor();
+    const buffer = this._bufferService.buffer;
+    if (buffer.y === buffer.scrollTop) {
+      // possibly move the code below to term.reverseScroll();
+      // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
+      // blankLine(true) is xterm/linux behavior
+      const scrollRegionHeight = buffer.scrollBottom - buffer.scrollTop;
+      buffer.lines.shiftElements(buffer.y + buffer.ybase, scrollRegionHeight, 1);
+      buffer.lines.set(buffer.y + buffer.ybase, buffer.getBlankLine(this._terminal.eraseAttrData()));
+      this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+    } else {
+      buffer.y--;
+      this._restrictCursor(); // quickfix to not run out of bounds
+    }
+  }
+
+  /**
+   * ESC c
+   *   DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html)
+   *   Reset to initial state.
+   */
+  public reset(): void {
+    this._parser.reset();
+    this._terminal.reset();  // TODO: save to move from terminal?
+  }
+
+  /**
+   * ESC n
+   * ESC o
+   * ESC |
+   * ESC }
+   * ESC ~
+   *   DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html)
+   *   When you use a locking shift, the character set remains in GL or GR until
+   *   you use another locking shift. (partly supported)
+   */
+  public setgLevel(level: number): void {
+    this._terminal.setgLevel(level);  // TODO: save to move from terminal?
+  }
+
+  /**
+   * ESC # 8
+   *   DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html)
+   *   This control function fills the complete screen area with
+   *   a test pattern (E) used for adjusting screen alignment.
+   *
+   * TODO: move DECALN into compat addon
+   */
+  public screenAlignmentPattern(): void {
+    // prepare cell data
+    const cell = new CellData();
+    cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0);
+    cell.fg = this._terminal.curAttrData.fg;
+    cell.bg = this._terminal.curAttrData.bg;
+
+    const buffer = this._bufferService.buffer;
+
+    this._setCursor(0, 0);
+    for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) {
+      const row = buffer.y + buffer.ybase + yOffset;
+      buffer.lines.get(row).fill(cell);
+      buffer.lines.get(row).isWrapped = false;
+    }
+    this._dirtyRowService.markAllDirty();
+    this._setCursor(0, 0);
+  }
+}
diff --git a/node_modules/xterm/src/Terminal.ts b/node_modules/xterm/src/Terminal.ts
new file mode 100644 (file)
index 0000000..3e7e55c
--- /dev/null
@@ -0,0 +1,1610 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * @license MIT
+ *
+ * Originally forked from (with the author's permission):
+ *   Fabrice Bellard's javascript vt100 for jslinux:
+ *   http://bellard.org/jslinux/
+ *   Copyright (c) 2011 Fabrice Bellard
+ *   The original design remains. The terminal itself
+ *   has been extended to include xterm CSI codes, among
+ *   other features.
+ *
+ * Terminal Emulation References:
+ *   http://vt100.net/
+ *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
+ *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+ *   http://invisible-island.net/vttest/
+ *   http://www.inwap.com/pdp10/ansicode.txt
+ *   http://linux.die.net/man/4/console_codes
+ *   http://linux.die.net/man/7/urxvt
+ */
+
+import { IInputHandlingTerminal, ICompositionHelper, ITerminalOptions, ITerminal, IBrowser, CustomKeyEventHandler } from './Types';
+import { IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { CompositionHelper } from 'browser/input/CompositionHelper';
+import { Viewport } from 'browser/Viewport';
+import { rightClickHandler, moveTextAreaUnderMouseCursor, handlePasteEvent, copyHandler, paste } from 'browser/Clipboard';
+import { C0 } from 'common/data/EscapeSequences';
+import { InputHandler } from './InputHandler';
+import { Renderer } from './renderer/Renderer';
+import { Linkifier } from 'browser/Linkifier';
+import { SelectionService } from 'browser/services/SelectionService';
+import * as Browser from 'common/Platform';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import * as Strings from 'browser/LocalizableStrings';
+import { SoundService } from 'browser/services/SoundService';
+import { MouseZoneManager } from 'browser/MouseZoneManager';
+import { AccessibilityManager } from './AccessibilityManager';
+import { ITheme, IMarker, IDisposable, ISelectionPosition } from 'xterm';
+import { DomRenderer } from './renderer/dom/DomRenderer';
+import { IKeyboardEvent, KeyboardResultType, ICharset, IBufferLine, IAttributeData, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';
+import { evaluateKeyboardEvent } from 'common/input/Keyboard';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
+import { applyWindowsMode } from './WindowsMode';
+import { ColorManager } from 'browser/ColorManager';
+import { RenderService } from 'browser/services/RenderService';
+import { IOptionsService, IBufferService, ICoreMouseService, ICoreService, ILogService, IDirtyRowService, IInstantiationService } from 'common/services/Services';
+import { OptionsService } from 'common/services/OptionsService';
+import { ICharSizeService, IRenderService, IMouseService, ISelectionService, ISoundService } from 'browser/services/Services';
+import { CharSizeService } from 'browser/services/CharSizeService';
+import { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService';
+import { Disposable } from 'common/Lifecycle';
+import { IBufferSet, IBuffer } from 'common/buffer/Types';
+import { Attributes } from 'common/buffer/Constants';
+import { MouseService } from 'browser/services/MouseService';
+import { IParams, IFunctionIdentifier } from 'common/parser/Types';
+import { CoreService } from 'common/services/CoreService';
+import { LogService } from 'common/services/LogService';
+import { ILinkifier, IMouseZoneManager, LinkMatcherHandler, ILinkMatcherOptions, IViewport } from 'browser/Types';
+import { DirtyRowService } from 'common/services/DirtyRowService';
+import { InstantiationService } from 'common/services/InstantiationService';
+import { CoreMouseService } from 'common/services/CoreMouseService';
+import { WriteBuffer } from 'common/input/WriteBuffer';
+
+// Let it work inside Node.js for automated testing purposes.
+const document = (typeof window !== 'undefined') ? window.document : null;
+
+
+export class Terminal extends Disposable implements ITerminal, IDisposable, IInputHandlingTerminal {
+  public textarea: HTMLTextAreaElement;
+  public element: HTMLElement;
+  public screenElement: HTMLElement;
+
+  /**
+   * The HTMLElement that the terminal is created in, set by Terminal.open.
+   */
+  private _parent: HTMLElement | null;
+  private _document: Document;
+  private _viewportScrollArea: HTMLElement;
+  private _viewportElement: HTMLElement;
+  private _helperContainer: HTMLElement;
+  private _compositionView: HTMLElement;
+
+  private _visualBellTimer: number;
+
+  public browser: IBrowser = <any>Browser;
+
+  // TODO: We should remove options once components adopt optionsService
+  public get options(): ITerminalOptions { return this.optionsService.options; }
+
+  // TODO: This can be changed to an enum or boolean, 0 and 1 seem to be the only options
+  public cursorState: number;
+  public cursorHidden: boolean;
+
+  private _customKeyEventHandler: CustomKeyEventHandler;
+
+  // common services
+  private _bufferService: IBufferService;
+  private _coreService: ICoreService;
+  private _coreMouseService: ICoreMouseService;
+  private _dirtyRowService: IDirtyRowService;
+  private _instantiationService: IInstantiationService;
+  private _logService: ILogService;
+  public optionsService: IOptionsService;
+
+  // browser services
+  private _charSizeService: ICharSizeService;
+  private _mouseService: IMouseService;
+  private _renderService: IRenderService;
+  private _selectionService: ISelectionService;
+  private _soundService: ISoundService;
+
+  // modes
+  public applicationKeypad: boolean;
+  public originMode: boolean;
+  public insertMode: boolean;
+  public wraparoundMode: boolean; // defaults: xterm - true, vt100 - false
+  public bracketedPasteMode: boolean;
+
+  // charset
+  // The current charset
+  public charset: ICharset;
+  public gcharset: number;
+  public glevel: number;
+  public charsets: ICharset[];
+
+  // mouse properties
+  public mouseEvents: CoreMouseEventType = CoreMouseEventType.NONE;
+  public sendFocus: boolean;
+
+  // misc
+  public savedCols: number;
+
+  public curAttrData: IAttributeData;
+  private _eraseAttrData: IAttributeData;
+
+  public params: (string | number)[];
+  public currentParam: string | number;
+
+  // write buffer
+  private _writeBuffer: WriteBuffer;
+
+  // Store if user went browsing history in scrollback
+  private _userScrolling: boolean;
+
+  /**
+   * Records whether the keydown event has already been handled and triggered a data event, if so
+   * the keypress event should not trigger a data event but should still print to the textarea so
+   * screen readers will announce it.
+   */
+  private _keyDownHandled: boolean = false;
+
+  private _inputHandler: InputHandler;
+  public linkifier: ILinkifier;
+  public viewport: IViewport;
+  private _compositionHelper: ICompositionHelper;
+  private _mouseZoneManager: IMouseZoneManager;
+  private _accessibilityManager: AccessibilityManager;
+  private _colorManager: ColorManager;
+  private _theme: ITheme;
+  private _windowsMode: IDisposable | undefined;
+
+  // bufferline to clone/copy from for new blank lines
+  private _blankLine: IBufferLine = null;
+
+  public get cols(): number { return this._bufferService.cols; }
+  public get rows(): number { return this._bufferService.rows; }
+
+  private _onCursorMove = new EventEmitter<void>();
+  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }
+  private _onData = new EventEmitter<string>();
+  public get onData(): IEvent<string> { return this._onData.event; }
+  private _onKey = new EventEmitter<{ key: string, domEvent: KeyboardEvent }>();
+  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._onKey.event; }
+  private _onLineFeed = new EventEmitter<void>();
+  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }
+  private _onRender = new EventEmitter<{ start: number, end: number }>();
+  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }
+  private _onResize = new EventEmitter<{ cols: number, rows: number }>();
+  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._onResize.event; }
+  private _onScroll = new EventEmitter<number>();
+  public get onScroll(): IEvent<number> { return this._onScroll.event; }
+  private _onSelectionChange = new EventEmitter<void>();
+  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }
+  private _onTitleChange = new EventEmitter<string>();
+  public get onTitleChange(): IEvent<string> { return this._onTitleChange.event; }
+
+  private _onFocus = new EventEmitter<void>();
+  public get onFocus(): IEvent<void> { return this._onFocus.event; }
+  private _onBlur = new EventEmitter<void>();
+  public get onBlur(): IEvent<void> { return this._onBlur.event; }
+  public onA11yCharEmitter = new EventEmitter<string>();
+  public get onA11yChar(): IEvent<string> { return this.onA11yCharEmitter.event; }
+  public onA11yTabEmitter = new EventEmitter<number>();
+  public get onA11yTab(): IEvent<number> { return this.onA11yTabEmitter.event; }
+
+  /**
+   * Creates a new `Terminal` object.
+   *
+   * @param options An object containing a set of options, the available options are:
+   *   - `cursorBlink` (boolean): Whether the terminal cursor blinks
+   *   - `cols` (number): The number of columns of the terminal (horizontal size)
+   *   - `rows` (number): The number of rows of the terminal (vertical size)
+   *
+   * @public
+   * @class Xterm Xterm
+   * @alias module:xterm/src/xterm
+   */
+  constructor(
+    options: ITerminalOptions = {}
+  ) {
+    super();
+
+    // Setup and initialize common services
+    this._instantiationService = new InstantiationService();
+    this.optionsService = new OptionsService(options);
+    this._instantiationService.setService(IOptionsService, this.optionsService);
+    this._bufferService = this._instantiationService.createInstance(BufferService);
+    this._instantiationService.setService(IBufferService, this._bufferService);
+    this._logService = this._instantiationService.createInstance(LogService);
+    this._instantiationService.setService(ILogService, this._logService);
+    this._coreService = this._instantiationService.createInstance(CoreService, () => this.scrollToBottom());
+    this._instantiationService.setService(ICoreService, this._coreService);
+    this._coreService.onData(e => this._onData.fire(e));
+    this._coreMouseService = this._instantiationService.createInstance(CoreMouseService);
+    this._instantiationService.setService(ICoreMouseService, this._coreMouseService);
+    this._dirtyRowService = this._instantiationService.createInstance(DirtyRowService);
+    this._instantiationService.setService(IDirtyRowService, this._dirtyRowService);
+
+    this._setupOptionsListeners();
+    this._setup();
+
+    this._writeBuffer = new WriteBuffer(data => this._inputHandler.parse(data));
+  }
+
+  public dispose(): void {
+    if (this._isDisposed) {
+      return;
+    }
+    super.dispose();
+    if (this._windowsMode) {
+      this._windowsMode.dispose();
+      this._windowsMode = undefined;
+    }
+    if (this._renderService) {
+      this._renderService.dispose();
+    }
+    this._customKeyEventHandler = null;
+    this.write = () => {};
+    if (this.element && this.element.parentNode) {
+      this.element.parentNode.removeChild(this.element);
+    }
+  }
+
+  private _setup(): void {
+    this._parent = document ? document.body : null;
+
+    this.cursorState = 0;
+    this.cursorHidden = false;
+    this._customKeyEventHandler = null;
+
+    // modes
+    this.applicationKeypad = false;
+    this.originMode = false;
+    this.insertMode = false;
+    this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
+    this.bracketedPasteMode = false;
+
+    // charset
+    this.charset = null;
+    this.gcharset = null;
+    this.glevel = 0;
+    // TODO: Can this be just []?
+    this.charsets = [null];
+
+    this.curAttrData = DEFAULT_ATTR_DATA.clone();
+    this._eraseAttrData = DEFAULT_ATTR_DATA.clone();
+
+    this.params = [];
+    this.currentParam = 0;
+
+    this._userScrolling = false;
+
+    // Register input handler and refire/handle events
+    this._inputHandler = new InputHandler(this, this._bufferService, this._coreService, this._dirtyRowService, this._logService, this.optionsService, this._coreMouseService);
+    this._inputHandler.onCursorMove(() => this._onCursorMove.fire());
+    this._inputHandler.onLineFeed(() => this._onLineFeed.fire());
+    this.register(this._inputHandler);
+
+    this.linkifier = this.linkifier || new Linkifier(this._bufferService, this._logService);
+
+    if (this.options.windowsMode) {
+      this._windowsMode = applyWindowsMode(this);
+    }
+  }
+
+  /**
+   * Convenience property to active buffer.
+   */
+  public get buffer(): IBuffer {
+    return this.buffers.active;
+  }
+
+  public get buffers(): IBufferSet {
+    return this._bufferService.buffers;
+  }
+
+  /**
+   * back_color_erase feature for xterm.
+   */
+  public eraseAttrData(): IAttributeData {
+    this._eraseAttrData.bg &= ~(Attributes.CM_MASK | 0xFFFFFF);
+    this._eraseAttrData.bg |= this.curAttrData.bg & ~0xFC000000;
+    return this._eraseAttrData;
+  }
+
+  /**
+   * Focus the terminal. Delegates focus handling to the terminal's DOM element.
+   */
+  public focus(): void {
+    if (this.textarea) {
+      this.textarea.focus({ preventScroll: true });
+    }
+  }
+
+  public get isFocused(): boolean {
+    return document.activeElement === this.textarea && document.hasFocus();
+  }
+
+  private _setupOptionsListeners(): void {
+    // TODO: These listeners should be owned by individual components
+    this.optionsService.onOptionChange(key => {
+      switch (key) {
+        case 'fontFamily':
+        case 'fontSize':
+          // When the font changes the size of the cells may change which requires a renderer clear
+          if (this._renderService) {
+            this._renderService.clear();
+          }
+          if (this._charSizeService) {
+            this._charSizeService.measure();
+          }
+          break;
+        case 'drawBoldTextInBrightColors':
+        case 'letterSpacing':
+        case 'lineHeight':
+        case 'fontWeight':
+        case 'fontWeightBold':
+          // When the font changes the size of the cells may change which requires a renderer clear
+          if (this._renderService) {
+            this._renderService.clear();
+            this._renderService.onResize(this.cols, this.rows);
+            this.refresh(0, this.rows - 1);
+          }
+          break;
+        case 'rendererType':
+          if (this._renderService) {
+            this._renderService.setRenderer(this._createRenderer());
+            this._renderService.onResize(this.cols, this.rows);
+          }
+          break;
+        case 'scrollback':
+          this.buffers.resize(this.cols, this.rows);
+          if (this.viewport) {
+            this.viewport.syncScrollArea();
+          }
+          break;
+        case 'screenReaderMode':
+          if (this.optionsService.options.screenReaderMode) {
+            if (!this._accessibilityManager && this._renderService) {
+              this._accessibilityManager = new AccessibilityManager(this, this._renderService);
+            }
+          } else {
+            if (this._accessibilityManager) {
+              this._accessibilityManager.dispose();
+              this._accessibilityManager = null;
+            }
+          }
+          break;
+        case 'tabStopWidth': this.buffers.setupTabStops(); break;
+        case 'theme':
+          this._setTheme(this.optionsService.options.theme);
+          break;
+        case 'windowsMode':
+          if (this.optionsService.options.windowsMode) {
+            if (!this._windowsMode) {
+              this._windowsMode = applyWindowsMode(this);
+            }
+          } else {
+            if (this._windowsMode) {
+              this._windowsMode.dispose();
+              this._windowsMode = undefined;
+            }
+          }
+          break;
+      }
+    });
+  }
+
+  /**
+   * Binds the desired focus behavior on a given terminal object.
+   */
+  private _onTextAreaFocus(ev: KeyboardEvent): void {
+    if (this.sendFocus) {
+      this._coreService.triggerDataEvent(C0.ESC + '[I');
+    }
+    this.updateCursorStyle(ev);
+    this.element.classList.add('focus');
+    this.showCursor();
+    this._onFocus.fire();
+  }
+
+  /**
+   * Blur the terminal, calling the blur function on the terminal's underlying
+   * textarea.
+   */
+  public blur(): void {
+    return this.textarea.blur();
+  }
+
+  /**
+   * Binds the desired blur behavior on a given terminal object.
+   */
+  private _onTextAreaBlur(): void {
+    // Text can safely be removed on blur. Doing it earlier could interfere with
+    // screen readers reading it out.
+    this.textarea.value = '';
+    this.refresh(this.buffer.y, this.buffer.y);
+    if (this.sendFocus) {
+      this._coreService.triggerDataEvent(C0.ESC + '[O');
+    }
+    this.element.classList.remove('focus');
+    this._onBlur.fire();
+  }
+
+  /**
+   * Initialize default behavior
+   */
+  private _initGlobal(): void {
+    this._bindKeys();
+
+    // Bind clipboard functionality
+    this.register(addDisposableDomListener(this.element, 'copy', (event: ClipboardEvent) => {
+      // If mouse events are active it means the selection manager is disabled and
+      // copy should be handled by the host program.
+      if (!this.hasSelection()) {
+        return;
+      }
+      copyHandler(event, this._selectionService);
+    }));
+    const pasteHandlerWrapper = (event: ClipboardEvent) => handlePasteEvent(event, this.textarea, this.bracketedPasteMode, this._coreService);
+    this.register(addDisposableDomListener(this.textarea, 'paste', pasteHandlerWrapper));
+    this.register(addDisposableDomListener(this.element, 'paste', pasteHandlerWrapper));
+
+    // Handle right click context menus
+    if (Browser.isFirefox) {
+      // Firefox doesn't appear to fire the contextmenu event on right click
+      this.register(addDisposableDomListener(this.element, 'mousedown', (event: MouseEvent) => {
+        if (event.button === 2) {
+          rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);
+        }
+      }));
+    } else {
+      this.register(addDisposableDomListener(this.element, 'contextmenu', (event: MouseEvent) => {
+        rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);
+      }));
+    }
+
+    // Move the textarea under the cursor when middle clicking on Linux to ensure
+    // middle click to paste selection works. This only appears to work in Chrome
+    // at the time is writing.
+    if (Browser.isLinux) {
+      // Use auxclick event over mousedown the latter doesn't seem to work. Note
+      // that the regular click event doesn't fire for the middle mouse button.
+      this.register(addDisposableDomListener(this.element, 'auxclick', (event: MouseEvent) => {
+        if (event.button === 1) {
+          moveTextAreaUnderMouseCursor(event, this.textarea, this.screenElement);
+        }
+      }));
+    }
+  }
+
+  /**
+   * Apply key handling to the terminal
+   */
+  private _bindKeys(): void {
+    this.register(addDisposableDomListener(this.textarea, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true));
+    this.register(addDisposableDomListener(this.textarea, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true));
+    this.register(addDisposableDomListener(this.textarea, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true));
+    this.register(addDisposableDomListener(this.textarea, 'compositionstart', () => this._compositionHelper.compositionstart()));
+    this.register(addDisposableDomListener(this.textarea, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper.compositionupdate(e)));
+    this.register(addDisposableDomListener(this.textarea, 'compositionend', () => this._compositionHelper.compositionend()));
+    this.register(this.onRender(() => this._compositionHelper.updateCompositionElements()));
+    this.register(this.onRender(e => this._queueLinkification(e.start, e.end)));
+  }
+
+  /**
+   * Opens the terminal within an element.
+   *
+   * @param parent The element to create the terminal within.
+   */
+  public open(parent: HTMLElement): void {
+    this._parent = parent || this._parent;
+
+    if (!this._parent) {
+      throw new Error('Terminal requires a parent element.');
+    }
+
+    if (!document.body.contains(parent)) {
+      this._logService.warn('Terminal.open was called on an element that was not attached to the DOM');
+    }
+
+    this._document = this._parent.ownerDocument;
+
+    // Create main element container
+    this.element = this._document.createElement('div');
+    this.element.dir = 'ltr';   // xterm.css assumes LTR
+    this.element.classList.add('terminal');
+    this.element.classList.add('xterm');
+    this.element.setAttribute('tabindex', '0');
+    this._parent.appendChild(this.element);
+
+    // Performance: Use a document fragment to build the terminal
+    // viewport and helper elements detached from the DOM
+    const fragment = document.createDocumentFragment();
+    this._viewportElement = document.createElement('div');
+    this._viewportElement.classList.add('xterm-viewport');
+    fragment.appendChild(this._viewportElement);
+    this._viewportScrollArea = document.createElement('div');
+    this._viewportScrollArea.classList.add('xterm-scroll-area');
+    this._viewportElement.appendChild(this._viewportScrollArea);
+
+    this.screenElement = document.createElement('div');
+    this.screenElement.classList.add('xterm-screen');
+    // Create the container that will hold helpers like the textarea for
+    // capturing DOM Events. Then produce the helpers.
+    this._helperContainer = document.createElement('div');
+    this._helperContainer.classList.add('xterm-helpers');
+    this.screenElement.appendChild(this._helperContainer);
+    fragment.appendChild(this.screenElement);
+
+    this.textarea = document.createElement('textarea');
+    this.textarea.classList.add('xterm-helper-textarea');
+    this.textarea.setAttribute('aria-label', Strings.promptLabel);
+    this.textarea.setAttribute('aria-multiline', 'false');
+    this.textarea.setAttribute('autocorrect', 'off');
+    this.textarea.setAttribute('autocapitalize', 'off');
+    this.textarea.setAttribute('spellcheck', 'false');
+    this.textarea.tabIndex = 0;
+    this.register(addDisposableDomListener(this.textarea, 'focus', (ev: KeyboardEvent) => this._onTextAreaFocus(ev)));
+    this.register(addDisposableDomListener(this.textarea, 'blur', () => this._onTextAreaBlur()));
+    this._helperContainer.appendChild(this.textarea);
+
+    this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer);
+    this._instantiationService.setService(ICharSizeService, this._charSizeService);
+
+    this._compositionView = document.createElement('div');
+    this._compositionView.classList.add('composition-view');
+    this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView);
+    this._helperContainer.appendChild(this._compositionView);
+
+    // Performance: Add viewport and helper elements from the fragment
+    this.element.appendChild(fragment);
+
+    this._theme = this.options.theme || this._theme;
+    this.options.theme = undefined;
+    this._colorManager = new ColorManager(document, this.options.allowTransparency);
+    this._colorManager.setTheme(this._theme);
+
+    const renderer = this._createRenderer();
+    this._renderService = this._instantiationService.createInstance(RenderService, renderer, this.rows, this.screenElement);
+    this._instantiationService.setService(IRenderService, this._renderService);
+    this._renderService.onRender(e => this._onRender.fire(e));
+    this.onResize(e => this._renderService.resize(e.cols, e.rows));
+
+    this._soundService = this._instantiationService.createInstance(SoundService);
+    this._instantiationService.setService(ISoundService, this._soundService);
+    this._mouseService = this._instantiationService.createInstance(MouseService);
+    this._instantiationService.setService(IMouseService, this._mouseService);
+
+    this.viewport = this._instantiationService.createInstance(Viewport,
+      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),
+      this._viewportElement,
+      this._viewportScrollArea
+    );
+    this.viewport.onThemeChange(this._colorManager.colors);
+    this.register(this.viewport);
+
+    this.register(this.onCursorMove(() => this._renderService.onCursorMove()));
+    this.register(this.onResize(() => this._renderService.onResize(this.cols, this.rows)));
+    this.register(this.onBlur(() => this._renderService.onBlur()));
+    this.register(this.onFocus(() => this._renderService.onFocus()));
+    this.register(this._renderService.onDimensionsChange(() => this.viewport.syncScrollArea()));
+
+    this._selectionService = this._instantiationService.createInstance(SelectionService,
+      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),
+      this.element,
+      this.screenElement);
+    this._instantiationService.setService(ISelectionService, this._selectionService);
+    this.register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire()));
+    this.register(this._selectionService.onRedrawRequest(e => this._renderService.onSelectionChanged(e.start, e.end, e.columnSelectMode)));
+    this.register(this._selectionService.onLinuxMouseSelection(text => {
+      // If there's a new selection, put it into the textarea, focus and select it
+      // in order to register it as a selection on the OS. This event is fired
+      // only on Linux to enable middle click to paste selection.
+      this.textarea.value = text;
+      this.textarea.focus();
+      this.textarea.select();
+    }));
+    this.register(this.onScroll(() => {
+      this.viewport.syncScrollArea();
+      this._selectionService.refresh();
+    }));
+    this.register(addDisposableDomListener(this._viewportElement, 'scroll', () => this._selectionService.refresh()));
+
+    this._mouseZoneManager = this._instantiationService.createInstance(MouseZoneManager, this.element, this.screenElement);
+    this.register(this._mouseZoneManager);
+    this.register(this.onScroll(() => this._mouseZoneManager.clearAll()));
+    this.linkifier.attachToDom(this.element, this._mouseZoneManager);
+
+    // This event listener must be registered aftre MouseZoneManager is created
+    this.register(addDisposableDomListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService.onMouseDown(e)));
+
+    // apply mouse event classes set by escape codes before terminal was attached
+    if (this.mouseEvents) {
+      this._selectionService.disable();
+      this.element.classList.add('enable-mouse-events');
+    } else {
+      this._selectionService.enable();
+    }
+
+    if (this.options.screenReaderMode) {
+      // Note that this must be done *after* the renderer is created in order to
+      // ensure the correct order of the dprchange event
+      this._accessibilityManager = new AccessibilityManager(this, this._renderService);
+    }
+
+    // Measure the character size
+    this._charSizeService.measure();
+
+    // Setup loop that draws to screen
+    this.refresh(0, this.rows - 1);
+
+    // Initialize global actions that need to be taken on the document.
+    this._initGlobal();
+
+    // Listen for mouse events and translate
+    // them into terminal mouse protocols.
+    this.bindMouse();
+  }
+
+  private _createRenderer(): IRenderer {
+    switch (this.options.rendererType) {
+      case 'canvas': return new Renderer(this._colorManager.colors, this, this._bufferService, this._charSizeService, this.optionsService);
+      case 'dom': return new DomRenderer(this, this._colorManager.colors, this._charSizeService, this.optionsService);
+      default: throw new Error(`Unrecognized rendererType "${this.options.rendererType}"`);
+    }
+  }
+
+  /**
+   * Sets the theme on the renderer. The renderer must have been initialized.
+   * @param theme The theme to set.
+   */
+  private _setTheme(theme: ITheme): void {
+    this._theme = theme;
+    if (this._colorManager) {
+      this._colorManager.setTheme(theme);
+    }
+    if (this._renderService) {
+      this._renderService.setColors(this._colorManager.colors);
+    }
+    if (this.viewport) {
+      this.viewport.onThemeChange(this._colorManager.colors);
+    }
+  }
+
+  /**
+   * Bind certain mouse events to the terminal.
+   * By default only 3 button + wheel up/down is ativated. For higher buttons
+   * no mouse report will be created. Typically the standard actions will be active.
+   *
+   * There are several reasons not to enable support for higher buttons/wheel:
+   * - Button 4 and 5 are typically used for history back and forward navigation,
+   *   there is no straight forward way to supress/intercept those standard actions.
+   * - Support for higher buttons does not work in some platform/browser combinations.
+   * - Left/right wheel was not tested.
+   * - Emulators vary in mouse button support, typically only 3 buttons and
+   *   wheel up/down work reliable.
+   *
+   * TODO: Move mouse event code into its own file.
+   */
+  public bindMouse(): void {
+    const self = this;
+    const el = this.element;
+
+    // send event to CoreMouseService
+    function sendEvent(ev: MouseEvent | WheelEvent): boolean {
+      let pos;
+
+      // get mouse coordinates
+      pos = self._mouseService.getRawByteCoords(ev, self.screenElement, self.cols, self.rows);
+      if (!pos) {
+        return false;
+      }
+
+      let but: CoreMouseButton;
+      let action: CoreMouseAction;
+      switch ((<any>ev).overrideType || ev.type) {
+        case 'mousemove':
+          action = CoreMouseAction.MOVE;
+          if (ev.buttons === undefined) {
+            // buttons is not supported on macOS, try to get a value from button instead
+            but = CoreMouseButton.NONE;
+            if (ev.button !== undefined) {
+              but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
+            }
+          } else {
+            // according to MDN buttons only reports up to button 5 (AUX2)
+            but = ev.buttons & 1 ? CoreMouseButton.LEFT :
+                  ev.buttons & 4 ? CoreMouseButton.MIDDLE :
+                  ev.buttons & 2 ? CoreMouseButton.RIGHT :
+                  CoreMouseButton.NONE; // fallback to NONE
+          }
+          break;
+        case 'mouseup':
+          action = CoreMouseAction.UP;
+          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
+          break;
+        case 'mousedown':
+          action = CoreMouseAction.DOWN;
+          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
+          break;
+        case 'wheel':
+          // only UP/DOWN wheel events are respected
+          if ((ev as WheelEvent).deltaY !== 0) {
+            action = (ev as WheelEvent).deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN;
+          }
+          but = CoreMouseButton.WHEEL;
+          break;
+        default:
+          // dont handle other event types by accident
+          return false;
+      }
+
+      // exit if we cannot determine valid button/action values
+      // do nothing for higher buttons than wheel
+      if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) {
+        return false;
+      }
+
+      return self._coreMouseService.triggerMouseEvent({
+        col: pos.x - 33, // FIXME: why -33 here?
+        row: pos.y - 33,
+        button: but,
+        action,
+        ctrl: ev.ctrlKey,
+        alt: ev.altKey,
+        shift: ev.shiftKey
+      });
+    }
+
+    /**
+     * Event listener state handling.
+     * We listen to the onProtocolChange event of CoreMouseService and put
+     * requested listeners in `requestedEvents`. With this the listeners
+     * have all bits to do the event listener juggling.
+     * Note: 'mousedown' currently is "always on" and not managed
+     * by onProtocolChange.
+     */
+    const requestedEvents: {[key: string]: ((ev: Event) => void) | null} = {
+      mouseup: null,
+      wheel: null,
+      mousedrag: null,
+      mousemove: null
+    };
+    const eventListeners: {[key: string]: (ev: Event) => void} = {
+      mouseup: (ev: MouseEvent) => {
+        sendEvent(ev);
+        if (!ev.buttons) {
+          // if no other button is held remove global handlers
+          this._document.removeEventListener('mouseup', requestedEvents.mouseup);
+          if (requestedEvents.mousedrag) {
+            this._document.removeEventListener('mousemove', requestedEvents.mousedrag);
+          }
+        }
+        return this.cancel(ev);
+      },
+      wheel: (ev: WheelEvent) => {
+        sendEvent(ev);
+        ev.preventDefault();
+        return this.cancel(ev);
+      },
+      mousedrag: (ev: MouseEvent) => {
+        // deal only with move while a button is held
+        if (ev.buttons) {
+          sendEvent(ev);
+        }
+      },
+      mousemove: (ev: MouseEvent) => {
+        // deal only with move without any button
+        if (!ev.buttons) {
+          sendEvent(ev);
+        }
+      }
+    };
+    this._coreMouseService.onProtocolChange(events => {
+      // apply global changes on events
+      this.mouseEvents = events;
+      if (events) {
+        if (this.optionsService.options.logLevel === 'debug') {
+          this._logService.debug('Binding to mouse events:', this._coreMouseService.explainEvents(events));
+        }
+        this.element.classList.add('enable-mouse-events');
+        this._selectionService.disable();
+      } else {
+        this._logService.debug('Unbinding from mouse events.');
+        this.element.classList.remove('enable-mouse-events');
+        this._selectionService.enable();
+      }
+
+      // add/remove handlers from requestedEvents
+
+      if (!(events & CoreMouseEventType.MOVE)) {
+        el.removeEventListener('mousemove', requestedEvents.mousemove);
+        requestedEvents.mousemove = null;
+      } else if (!requestedEvents.mousemove) {
+        el.addEventListener('mousemove', eventListeners.mousemove);
+        requestedEvents.mousemove = eventListeners.mousemove;
+      }
+
+      if (!(events & CoreMouseEventType.WHEEL)) {
+        el.removeEventListener('wheel', requestedEvents.wheel);
+        requestedEvents.wheel = null;
+      } else if (!requestedEvents.wheel) {
+        el.addEventListener('wheel', eventListeners.wheel);
+        requestedEvents.wheel = eventListeners.wheel;
+      }
+
+      if (!(events & CoreMouseEventType.UP)) {
+        this._document.removeEventListener('mouseup', requestedEvents.mouseup);
+        requestedEvents.mouseup = null;
+      } else if (!requestedEvents.mouseup) {
+        requestedEvents.mouseup = eventListeners.mouseup;
+      }
+
+      if (!(events & CoreMouseEventType.DRAG)) {
+        this._document.removeEventListener('mousemove', requestedEvents.mousedrag);
+        requestedEvents.mousedrag = null;
+      } else if (!requestedEvents.mousedrag) {
+        requestedEvents.mousedrag = eventListeners.mousedrag;
+      }
+    });
+    // force initial onProtocolChange so we dont miss early mouse requests
+    this._coreMouseService.activeProtocol = this._coreMouseService.activeProtocol;
+
+    /**
+     * "Always on" event listeners.
+     */
+    this.register(addDisposableDomListener(el, 'mousedown', (ev: MouseEvent) => {
+      ev.preventDefault();
+      this.focus();
+
+      // Don't send the mouse button to the pty if mouse events are disabled or
+      // if the selection manager is having selection forced (ie. a modifier is
+      // held).
+      if (!this.mouseEvents || this._selectionService.shouldForceSelection(ev)) {
+        return;
+      }
+
+      sendEvent(ev);
+
+      // Register additional global handlers which should keep reporting outside
+      // of the terminal element.
+      // Note: Other emulators also do this for 'mousedown' while a button
+      // is held, we currently limit 'mousedown' to the terminal only.
+      if (requestedEvents.mouseup) {
+        this._document.addEventListener('mouseup', requestedEvents.mouseup);
+      }
+      if (requestedEvents.mousedrag) {
+        this._document.addEventListener('mousemove', requestedEvents.mousedrag);
+      }
+
+      return this.cancel(ev);
+    }));
+
+    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {
+      if (!requestedEvents.wheel) {
+        // Convert wheel events into up/down events when the buffer does not have scrollback, this
+        // enables scrolling in apps hosted in the alt buffer such as vim or tmux.
+        if (!this.buffer.hasScrollback) {
+          const amount = this.viewport.getLinesScrolled(ev);
+
+          // Do nothing if there's no vertical scroll
+          if (amount === 0) {
+            return;
+          }
+
+          // Construct and send sequences
+          const sequence = C0.ESC + (this._coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + ( ev.deltaY < 0 ? 'A' : 'B');
+          let data = '';
+          for (let i = 0; i < Math.abs(amount); i++) {
+            data += sequence;
+          }
+          this._coreService.triggerDataEvent(data, true);
+        }
+        return;
+      }
+    }));
+
+    // allow wheel scrolling in
+    // the shell for example
+    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {
+      if (requestedEvents.wheel) return;
+      if (!this.viewport.onWheel(ev)) {
+        return this.cancel(ev);
+      }
+    }));
+
+    this.register(addDisposableDomListener(el, 'touchstart', (ev: TouchEvent) => {
+      if (this.mouseEvents) return;
+      this.viewport.onTouchStart(ev);
+      return this.cancel(ev);
+    }));
+
+    this.register(addDisposableDomListener(el, 'touchmove', (ev: TouchEvent) => {
+      if (this.mouseEvents) return;
+      if (!this.viewport.onTouchMove(ev)) {
+        return this.cancel(ev);
+      }
+    }));
+  }
+
+
+  /**
+   * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
+   * opportunity.
+   * @param start The row to start from (between 0 and this.rows - 1).
+   * @param end The row to end at (between start and this.rows - 1).
+   */
+  public refresh(start: number, end: number): void {
+    if (this._renderService) {
+      this._renderService.refreshRows(start, end);
+    }
+  }
+
+  /**
+   * Queues linkification for the specified rows.
+   * @param start The row to start from (between 0 and this.rows - 1).
+   * @param end The row to end at (between start and this.rows - 1).
+   */
+  private _queueLinkification(start: number, end: number): void {
+    if (this.linkifier) {
+      this.linkifier.linkifyRows(start, end);
+    }
+  }
+
+  /**
+   * Change the cursor style for different selection modes
+   */
+  public updateCursorStyle(ev: KeyboardEvent): void {
+    if (this._selectionService && this._selectionService.shouldColumnSelect(ev)) {
+      this.element.classList.add('column-select');
+    } else {
+      this.element.classList.remove('column-select');
+    }
+  }
+
+  /**
+   * Display the cursor element
+   */
+  public showCursor(): void {
+    if (!this.cursorState) {
+      this.cursorState = 1;
+      this.refresh(this.buffer.y, this.buffer.y);
+    }
+  }
+
+  /**
+   * Scroll the terminal down 1 row, creating a blank line.
+   * @param isWrapped Whether the new line is wrapped from the previous line.
+   */
+  public scroll(isWrapped: boolean = false): void {
+    let newLine: IBufferLine;
+    newLine = this._blankLine;
+    const eraseAttr = this.eraseAttrData();
+    if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) {
+      newLine = this.buffer.getBlankLine(eraseAttr, isWrapped);
+      this._blankLine = newLine;
+    }
+    newLine.isWrapped = isWrapped;
+
+    const topRow = this.buffer.ybase + this.buffer.scrollTop;
+    const bottomRow = this.buffer.ybase + this.buffer.scrollBottom;
+
+    if (this.buffer.scrollTop === 0) {
+      // Determine whether the buffer is going to be trimmed after insertion.
+      const willBufferBeTrimmed = this.buffer.lines.isFull;
+
+      // Insert the line using the fastest method
+      if (bottomRow === this.buffer.lines.length - 1) {
+        if (willBufferBeTrimmed) {
+          this.buffer.lines.recycle().copyFrom(newLine);
+        } else {
+          this.buffer.lines.push(newLine.clone());
+        }
+      } else {
+        this.buffer.lines.splice(bottomRow + 1, 0, newLine.clone());
+      }
+
+      // Only adjust ybase and ydisp when the buffer is not trimmed
+      if (!willBufferBeTrimmed) {
+        this.buffer.ybase++;
+        // Only scroll the ydisp with ybase if the user has not scrolled up
+        if (!this._userScrolling) {
+          this.buffer.ydisp++;
+        }
+      } else {
+        // When the buffer is full and the user has scrolled up, keep the text
+        // stable unless ydisp is right at the top
+        if (this._userScrolling) {
+          this.buffer.ydisp = Math.max(this.buffer.ydisp - 1, 0);
+        }
+      }
+    } else {
+      // scrollTop is non-zero which means no line will be going to the
+      // scrollback, instead we can just shift them in-place.
+      const scrollRegionHeight = bottomRow - topRow + 1/*as it's zero-based*/;
+      this.buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1);
+      this.buffer.lines.set(bottomRow, newLine.clone());
+    }
+
+    // Move the viewport to the bottom of the buffer unless the user is
+    // scrolling.
+    if (!this._userScrolling) {
+      this.buffer.ydisp = this.buffer.ybase;
+    }
+
+    // Flag rows that need updating
+    this._dirtyRowService.markRangeDirty(this.buffer.scrollTop, this.buffer.scrollBottom);
+
+    this._onScroll.fire(this.buffer.ydisp);
+  }
+
+  /**
+   * Scroll the display of the terminal
+   * @param disp The number of lines to scroll down (negative scroll up).
+   * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used
+   * to avoid unwanted events being handled by the viewport when the event was triggered from the
+   * viewport originally.
+   */
+  public scrollLines(disp: number, suppressScrollEvent?: boolean): void {
+    if (disp < 0) {
+      if (this.buffer.ydisp === 0) {
+        return;
+      }
+      this._userScrolling = true;
+    } else if (disp + this.buffer.ydisp >= this.buffer.ybase) {
+      this._userScrolling = false;
+    }
+
+    const oldYdisp = this.buffer.ydisp;
+    this.buffer.ydisp = Math.max(Math.min(this.buffer.ydisp + disp, this.buffer.ybase), 0);
+
+    // No change occurred, don't trigger scroll/refresh
+    if (oldYdisp === this.buffer.ydisp) {
+      return;
+    }
+
+    if (!suppressScrollEvent) {
+      this._onScroll.fire(this.buffer.ydisp);
+    }
+
+    this.refresh(0, this.rows - 1);
+  }
+
+  /**
+   * Scroll the display of the terminal by a number of pages.
+   * @param pageCount The number of pages to scroll (negative scrolls up).
+   */
+  public scrollPages(pageCount: number): void {
+    this.scrollLines(pageCount * (this.rows - 1));
+  }
+
+  /**
+   * Scrolls the display of the terminal to the top.
+   */
+  public scrollToTop(): void {
+    this.scrollLines(-this.buffer.ydisp);
+  }
+
+  /**
+   * Scrolls the display of the terminal to the bottom.
+   */
+  public scrollToBottom(): void {
+    this.scrollLines(this.buffer.ybase - this.buffer.ydisp);
+  }
+
+  public scrollToLine(line: number): void {
+    const scrollAmount = line - this.buffer.ydisp;
+    if (scrollAmount !== 0) {
+      this.scrollLines(scrollAmount);
+    }
+  }
+
+  public paste(data: string): void {
+    paste(data, this.textarea, this.bracketedPasteMode, this._coreService);
+  }
+
+  /**
+   * Attaches a custom key event handler which is run before keys are processed,
+   * giving consumers of xterm.js ultimate control as to what keys should be
+   * processed by the terminal and what keys should not.
+   * @param customKeyEventHandler The custom KeyboardEvent handler to attach.
+   * This is a function that takes a KeyboardEvent, allowing consumers to stop
+   * propagation and/or prevent the default action. The function returns whether
+   * the event should be processed by xterm.js.
+   */
+  public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void {
+    this._customKeyEventHandler = customKeyEventHandler;
+  }
+
+  /** Add handler for ESC escape sequence. See xterm.d.ts for details. */
+  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {
+    return this._inputHandler.addEscHandler(id, callback);
+  }
+
+  /** Add handler for DCS escape sequence. See xterm.d.ts for details. */
+  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {
+    return this._inputHandler.addDcsHandler(id, callback);
+  }
+
+  /** Add handler for CSI escape sequence. See xterm.d.ts for details. */
+  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {
+    return this._inputHandler.addCsiHandler(id, callback);
+  }
+  /** Add handler for OSC escape sequence. See xterm.d.ts for details. */
+  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {
+    return this._inputHandler.addOscHandler(ident, callback);
+  }
+
+  /**
+   * Registers a link matcher, allowing custom link patterns to be matched and
+   * handled.
+   * @param regex The regular expression to search for, specifically
+   * this searches the textContent of the rows. You will want to use \s to match
+   * a space ' ' character for example.
+   * @param handler The callback when the link is called.
+   * @param options Options for the link matcher.
+   * @return The ID of the new matcher, this can be used to deregister.
+   */
+  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?: ILinkMatcherOptions): number {
+    const matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
+    this.refresh(0, this.rows - 1);
+    return matcherId;
+  }
+
+  /**
+   * Deregisters a link matcher if it has been registered.
+   * @param matcherId The link matcher's ID (returned after register)
+   */
+  public deregisterLinkMatcher(matcherId: number): void {
+    if (this.linkifier.deregisterLinkMatcher(matcherId)) {
+      this.refresh(0, this.rows - 1);
+    }
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {
+    const joinerId = this._renderService.registerCharacterJoiner(handler);
+    this.refresh(0, this.rows - 1);
+    return joinerId;
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): void {
+    if (this._renderService.deregisterCharacterJoiner(joinerId)) {
+      this.refresh(0, this.rows - 1);
+    }
+  }
+
+  public get markers(): IMarker[] {
+    return this.buffer.markers;
+  }
+
+  public addMarker(cursorYOffset: number): IMarker {
+    // Disallow markers on the alt buffer
+    if (this.buffer !== this.buffers.normal) {
+      return;
+    }
+
+    return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);
+  }
+
+  /**
+   * Gets whether the terminal has an active selection.
+   */
+  public hasSelection(): boolean {
+    return this._selectionService ? this._selectionService.hasSelection : false;
+  }
+
+  /**
+   * Selects text within the terminal.
+   * @param column The column the selection starts at..
+   * @param row The row the selection starts at.
+   * @param length The length of the selection.
+   */
+  public select(column: number, row: number, length: number): void {
+    this._selectionService.setSelection(column, row, length);
+  }
+
+  /**
+   * Gets the terminal's current selection, this is useful for implementing copy
+   * behavior outside of xterm.js.
+   */
+  public getSelection(): string {
+    return this._selectionService ? this._selectionService.selectionText : '';
+  }
+
+  public getSelectionPosition(): ISelectionPosition | undefined {
+    if (!this._selectionService.hasSelection) {
+      return undefined;
+    }
+
+    return {
+      startColumn: this._selectionService.selectionStart[0],
+      startRow: this._selectionService.selectionStart[1],
+      endColumn: this._selectionService.selectionEnd[0],
+      endRow: this._selectionService.selectionEnd[1]
+    };
+  }
+
+  /**
+   * Clears the current terminal selection.
+   */
+  public clearSelection(): void {
+    if (this._selectionService) {
+      this._selectionService.clearSelection();
+    }
+  }
+
+  /**
+   * Selects all text within the terminal.
+   */
+  public selectAll(): void {
+    if (this._selectionService) {
+      this._selectionService.selectAll();
+    }
+  }
+
+  public selectLines(start: number, end: number): void {
+    if (this._selectionService) {
+      this._selectionService.selectLines(start, end);
+    }
+  }
+
+  /**
+   * Handle a keydown event
+   * Key Resources:
+   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
+   * @param ev The keydown event to be handled.
+   */
+  protected _keyDown(event: KeyboardEvent): boolean {
+    this._keyDownHandled = false;
+
+    if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {
+      return false;
+    }
+
+    if (!this._compositionHelper.keydown(event)) {
+      if (this.buffer.ybase !== this.buffer.ydisp) {
+        this.scrollToBottom();
+      }
+      return false;
+    }
+
+    const result = evaluateKeyboardEvent(event, this._coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);
+
+    this.updateCursorStyle(event);
+
+    if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {
+      const scrollCount = this.rows - 1;
+      this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);
+      return this.cancel(event, true);
+    }
+
+    if (result.type === KeyboardResultType.SELECT_ALL) {
+      this.selectAll();
+    }
+
+    if (this._isThirdLevelShift(this.browser, event)) {
+      return true;
+    }
+
+    if (result.cancel) {
+      // The event is canceled at the end already, is this necessary?
+      this.cancel(event, true);
+    }
+
+    if (!result.key) {
+      return true;
+    }
+
+    // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers
+    // will announce deleted characters. This will not work 100% of the time but it should cover
+    // most scenarios.
+    if (result.key === C0.ETX || result.key === C0.CR) {
+      this.textarea.value = '';
+    }
+
+    this._onKey.fire({ key: result.key, domEvent: event });
+    this.showCursor();
+    this._coreService.triggerDataEvent(result.key, true);
+
+    // Cancel events when not in screen reader mode so events don't get bubbled up and handled by
+    // other listeners. When screen reader mode is enabled, this could cause issues if the event
+    // is handled at a higher level, this is a compromise in order to echo keys to the screen
+    // reader.
+    if (!this.optionsService.options.screenReaderMode) {
+      return this.cancel(event, true);
+    }
+
+    this._keyDownHandled = true;
+  }
+
+  private _isThirdLevelShift(browser: IBrowser, ev: IKeyboardEvent): boolean {
+    const thirdLevelKey =
+        (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
+        (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
+
+    if (ev.type === 'keypress') {
+      return thirdLevelKey;
+    }
+
+    // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
+    return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
+  }
+
+  /**
+   * Set the G level of the terminal
+   * @param g
+   */
+  public setgLevel(g: number): void {
+    this.glevel = g;
+    this.charset = this.charsets[g];
+  }
+
+  /**
+   * Set the charset for the given G level of the terminal
+   * @param g
+   * @param charset
+   */
+  public setgCharset(g: number, charset: ICharset): void {
+    this.charsets[g] = charset;
+    if (this.glevel === g) {
+      this.charset = charset;
+    }
+  }
+
+  protected _keyUp(ev: KeyboardEvent): void {
+    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
+      return;
+    }
+
+    if (!wasModifierKeyOnlyEvent(ev)) {
+      this.focus();
+    }
+
+    this.updateCursorStyle(ev);
+  }
+
+  /**
+   * Handle a keypress event.
+   * Key Resources:
+   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
+   * @param ev The keypress event to be handled.
+   */
+  protected _keyPress(ev: KeyboardEvent): boolean {
+    let key;
+
+    if (this._keyDownHandled) {
+      return false;
+    }
+
+    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
+      return false;
+    }
+
+    this.cancel(ev);
+
+    if (ev.charCode) {
+      key = ev.charCode;
+    } else if (ev.which === null || ev.which === undefined) {
+      key = ev.keyCode;
+    } else if (ev.which !== 0 && ev.charCode !== 0) {
+      key = ev.which;
+    } else {
+      return false;
+    }
+
+    if (!key || (
+      (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev)
+    )) {
+      return false;
+    }
+
+    key = String.fromCharCode(key);
+
+    this._onKey.fire({ key, domEvent: ev });
+    this.showCursor();
+    this._coreService.triggerDataEvent(key, true);
+
+    return true;
+  }
+
+  /**
+   * Ring the bell.
+   * Note: We could do sweet things with webaudio here
+   */
+  public bell(): void {
+    if (this._soundBell()) {
+      this._soundService.playBellSound();
+    }
+
+    if (this._visualBell()) {
+      this.element.classList.add('visual-bell-active');
+      clearTimeout(this._visualBellTimer);
+      this._visualBellTimer = window.setTimeout(() => {
+        this.element.classList.remove('visual-bell-active');
+      }, 200);
+    }
+  }
+
+  /**
+   * Resizes the terminal.
+   *
+   * @param x The number of columns to resize to.
+   * @param y The number of rows to resize to.
+   */
+  public resize(x: number, y: number): void {
+    if (isNaN(x) || isNaN(y)) {
+      return;
+    }
+
+    if (x === this.cols && y === this.rows) {
+      // Check if we still need to measure the char size (fixes #785).
+      if (this._charSizeService && !this._charSizeService.hasValidSize) {
+        this._charSizeService.measure();
+      }
+      return;
+    }
+
+    if (x < MINIMUM_COLS) x = MINIMUM_COLS;
+    if (y < MINIMUM_ROWS) y = MINIMUM_ROWS;
+
+    this.buffers.resize(x, y);
+
+    this._bufferService.resize(x, y);
+    this.buffers.setupTabStops(this.cols);
+
+    if (this._charSizeService) {
+      this._charSizeService.measure();
+    }
+
+    // Sync the scroll area to make sure scroll events don't fire and scroll the viewport to an
+    // invalid location
+    this.viewport.syncScrollArea(true);
+
+    this.refresh(0, this.rows - 1);
+    this._onResize.fire({ cols: x, rows: y });
+  }
+
+  /**
+   * Clear the entire buffer, making the prompt line the new first line.
+   */
+  public clear(): void {
+    if (this.buffer.ybase === 0 && this.buffer.y === 0) {
+      // Don't clear if it's already clear
+      return;
+    }
+    this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y));
+    this.buffer.lines.length = 1;
+    this.buffer.ydisp = 0;
+    this.buffer.ybase = 0;
+    this.buffer.y = 0;
+    for (let i = 1; i < this.rows; i++) {
+      this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));
+    }
+    this.refresh(0, this.rows - 1);
+    this._onScroll.fire(this.buffer.ydisp);
+  }
+
+  /**
+   * Evaluate if the current terminal is the given argument.
+   * @param term The terminal name to evaluate
+   */
+  public is(term: string): boolean {
+    return (this.options.termName + '').indexOf(term) === 0;
+  }
+
+  /**
+   * Emit the data event and populate the given data.
+   * @param data The data to populate in the event.
+   */
+  // public handler(data: string): void {
+  //   // Prevents all events to pty process if stdin is disabled
+  //   if (this.options.disableStdin) {
+  //     return;
+  //   }
+
+  //   // Clear the selection if the selection manager is available and has an active selection
+  //   if (this.selectionService && this.selectionService.hasSelection) {
+  //     this.selectionService.clearSelection();
+  //   }
+
+  //   // Input is being sent to the terminal, the terminal should focus the prompt.
+  //   if (this.buffer.ybase !== this.buffer.ydisp) {
+  //     this.scrollToBottom();
+  //   }
+  //   this._onData.fire(data);
+  // }
+
+  /**
+   * Emit the 'title' event and populate the given title.
+   * @param title The title to populate in the event.
+   */
+  public handleTitle(title: string): void {
+    this._onTitleChange.fire(title);
+  }
+
+  /**
+   * Reset terminal.
+   * Note: Calling this directly from JS is synchronous but does not clear
+   * input buffers and does not reset the parser, thus the terminal will
+   * continue to apply pending input data.
+   * If you need in band reset (synchronous with input data) consider
+   * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).
+   */
+  public reset(): void {
+    /**
+     * Since _setup handles a full terminal creation, we have to carry forward
+     * a few things that should not reset.
+     */
+    this.options.rows = this.rows;
+    this.options.cols = this.cols;
+    const customKeyEventHandler = this._customKeyEventHandler;
+    const inputHandler = this._inputHandler;
+    const cursorState = this.cursorState;
+    const userScrolling = this._userScrolling;
+
+    this._setup();
+    this._bufferService.reset();
+    this._coreService.reset();
+    this._coreMouseService.reset();
+    if (this._selectionService) {
+      this._selectionService.reset();
+    }
+
+    // reattach
+    this._customKeyEventHandler = customKeyEventHandler;
+    this._inputHandler = inputHandler;
+    this.cursorState = cursorState;
+    this._userScrolling = userScrolling;
+
+    // do a full screen refresh
+    this.refresh(0, this.rows - 1);
+    if (this.viewport) {
+      this.viewport.syncScrollArea();
+    }
+  }
+
+  // TODO: Remove cancel function and cancelEvents option
+  public cancel(ev: Event, force?: boolean): boolean {
+    if (!this.options.cancelEvents && !force) {
+      return;
+    }
+    ev.preventDefault();
+    ev.stopPropagation();
+    return false;
+  }
+
+  private _visualBell(): boolean {
+    return false;
+    // return this.options.bellStyle === 'visual' ||
+    //     this.options.bellStyle === 'both';
+  }
+
+  private _soundBell(): boolean {
+    return this.options.bellStyle === 'sound';
+    // return this.options.bellStyle === 'sound' ||
+    //     this.options.bellStyle === 'both';
+  }
+
+  public write(data: string | Uint8Array, callback?: () => void): void {
+    this._writeBuffer.write(data, callback);
+  }
+
+  public writeSync(data: string | Uint8Array): void {
+    this._writeBuffer.writeSync(data);
+  }
+}
+
+/**
+ * Helpers
+ */
+
+function wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {
+  return ev.keyCode === 16 || // Shift
+    ev.keyCode === 17 || // Ctrl
+    ev.keyCode === 18; // Alt
+}
diff --git a/node_modules/xterm/src/Types.d.ts b/node_modules/xterm/src/Types.d.ts
new file mode 100644 (file)
index 0000000..be1019e
--- /dev/null
@@ -0,0 +1,260 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ITerminalOptions as IPublicTerminalOptions, IDisposable, IMarker, ISelectionPosition } from 'xterm';
+import { ICharset, IAttributeData, CharData, CoreMouseEventType } from 'common/Types';
+import { IEvent, IEventEmitter } from 'common/EventEmitter';
+import { IColorSet, ILinkifier, ILinkMatcherOptions, IViewport } from 'browser/Types';
+import { IOptionsService } from 'common/services/Services';
+import { IBuffer, IBufferSet } from 'common/buffer/Types';
+import { IParams, IFunctionIdentifier } from 'common/parser/Types';
+
+export type CustomKeyEventHandler = (event: KeyboardEvent) => boolean;
+
+export type LineData = CharData[];
+
+/**
+ * This interface encapsulates everything needed from the Terminal by the
+ * InputHandler. This cleanly separates the large amount of methods needed by
+ * InputHandler cleanly from the ITerminal interface.
+ */
+export interface IInputHandlingTerminal {
+  element: HTMLElement;
+  options: ITerminalOptions;
+  cols: number;
+  rows: number;
+  charset: ICharset;
+  gcharset: number;
+  glevel: number;
+  charsets: ICharset[];
+  applicationKeypad: boolean;
+  originMode: boolean;
+  insertMode: boolean;
+  wraparoundMode: boolean;
+  bracketedPasteMode: boolean;
+  curAttrData: IAttributeData;
+  savedCols: number;
+  mouseEvents: CoreMouseEventType;
+  sendFocus: boolean;
+  cursorHidden: boolean;
+
+  buffers: IBufferSet;
+  buffer: IBuffer;
+  viewport: IViewport;
+
+  onA11yCharEmitter: IEventEmitter<string>;
+  onA11yTabEmitter: IEventEmitter<number>;
+
+  bell(): void;
+  focus(): void;
+  scroll(isWrapped?: boolean): void;
+  setgLevel(g: number): void;
+  eraseAttrData(): IAttributeData;
+  is(term: string): boolean;
+  setgCharset(g: number, charset: ICharset): void;
+  resize(x: number, y: number): void;
+  reset(): void;
+  showCursor(): void;
+  refresh(start: number, end: number): void;
+  handleTitle(title: string): void;
+}
+
+export interface ICompositionHelper {
+  compositionstart(): void;
+  compositionupdate(ev: CompositionEvent): void;
+  compositionend(): void;
+  updateCompositionElements(dontRecurse?: boolean): void;
+  keydown(ev: KeyboardEvent): boolean;
+}
+
+/**
+ * Calls the parser and handles actions generated by the parser.
+ */
+export interface IInputHandler {
+  parse(data: string | Uint8Array): void;
+  print(data: Uint32Array, start: number, end: number): void;
+
+  /** C0 BEL */ bell(): void;
+  /** C0 LF */ lineFeed(): void;
+  /** C0 CR */ carriageReturn(): void;
+  /** C0 BS */ backspace(): void;
+  /** C0 HT */ tab(): void;
+  /** C0 SO */ shiftOut(): void;
+  /** C0 SI */ shiftIn(): void;
+
+  /** CSI @ */ insertChars(params: IParams): void;
+  /** CSI SP @ */ scrollLeft(params: IParams): void;
+  /** CSI A */ cursorUp(params: IParams): void;
+  /** CSI SP A */ scrollRight(params: IParams): void;
+  /** CSI B */ cursorDown(params: IParams): void;
+  /** CSI C */ cursorForward(params: IParams): void;
+  /** CSI D */ cursorBackward(params: IParams): void;
+  /** CSI E */ cursorNextLine(params: IParams): void;
+  /** CSI F */ cursorPrecedingLine(params: IParams): void;
+  /** CSI G */ cursorCharAbsolute(params: IParams): void;
+  /** CSI H */ cursorPosition(params: IParams): void;
+  /** CSI I */ cursorForwardTab(params: IParams): void;
+  /** CSI J */ eraseInDisplay(params: IParams): void;
+  /** CSI K */ eraseInLine(params: IParams): void;
+  /** CSI L */ insertLines(params: IParams): void;
+  /** CSI M */ deleteLines(params: IParams): void;
+  /** CSI P */ deleteChars(params: IParams): void;
+  /** CSI S */ scrollUp(params: IParams): void;
+  /** CSI T */ scrollDown(params: IParams, collect?: string): void;
+  /** CSI X */ eraseChars(params: IParams): void;
+  /** CSI Z */ cursorBackwardTab(params: IParams): void;
+  /** CSI ` */ charPosAbsolute(params: IParams): void;
+  /** CSI a */ hPositionRelative(params: IParams): void;
+  /** CSI b */ repeatPrecedingCharacter(params: IParams): void;
+  /** CSI c */ sendDeviceAttributesPrimary(params: IParams): void;
+  /** CSI > c */ sendDeviceAttributesSecondary(params: IParams): void;
+  /** CSI d */ linePosAbsolute(params: IParams): void;
+  /** CSI e */ vPositionRelative(params: IParams): void;
+  /** CSI f */ hVPosition(params: IParams): void;
+  /** CSI g */ tabClear(params: IParams): void;
+  /** CSI h */ setMode(params: IParams, collect?: string): void;
+  /** CSI l */ resetMode(params: IParams, collect?: string): void;
+  /** CSI m */ charAttributes(params: IParams): void;
+  /** CSI n */ deviceStatus(params: IParams, collect?: string): void;
+  /** CSI p */ softReset(params: IParams, collect?: string): void;
+  /** CSI q */ setCursorStyle(params: IParams, collect?: string): void;
+  /** CSI r */ setScrollRegion(params: IParams, collect?: string): void;
+  /** CSI s */ saveCursor(params: IParams): void;
+  /** CSI u */ restoreCursor(params: IParams): void;
+  /** CSI ' } */ insertColumns(params: IParams): void;
+  /** CSI ' ~ */ deleteColumns(params: IParams): void;
+  /** OSC 0
+      OSC 2 */ setTitle(data: string): void;
+  /** ESC E */ nextLine(): void;
+  /** ESC = */ keypadApplicationMode(): void;
+  /** ESC > */ keypadNumericMode(): void;
+  /** ESC % G
+      ESC % @ */ selectDefaultCharset(): void;
+  /** ESC ( C
+      ESC ) C
+      ESC * C
+      ESC + C
+      ESC - C
+      ESC . C
+      ESC / C */ selectCharset(collectAndFlag: string): void;
+  /** ESC D */ index(): void;
+  /** ESC H */ tabSet(): void;
+  /** ESC M */ reverseIndex(): void;
+  /** ESC c */ reset(): void;
+  /** ESC n
+      ESC o
+      ESC |
+      ESC }
+      ESC ~ */ setgLevel(level: number): void;
+  /** ESC # 8 */ screenAlignmentPattern(): void;
+}
+
+export interface ITerminal extends IPublicTerminal, IElementAccessor, IBufferAccessor, ILinkifierAccessor {
+  screenElement: HTMLElement;
+  browser: IBrowser;
+  cursorHidden: boolean;
+  cursorState: number;
+  buffer: IBuffer;
+  buffers: IBufferSet;
+  isFocused: boolean;
+  viewport: IViewport;
+  bracketedPasteMode: boolean;
+  optionsService: IOptionsService;
+  // TODO: We should remove options once components adopt optionsService
+  options: ITerminalOptions;
+
+  onBlur: IEvent<void>;
+  onFocus: IEvent<void>;
+  onA11yChar: IEvent<string>;
+  onA11yTab: IEvent<number>;
+
+  scrollLines(disp: number, suppressScrollEvent?: boolean): void;
+  cancel(ev: Event, force?: boolean): boolean | void;
+  showCursor(): void;
+}
+
+// Portions of the public API that are required by the internal Terminal
+export interface IPublicTerminal extends IDisposable {
+  textarea: HTMLTextAreaElement | undefined;
+  rows: number;
+  cols: number;
+  buffer: IBuffer;
+  markers: IMarker[];
+  onCursorMove: IEvent<void>;
+  onData: IEvent<string>;
+  onKey: IEvent<{ key: string, domEvent: KeyboardEvent }>;
+  onLineFeed: IEvent<void>;
+  onScroll: IEvent<number>;
+  onSelectionChange: IEvent<void>;
+  onRender: IEvent<{ start: number, end: number }>;
+  onResize: IEvent<{ cols: number, rows: number }>;
+  onTitleChange: IEvent<string>;
+  blur(): void;
+  focus(): void;
+  resize(columns: number, rows: number): void;
+  open(parent: HTMLElement): void;
+  attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void;
+  addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable;
+  addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable;
+  addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable;
+  addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable;
+  registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number;
+  deregisterLinkMatcher(matcherId: number): void;
+  registerCharacterJoiner(handler: (text: string) => [number, number][]): number;
+  deregisterCharacterJoiner(joinerId: number): void;
+  addMarker(cursorYOffset: number): IMarker;
+  hasSelection(): boolean;
+  getSelection(): string;
+  getSelectionPosition(): ISelectionPosition | undefined;
+  clearSelection(): void;
+  select(column: number, row: number, length: number): void;
+  selectAll(): void;
+  selectLines(start: number, end: number): void;
+  dispose(): void;
+  scrollLines(amount: number): void;
+  scrollPages(pageCount: number): void;
+  scrollToTop(): void;
+  scrollToBottom(): void;
+  scrollToLine(line: number): void;
+  clear(): void;
+  write(data: string | Uint8Array, callback?: () => void): void;
+  paste(data: string): void;
+  refresh(start: number, end: number): void;
+  reset(): void;
+}
+
+export interface IBufferAccessor {
+  buffer: IBuffer;
+}
+
+export interface IElementAccessor {
+  readonly element: HTMLElement | undefined;
+}
+
+export interface ILinkifierAccessor {
+  linkifier: ILinkifier;
+}
+
+// TODO: The options that are not in the public API should be reviewed
+export interface ITerminalOptions extends IPublicTerminalOptions {
+  [key: string]: any;
+  cancelEvents?: boolean;
+  convertEol?: boolean;
+  handler?: (data: string) => void;
+  screenKeys?: boolean;
+  termName?: string;
+  useFlowControl?: boolean;
+}
+
+export interface IBrowser {
+  isNode: boolean;
+  userAgent: string;
+  platform: string;
+  isFirefox: boolean;
+  isMac: boolean;
+  isIpad: boolean;
+  isIphone: boolean;
+  isWindows: boolean;
+}
diff --git a/node_modules/xterm/src/WindowsMode.ts b/node_modules/xterm/src/WindowsMode.ts
new file mode 100644 (file)
index 0000000..0838cae
--- /dev/null
@@ -0,0 +1,28 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'xterm';
+import { ITerminal } from './Types';
+import { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';
+
+export function applyWindowsMode(terminal: ITerminal): IDisposable {
+  // Winpty does not support wraparound mode which means that lines will never
+  // be marked as wrapped. This causes issues for things like copying a line
+  // retaining the wrapped new line characters or if consumers are listening
+  // in on the data stream.
+  //
+  // The workaround for this is to listen to every incoming line feed and mark
+  // the line as wrapped if the last character in the previous line is not a
+  // space. This is certainly not without its problems, but generally on
+  // Windows when text reaches the end of the terminal it's likely going to be
+  // wrapped.
+  return terminal.onLineFeed(() => {
+    const line = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y - 1);
+    const lastChar = line.get(terminal.cols - 1);
+
+    const nextLine = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y);
+    nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE);
+  });
+}
diff --git a/node_modules/xterm/src/browser/Clipboard.ts b/node_modules/xterm/src/browser/Clipboard.ts
new file mode 100644 (file)
index 0000000..594e442
--- /dev/null
@@ -0,0 +1,111 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ISelectionService } from 'browser/services/Services';
+import { ICoreService } from 'common/services/Services';
+
+/**
+ * Prepares text to be pasted into the terminal by normalizing the line endings
+ * @param text The pasted text that needs processing before inserting into the terminal
+ */
+export function prepareTextForTerminal(text: string): string {
+  return text.replace(/\r?\n/g, '\r');
+}
+
+/**
+ * Bracket text for paste, if necessary, as per https://cirw.in/blog/bracketed-paste
+ * @param text The pasted text to bracket
+ */
+export function bracketTextForPaste(text: string, bracketedPasteMode: boolean): string {
+  if (bracketedPasteMode) {
+    return '\x1b[200~' + text + '\x1b[201~';
+  }
+  return text;
+}
+
+/**
+ * Binds copy functionality to the given terminal.
+ * @param ev The original copy event to be handled
+ */
+export function copyHandler(ev: ClipboardEvent, selectionService: ISelectionService): void {
+  if (ev.clipboardData) {
+    ev.clipboardData.setData('text/plain', selectionService.selectionText);
+  }
+  // Prevent or the original text will be copied.
+  ev.preventDefault();
+}
+
+/**
+ * Redirect the clipboard's data to the terminal's input handler.
+ * @param ev The original paste event to be handled
+ * @param term The terminal on which to apply the handled paste event
+ */
+export function handlePasteEvent(ev: ClipboardEvent, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {
+  ev.stopPropagation();
+  if (ev.clipboardData) {
+    const text = ev.clipboardData.getData('text/plain');
+    paste(text, textarea, bracketedPasteMode, coreService);
+  }
+}
+
+export function paste(text: string, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {
+  text = prepareTextForTerminal(text);
+  text = bracketTextForPaste(text, bracketedPasteMode);
+  coreService.triggerDataEvent(text, true);
+  textarea.value = '';
+}
+
+/**
+ * Moves the textarea under the mouse cursor and focuses it.
+ * @param ev The original right click event to be handled.
+ * @param textarea The terminal's textarea.
+ */
+export function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement): void {
+
+  // Calculate textarea position relative to the screen element
+  const pos = screenElement.getBoundingClientRect();
+  const left = ev.clientX - pos.left - 10;
+  const top = ev.clientY - pos.top - 10;
+
+  // Bring textarea at the cursor position
+  textarea.style.position = 'absolute';
+  textarea.style.width = '20px';
+  textarea.style.height = '20px';
+  textarea.style.left = `${left}px`;
+  textarea.style.top = `${top}px`;
+  textarea.style.zIndex = '1000';
+
+  textarea.focus();
+
+  // Reset the terminal textarea's styling
+  // Timeout needs to be long enough for click event to be handled.
+  setTimeout(() => {
+    textarea.style.position = null;
+    textarea.style.width = null;
+    textarea.style.height = null;
+    textarea.style.left = null;
+    textarea.style.top = null;
+    textarea.style.zIndex = null;
+  }, 200);
+}
+
+/**
+ * Bind to right-click event and allow right-click copy and paste.
+ * @param ev The original right click event to be handled.
+ * @param textarea The terminal's textarea.
+ * @param selectionService The terminal's selection manager.
+ * @param shouldSelectWord If true and there is no selection the current word will be selected
+ */
+export function rightClickHandler(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement, selectionService: ISelectionService, shouldSelectWord: boolean): void {
+  moveTextAreaUnderMouseCursor(ev, textarea, screenElement);
+
+  if (shouldSelectWord && !selectionService.isClickInSelection(ev)) {
+    selectionService.selectWordAtCursor(ev);
+  }
+
+  // Get textarea ready to copy from the context menu
+  textarea.value = selectionService.selectionText;
+  textarea.select();
+}
diff --git a/node_modules/xterm/src/browser/ColorManager.ts b/node_modules/xterm/src/browser/ColorManager.ts
new file mode 100644 (file)
index 0000000..70d21a7
--- /dev/null
@@ -0,0 +1,190 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IColorManager, IColor, IColorSet } from 'browser/Types';
+import { ITheme } from 'common/services/Services';
+
+const DEFAULT_FOREGROUND = fromHex('#ffffff');
+const DEFAULT_BACKGROUND = fromHex('#000000');
+const DEFAULT_CURSOR = fromHex('#ffffff');
+const DEFAULT_CURSOR_ACCENT = fromHex('#000000');
+const DEFAULT_SELECTION = {
+  css: 'rgba(255, 255, 255, 0.3)',
+  rgba: 0xFFFFFF77
+};
+
+// An IIFE to generate DEFAULT_ANSI_COLORS. Do not mutate DEFAULT_ANSI_COLORS, instead make a copy
+// and mutate that.
+export const DEFAULT_ANSI_COLORS = (() => {
+  const colors = [
+    // dark:
+    fromHex('#2e3436'),
+    fromHex('#cc0000'),
+    fromHex('#4e9a06'),
+    fromHex('#c4a000'),
+    fromHex('#3465a4'),
+    fromHex('#75507b'),
+    fromHex('#06989a'),
+    fromHex('#d3d7cf'),
+    // bright:
+    fromHex('#555753'),
+    fromHex('#ef2929'),
+    fromHex('#8ae234'),
+    fromHex('#fce94f'),
+    fromHex('#729fcf'),
+    fromHex('#ad7fa8'),
+    fromHex('#34e2e2'),
+    fromHex('#eeeeec')
+  ];
+
+  // Fill in the remaining 240 ANSI colors.
+  // Generate colors (16-231)
+  const v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
+  for (let i = 0; i < 216; i++) {
+    const r = v[(i / 36) % 6 | 0];
+    const g = v[(i / 6) % 6 | 0];
+    const b = v[i % 6];
+    colors.push({
+      css: `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`,
+      // Use >>> 0 to force a conversion to an unsigned int
+      rgba: ((r << 24) | (g << 16) | (b << 8) | 0xFF) >>> 0
+    });
+  }
+
+  // Generate greys (232-255)
+  for (let i = 0; i < 24; i++) {
+    const c = 8 + i * 10;
+    const ch = toPaddedHex(c);
+    colors.push({
+      css: `#${ch}${ch}${ch}`,
+      rgba: ((c << 24) | (c << 16) | (c << 8) | 0xFF) >>> 0
+    });
+  }
+
+  return colors;
+})();
+
+function fromHex(css: string): IColor {
+  return {
+    css,
+    rgba: parseInt(css.slice(1), 16) << 8 | 0xFF
+  };
+}
+
+function toPaddedHex(c: number): string {
+  const s = c.toString(16);
+  return s.length < 2 ? '0' + s : s;
+}
+
+/**
+ * Manages the source of truth for a terminal's colors.
+ */
+export class ColorManager implements IColorManager {
+  public colors: IColorSet;
+  private _ctx: CanvasRenderingContext2D;
+  private _litmusColor: CanvasGradient;
+
+  constructor(document: Document, public allowTransparency: boolean) {
+    const canvas = document.createElement('canvas');
+    canvas.width = 1;
+    canvas.height = 1;
+    const ctx = canvas.getContext('2d');
+    if (!ctx) {
+      throw new Error('Could not get rendering context');
+    }
+    this._ctx = ctx;
+    this._ctx.globalCompositeOperation = 'copy';
+    this._litmusColor = this._ctx.createLinearGradient(0, 0, 1, 1);
+    this.colors = {
+      foreground: DEFAULT_FOREGROUND,
+      background: DEFAULT_BACKGROUND,
+      cursor: DEFAULT_CURSOR,
+      cursorAccent: DEFAULT_CURSOR_ACCENT,
+      selection: DEFAULT_SELECTION,
+      ansi: DEFAULT_ANSI_COLORS.slice()
+    };
+  }
+
+  /**
+   * Sets the terminal's theme.
+   * @param theme The  theme to use. If a partial theme is provided then default
+   * colors will be used where colors are not defined.
+   */
+  public setTheme(theme: ITheme = {}): void {
+    this.colors.foreground = this._parseColor(theme.foreground, DEFAULT_FOREGROUND);
+    this.colors.background = this._parseColor(theme.background, DEFAULT_BACKGROUND);
+    this.colors.cursor = this._parseColor(theme.cursor, DEFAULT_CURSOR, true);
+    this.colors.cursorAccent = this._parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT, true);
+    this.colors.selection = this._parseColor(theme.selection, DEFAULT_SELECTION, true);
+    this.colors.ansi[0] = this._parseColor(theme.black, DEFAULT_ANSI_COLORS[0]);
+    this.colors.ansi[1] = this._parseColor(theme.red, DEFAULT_ANSI_COLORS[1]);
+    this.colors.ansi[2] = this._parseColor(theme.green, DEFAULT_ANSI_COLORS[2]);
+    this.colors.ansi[3] = this._parseColor(theme.yellow, DEFAULT_ANSI_COLORS[3]);
+    this.colors.ansi[4] = this._parseColor(theme.blue, DEFAULT_ANSI_COLORS[4]);
+    this.colors.ansi[5] = this._parseColor(theme.magenta, DEFAULT_ANSI_COLORS[5]);
+    this.colors.ansi[6] = this._parseColor(theme.cyan, DEFAULT_ANSI_COLORS[6]);
+    this.colors.ansi[7] = this._parseColor(theme.white, DEFAULT_ANSI_COLORS[7]);
+    this.colors.ansi[8] = this._parseColor(theme.brightBlack, DEFAULT_ANSI_COLORS[8]);
+    this.colors.ansi[9] = this._parseColor(theme.brightRed, DEFAULT_ANSI_COLORS[9]);
+    this.colors.ansi[10] = this._parseColor(theme.brightGreen, DEFAULT_ANSI_COLORS[10]);
+    this.colors.ansi[11] = this._parseColor(theme.brightYellow, DEFAULT_ANSI_COLORS[11]);
+    this.colors.ansi[12] = this._parseColor(theme.brightBlue, DEFAULT_ANSI_COLORS[12]);
+    this.colors.ansi[13] = this._parseColor(theme.brightMagenta, DEFAULT_ANSI_COLORS[13]);
+    this.colors.ansi[14] = this._parseColor(theme.brightCyan, DEFAULT_ANSI_COLORS[14]);
+    this.colors.ansi[15] = this._parseColor(theme.brightWhite, DEFAULT_ANSI_COLORS[15]);
+  }
+
+  private _parseColor(
+    css: string | undefined,
+    fallback: IColor,
+    allowTransparency: boolean = this.allowTransparency
+  ): IColor {
+    if (css === undefined) {
+      return fallback;
+    }
+
+    // If parsing the value results in failure, then it must be ignored, and the attribute must
+    // retain its previous value.
+    // -- https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles
+    this._ctx.fillStyle = this._litmusColor;
+    this._ctx.fillStyle = css;
+    if (typeof this._ctx.fillStyle !== 'string') {
+      console.warn(`Color: ${css} is invalid using fallback ${fallback.css}`);
+      return fallback;
+    }
+
+    this._ctx.fillRect(0, 0, 1, 1);
+    const data = this._ctx.getImageData(0, 0, 1, 1).data;
+
+    if (!allowTransparency && data[3] !== 0xFF) {
+      // Ideally we'd just ignore the alpha channel, but...
+      //
+      // Browsers may not give back exactly the same RGB values we put in, because most/all
+      // convert the color to a pre-multiplied representation. getImageData converts that back to
+      // a un-premultipled representation, but the precision loss may make the RGB channels unuable
+      // on their own.
+      //
+      // E.g. In Chrome #12345610 turns into #10305010, and in the extreme case, 0xFFFFFF00 turns
+      // into 0x00000000.
+      //
+      // "Note: Due to the lossy nature of converting to and from premultiplied alpha color values,
+      // pixels that have just been set using putImageData() might be returned to an equivalent
+      // getImageData() as different values."
+      // -- https://html.spec.whatwg.org/multipage/canvas.html#pixel-manipulation
+      //
+      // So let's just use the fallback color in this case instead.
+      console.warn(
+        `Color: ${css} is using transparency, but allowTransparency is false. ` +
+        `Using fallback ${fallback.css}.`
+      );
+      return fallback;
+    }
+
+    return {
+      css,
+      rgba: (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0
+    };
+  }
+}
diff --git a/node_modules/xterm/src/browser/Lifecycle.ts b/node_modules/xterm/src/browser/Lifecycle.ts
new file mode 100644 (file)
index 0000000..1344ea9
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+/**
+ * Adds a disposable listener to a node in the DOM, returning the disposable.
+ * @param type The event type.
+ * @param handler The handler for the listener.
+ */
+export function addDisposableDomListener(
+  node: Element | Window | Document,
+  type: string,
+  handler: (e: any) => void,
+  useCapture?: boolean
+): IDisposable {
+  node.addEventListener(type, handler, useCapture);
+  return {
+    dispose: () => {
+      if (!handler) {
+        // Already disposed
+        return;
+      }
+      node.removeEventListener(type, handler, useCapture);
+    }
+  };
+}
diff --git a/node_modules/xterm/src/browser/Linkifier.ts b/node_modules/xterm/src/browser/Linkifier.ts
new file mode 100644 (file)
index 0000000..58aca70
--- /dev/null
@@ -0,0 +1,348 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ILinkifierEvent, ILinkMatcher, LinkMatcherHandler, ILinkMatcherOptions, ILinkifier, IMouseZoneManager, IMouseZone, IRegisteredLinkMatcher } from 'browser/Types';
+import { IBufferStringIteratorResult } from 'common/buffer/Types';
+import { getStringCellWidth } from 'common/CharWidth';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { ILogService, IBufferService } from 'common/services/Services';
+
+/**
+ * Limit of the unwrapping line expansion (overscan) at the top and bottom
+ * of the actual viewport in ASCII characters.
+ * A limit of 2000 should match most sane urls.
+ */
+const OVERSCAN_CHAR_LIMIT = 2000;
+
+/**
+ * The Linkifier applies links to rows shortly after they have been refreshed.
+ */
+export class Linkifier implements ILinkifier {
+  /**
+   * The time to wait after a row is changed before it is linkified. This prevents
+   * the costly operation of searching every row multiple times, potentially a
+   * huge amount of times.
+   */
+  protected static _timeBeforeLatency = 200;
+
+  protected _linkMatchers: IRegisteredLinkMatcher[] = [];
+
+  private _mouseZoneManager: IMouseZoneManager | undefined;
+  private _element: HTMLElement | undefined;
+
+  private _rowsTimeoutId: number | undefined;
+  private _nextLinkMatcherId = 0;
+  private _rowsToLinkify: { start: number | undefined, end: number | undefined };
+
+  private _onLinkHover = new EventEmitter<ILinkifierEvent>();
+  public get onLinkHover(): IEvent<ILinkifierEvent> { return this._onLinkHover.event; }
+  private _onLinkLeave = new EventEmitter<ILinkifierEvent>();
+  public get onLinkLeave(): IEvent<ILinkifierEvent> { return this._onLinkLeave.event; }
+  private _onLinkTooltip = new EventEmitter<ILinkifierEvent>();
+  public get onLinkTooltip(): IEvent<ILinkifierEvent> { return this._onLinkTooltip.event; }
+
+  constructor(
+    protected readonly _bufferService: IBufferService,
+    private readonly _logService: ILogService
+  ) {
+    this._rowsToLinkify = {
+      start: undefined,
+      end: undefined
+    };
+  }
+
+  /**
+   * Attaches the linkifier to the DOM, enabling linkification.
+   * @param mouseZoneManager The mouse zone manager to register link zones with.
+   */
+  public attachToDom(element: HTMLElement, mouseZoneManager: IMouseZoneManager): void {
+    this._element = element;
+    this._mouseZoneManager = mouseZoneManager;
+  }
+
+  /**
+   * Queue linkification on a set of rows.
+   * @param start The row to linkify from (inclusive).
+   * @param end The row to linkify to (inclusive).
+   */
+  public linkifyRows(start: number, end: number): void {
+    // Don't attempt linkify if not yet attached to DOM
+    if (!this._mouseZoneManager) {
+      return;
+    }
+
+    // Increase range to linkify
+    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {
+      this._rowsToLinkify.start = start;
+      this._rowsToLinkify.end = end;
+    } else {
+      this._rowsToLinkify.start = Math.min(this._rowsToLinkify.start, start);
+      this._rowsToLinkify.end = Math.max(this._rowsToLinkify.end, end);
+    }
+
+    // Clear out any existing links on this row range
+    this._mouseZoneManager.clearAll(start, end);
+
+    // Restart timer
+    if (this._rowsTimeoutId) {
+      clearTimeout(this._rowsTimeoutId);
+    }
+    this._rowsTimeoutId = <number><any>setTimeout(() => this._linkifyRows(), Linkifier._timeBeforeLatency);
+  }
+
+  /**
+   * Linkifies the rows requested.
+   */
+  private _linkifyRows(): void {
+    this._rowsTimeoutId = undefined;
+    const buffer = this._bufferService.buffer;
+
+    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {
+      this._logService.debug('_rowToLinkify was unset before _linkifyRows was called');
+      return;
+    }
+
+    // Ensure the start row exists
+    const absoluteRowIndexStart = buffer.ydisp + this._rowsToLinkify.start;
+    if (absoluteRowIndexStart >= buffer.lines.length) {
+      return;
+    }
+
+    // Invalidate bad end row values (if a resize happened)
+    const absoluteRowIndexEnd = buffer.ydisp + Math.min(this._rowsToLinkify.end, this._bufferService.rows) + 1;
+
+    // Iterate over the range of unwrapped content strings within start..end
+    // (excluding).
+    // _doLinkifyRow gets full unwrapped lines with the start row as buffer offset
+    // for every matcher.
+    // The unwrapping is needed to also match content that got wrapped across
+    // several buffer lines. To avoid a worst case scenario where the whole buffer
+    // contains just a single unwrapped string we limit this line expansion beyond
+    // the viewport to +OVERSCAN_CHAR_LIMIT chars (overscan) at top and bottom.
+    // This comes with the tradeoff that matches longer than OVERSCAN_CHAR_LIMIT
+    // chars will not match anymore at the viewport borders.
+    const overscanLineLimit = Math.ceil(OVERSCAN_CHAR_LIMIT / this._bufferService.cols);
+    const iterator = this._bufferService.buffer.iterator(
+      false, absoluteRowIndexStart, absoluteRowIndexEnd, overscanLineLimit, overscanLineLimit);
+    while (iterator.hasNext()) {
+      const lineData: IBufferStringIteratorResult = iterator.next();
+      for (let i = 0; i < this._linkMatchers.length; i++) {
+        this._doLinkifyRow(lineData.range.first, lineData.content, this._linkMatchers[i]);
+      }
+    }
+
+    this._rowsToLinkify.start = undefined;
+    this._rowsToLinkify.end = undefined;
+  }
+
+  /**
+   * Registers a link matcher, allowing custom link patterns to be matched and
+   * handled.
+   * @param regex The regular expression to search for. Specifically, this
+   * searches the textContent of the rows. You will want to use \s to match a
+   * space ' ' character for example.
+   * @param handler The callback when the link is called.
+   * @param options Options for the link matcher.
+   * @return The ID of the new matcher, this can be used to deregister.
+   */
+  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: ILinkMatcherOptions = {}): number {
+    if (!handler) {
+      throw new Error('handler must be defined');
+    }
+    const matcher: IRegisteredLinkMatcher = {
+      id: this._nextLinkMatcherId++,
+      regex,
+      handler,
+      matchIndex: options.matchIndex,
+      validationCallback: options.validationCallback,
+      hoverTooltipCallback: options.tooltipCallback,
+      hoverLeaveCallback: options.leaveCallback,
+      willLinkActivate: options.willLinkActivate,
+      priority: options.priority || 0
+    };
+    this._addLinkMatcherToList(matcher);
+    return matcher.id;
+  }
+
+  /**
+   * Inserts a link matcher to the list in the correct position based on the
+   * priority of each link matcher. New link matchers of equal priority are
+   * considered after older link matchers.
+   * @param matcher The link matcher to be added.
+   */
+  private _addLinkMatcherToList(matcher: IRegisteredLinkMatcher): void {
+    if (this._linkMatchers.length === 0) {
+      this._linkMatchers.push(matcher);
+      return;
+    }
+
+    for (let i = this._linkMatchers.length - 1; i >= 0; i--) {
+      if (matcher.priority <= this._linkMatchers[i].priority) {
+        this._linkMatchers.splice(i + 1, 0, matcher);
+        return;
+      }
+    }
+
+    this._linkMatchers.splice(0, 0, matcher);
+  }
+
+  /**
+   * Deregisters a link matcher if it has been registered.
+   * @param matcherId The link matcher's ID (returned after register)
+   * @return Whether a link matcher was found and deregistered.
+   */
+  public deregisterLinkMatcher(matcherId: number): boolean {
+    for (let i = 0; i < this._linkMatchers.length; i++) {
+      if (this._linkMatchers[i].id === matcherId) {
+        this._linkMatchers.splice(i, 1);
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Linkifies a row given a specific handler.
+   * @param rowIndex The row index to linkify (absolute index).
+   * @param text string content of the unwrapped row.
+   * @param matcher The link matcher for this line.
+   */
+  private _doLinkifyRow(rowIndex: number, text: string, matcher: ILinkMatcher): void {
+    // clone regex to do a global search on text
+    const rex = new RegExp(matcher.regex.source, (matcher.regex.flags || '') + 'g');
+    let match;
+    let stringIndex = -1;
+    while ((match = rex.exec(text)) !== null) {
+      const uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];
+      if (!uri) {
+        // something matched but does not comply with the given matchIndex
+        // since this is most likely a bug the regex itself we simply do nothing here
+        this._logService.debug('match found without corresponding matchIndex', match, matcher);
+        break;
+      }
+
+      // Get index, match.index is for the outer match which includes negated chars
+      // therefore we cannot use match.index directly, instead we search the position
+      // of the match group in text again
+      // also correct regex and string search offsets for the next loop run
+      stringIndex = text.indexOf(uri, stringIndex + 1);
+      rex.lastIndex = stringIndex + uri.length;
+      if (stringIndex < 0) {
+        // invalid stringIndex (should not have happened)
+        break;
+      }
+
+      // get the buffer index as [absolute row, col] for the match
+      const bufferIndex = this._bufferService.buffer.stringIndexToBufferIndex(rowIndex, stringIndex);
+      if (bufferIndex[0] < 0) {
+        // invalid bufferIndex (should not have happened)
+        break;
+      }
+
+      const line = this._bufferService.buffer.lines.get(bufferIndex[0]);
+      if (!line) {
+        break;
+      }
+
+      const attr = line.getFg(bufferIndex[1]);
+      const fg = attr ? (attr >> 9) & 0x1ff : undefined;
+
+      if (matcher.validationCallback) {
+        matcher.validationCallback(uri, isValid => {
+          // Discard link if the line has already changed
+          if (this._rowsTimeoutId) {
+            return;
+          }
+          if (isValid) {
+            this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);
+          }
+        });
+      } else {
+        this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);
+      }
+    }
+  }
+
+  /**
+   * Registers a link to the mouse zone manager.
+   * @param x The column the link starts.
+   * @param y The row the link is on.
+   * @param uri The URI of the link.
+   * @param matcher The link matcher for the link.
+   * @param fg The link color for hover event.
+   */
+  private _addLink(x: number, y: number, uri: string, matcher: ILinkMatcher, fg: number | undefined): void {
+    if (!this._mouseZoneManager || !this._element) {
+      return;
+    }
+
+    const width = getStringCellWidth(uri);
+    const x1 = x % this._bufferService.cols;
+    const y1 = y + Math.floor(x / this._bufferService.cols);
+    let x2 = (x1 + width) % this._bufferService.cols;
+    let y2 = y1 + Math.floor((x1 + width) / this._bufferService.cols);
+    if (x2 === 0) {
+      x2 = this._bufferService.cols;
+      y2--;
+    }
+
+    this._mouseZoneManager.add(new MouseZone(
+      x1 + 1,
+      y1 + 1,
+      x2 + 1,
+      y2 + 1,
+      e => {
+        if (matcher.handler) {
+          return matcher.handler(e, uri);
+        }
+        window.open(uri, '_blank');
+      },
+      () => {
+        this._onLinkHover.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));
+        this._element!.classList.add('xterm-cursor-pointer');
+      },
+      e => {
+        this._onLinkTooltip.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));
+        if (matcher.hoverTooltipCallback) {
+          // Note that IViewportRange use 1-based coordinates to align with escape sequences such
+          // as CUP which use 1,1 as the default for row/col
+          matcher.hoverTooltipCallback(e, uri, { start: { x: x1, y: y1 }, end: { x: x2, y: y2 } });
+        }
+      },
+      () => {
+        this._onLinkLeave.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));
+        this._element!.classList.remove('xterm-cursor-pointer');
+        if (matcher.hoverLeaveCallback) {
+          matcher.hoverLeaveCallback();
+        }
+      },
+      e => {
+        if (matcher.willLinkActivate) {
+          return matcher.willLinkActivate(e, uri);
+        }
+        return true;
+      }
+    ));
+  }
+
+  private _createLinkHoverEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent {
+    return { x1, y1, x2, y2, cols: this._bufferService.cols, fg };
+  }
+}
+
+export class MouseZone implements IMouseZone {
+  constructor(
+    public x1: number,
+    public y1: number,
+    public x2: number,
+    public y2: number,
+    public clickCallback: (e: MouseEvent) => any,
+    public hoverCallback: (e: MouseEvent) => any,
+    public tooltipCallback: (e: MouseEvent) => any,
+    public leaveCallback: () => void,
+    public willLinkActivate: (e: MouseEvent) => boolean
+  ) {
+  }
+}
diff --git a/node_modules/xterm/src/browser/LocalizableStrings.ts b/node_modules/xterm/src/browser/LocalizableStrings.ts
new file mode 100644 (file)
index 0000000..8e78233
--- /dev/null
@@ -0,0 +1,7 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export let promptLabel = 'Terminal input';
+export let tooMuchOutput = 'Too much output to announce, navigate to rows manually to read';
diff --git a/node_modules/xterm/src/browser/MouseZoneManager.ts b/node_modules/xterm/src/browser/MouseZoneManager.ts
new file mode 100644 (file)
index 0000000..7eb7c5f
--- /dev/null
@@ -0,0 +1,241 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Disposable } from 'common/Lifecycle';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { IMouseService, ISelectionService } from 'browser/services/Services';
+import { IMouseZoneManager, IMouseZone } from 'browser/Types';
+import { IBufferService } from 'common/services/Services';
+
+const HOVER_DURATION = 500;
+
+/**
+ * The MouseZoneManager allows components to register zones within the terminal
+ * that trigger hover and click callbacks.
+ *
+ * This class was intentionally made not so robust initially as the only case it
+ * needed to support was single-line links which never overlap. Improvements can
+ * be made in the future.
+ */
+export class MouseZoneManager extends Disposable implements IMouseZoneManager {
+  private _zones: IMouseZone[] = [];
+
+  private _areZonesActive: boolean = false;
+  private _mouseMoveListener: (e: MouseEvent) => any;
+  private _mouseLeaveListener: (e: MouseEvent) => any;
+  private _clickListener: (e: MouseEvent) => any;
+
+  private _tooltipTimeout: number | undefined;
+  private _currentZone: IMouseZone | undefined;
+  private _lastHoverCoords: [number | undefined, number | undefined] = [undefined, undefined];
+  private _initialSelectionLength: number = 0;
+
+  constructor(
+    private readonly _element: HTMLElement,
+    private readonly _screenElement: HTMLElement,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @IMouseService private readonly _mouseService: IMouseService,
+    @ISelectionService private readonly _selectionService: ISelectionService
+  ) {
+    super();
+
+    this.register(addDisposableDomListener(this._element, 'mousedown', e => this._onMouseDown(e)));
+
+    // These events are expensive, only listen to it when mouse zones are active
+    this._mouseMoveListener = e => this._onMouseMove(e);
+    this._mouseLeaveListener = e => this._onMouseLeave(e);
+    this._clickListener = e => this._onClick(e);
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this._deactivate();
+  }
+
+  public add(zone: IMouseZone): void {
+    this._zones.push(zone);
+    if (this._zones.length === 1) {
+      this._activate();
+    }
+  }
+
+  public clearAll(start?: number, end?: number): void {
+    // Exit if there's nothing to clear
+    if (this._zones.length === 0) {
+      return;
+    }
+
+    // Clear all if start/end weren't set
+    if (!start || !end) {
+      start = 0;
+      end = this._bufferService.rows - 1;
+    }
+
+    // Iterate through zones and clear them out if they're within the range
+    for (let i = 0; i < this._zones.length; i++) {
+      const zone = this._zones[i];
+      if ((zone.y1 > start && zone.y1 <= end + 1) ||
+          (zone.y2 > start && zone.y2 <= end + 1) ||
+          (zone.y1 < start && zone.y2 > end + 1)) {
+        if (this._currentZone && this._currentZone === zone) {
+          this._currentZone.leaveCallback();
+          this._currentZone = undefined;
+        }
+        this._zones.splice(i--, 1);
+      }
+    }
+
+    // Deactivate the mouse zone manager if all the zones have been removed
+    if (this._zones.length === 0) {
+      this._deactivate();
+    }
+  }
+
+  private _activate(): void {
+    if (!this._areZonesActive) {
+      this._areZonesActive = true;
+      this._element.addEventListener('mousemove', this._mouseMoveListener);
+      this._element.addEventListener('mouseleave', this._mouseLeaveListener);
+      this._element.addEventListener('click', this._clickListener);
+    }
+  }
+
+  private _deactivate(): void {
+    if (this._areZonesActive) {
+      this._areZonesActive = false;
+      this._element.removeEventListener('mousemove', this._mouseMoveListener);
+      this._element.removeEventListener('mouseleave', this._mouseLeaveListener);
+      this._element.removeEventListener('click', this._clickListener);
+    }
+  }
+
+  private _onMouseMove(e: MouseEvent): void {
+    // TODO: Ideally this would only clear the hover state when the mouse moves
+    // outside of the mouse zone
+    if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) {
+      this._onHover(e);
+      // Record the current coordinates
+      this._lastHoverCoords = [e.pageX, e.pageY];
+    }
+  }
+
+  private _onHover(e: MouseEvent): void {
+    const zone = this._findZoneEventAt(e);
+
+    // Do nothing if the zone is the same
+    if (zone === this._currentZone) {
+      return;
+    }
+
+    // Fire the hover end callback and cancel any existing timer if a new zone
+    // is being hovered
+    if (this._currentZone) {
+      this._currentZone.leaveCallback();
+      this._currentZone = undefined;
+      if (this._tooltipTimeout) {
+        clearTimeout(this._tooltipTimeout);
+      }
+    }
+
+    // Exit if there is not zone
+    if (!zone) {
+      return;
+    }
+    this._currentZone = zone;
+
+    // Trigger the hover callback
+    if (zone.hoverCallback) {
+      zone.hoverCallback(e);
+    }
+
+    // Restart the tooltip timeout
+    this._tooltipTimeout = <number><any>setTimeout(() => this._onTooltip(e), HOVER_DURATION);
+  }
+
+  private _onTooltip(e: MouseEvent): void {
+    this._tooltipTimeout = undefined;
+    const zone = this._findZoneEventAt(e);
+    if (zone && zone.tooltipCallback) {
+      zone.tooltipCallback(e);
+    }
+  }
+
+  private _onMouseDown(e: MouseEvent): void {
+    // Store current terminal selection length, to check if we're performing
+    // a selection operation
+    this._initialSelectionLength = this._getSelectionLength();
+
+    // Ignore the event if there are no zones active
+    if (!this._areZonesActive) {
+      return;
+    }
+
+    // Find the active zone, prevent event propagation if found to prevent other
+    // components from handling the mouse event.
+    const zone = this._findZoneEventAt(e);
+    if (zone) {
+      if (zone.willLinkActivate(e)) {
+        e.preventDefault();
+        e.stopImmediatePropagation();
+      }
+    }
+  }
+
+  private _onMouseLeave(e: MouseEvent): void {
+    // Fire the hover end callback and cancel any existing timer if the mouse
+    // leaves the terminal element
+    if (this._currentZone) {
+      this._currentZone.leaveCallback();
+      this._currentZone = undefined;
+      if (this._tooltipTimeout) {
+        clearTimeout(this._tooltipTimeout);
+      }
+    }
+  }
+
+  private _onClick(e: MouseEvent): void {
+    // Find the active zone and click it if found and no selection was
+    // being performed
+    const zone = this._findZoneEventAt(e);
+    const currentSelectionLength = this._getSelectionLength();
+
+    if (zone && currentSelectionLength === this._initialSelectionLength) {
+      zone.clickCallback(e);
+      e.preventDefault();
+      e.stopImmediatePropagation();
+    }
+  }
+
+  private _getSelectionLength(): number {
+    const selectionText = this._selectionService.selectionText;
+    return selectionText ? selectionText.length : 0;
+  }
+
+  private _findZoneEventAt(e: MouseEvent): IMouseZone | undefined {
+    const coords = this._mouseService.getCoords(e, this._screenElement, this._bufferService.cols, this._bufferService.rows);
+    if (!coords) {
+      return undefined;
+    }
+    const x = coords[0];
+    const y = coords[1];
+    for (let i = 0; i < this._zones.length; i++) {
+      const zone = this._zones[i];
+      if (zone.y1 === zone.y2) {
+        // Single line link
+        if (y === zone.y1 && x >= zone.x1 && x < zone.x2) {
+          return zone;
+        }
+      } else {
+        // Multi-line link
+        if ((y === zone.y1 && x >= zone.x1) ||
+            (y === zone.y2 && x < zone.x2) ||
+            (y > zone.y1 && y < zone.y2)) {
+          return zone;
+        }
+      }
+    }
+    return undefined;
+  }
+}
diff --git a/node_modules/xterm/src/browser/RenderDebouncer.ts b/node_modules/xterm/src/browser/RenderDebouncer.ts
new file mode 100644 (file)
index 0000000..27c866d
--- /dev/null
@@ -0,0 +1,63 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+/**
+ * Debounces calls to render terminal rows using animation frames.
+ */
+export class RenderDebouncer implements IDisposable {
+  private _rowStart: number | undefined;
+  private _rowEnd: number | undefined;
+  private _rowCount: number | undefined;
+  private _animationFrame: number | undefined;
+
+  constructor(
+    private _renderCallback: (start: number, end: number) => void
+  ) {
+  }
+
+  public dispose(): void {
+    if (this._animationFrame) {
+      window.cancelAnimationFrame(this._animationFrame);
+      this._animationFrame = undefined;
+    }
+  }
+
+  public refresh(rowStart: number, rowEnd: number, rowCount: number): void {
+    this._rowCount = rowCount;
+    // Get the min/max row start/end for the arg values
+    rowStart = rowStart !== undefined ? rowStart : 0;
+    rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;
+    // Set the properties to the updated values
+    this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;
+    this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;
+
+    if (this._animationFrame) {
+      return;
+    }
+
+    this._animationFrame = window.requestAnimationFrame(() => this._innerRefresh());
+  }
+
+  private _innerRefresh(): void {
+    // Make sure values are set
+    if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {
+      return;
+    }
+
+    // Clamp values
+    this._rowStart = Math.max(this._rowStart, 0);
+    this._rowEnd = Math.min(this._rowEnd, this._rowCount - 1);
+
+    // Run render callback
+    this._renderCallback(this._rowStart, this._rowEnd);
+
+    // Reset debouncer
+    this._rowStart = undefined;
+    this._rowEnd = undefined;
+    this._animationFrame = undefined;
+  }
+}
diff --git a/node_modules/xterm/src/browser/ScreenDprMonitor.ts b/node_modules/xterm/src/browser/ScreenDprMonitor.ts
new file mode 100644 (file)
index 0000000..ec8c6d8
--- /dev/null
@@ -0,0 +1,69 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Disposable } from 'common/Lifecycle';
+
+export type ScreenDprListener = (newDevicePixelRatio?: number, oldDevicePixelRatio?: number) => void;
+
+/**
+ * The screen device pixel ratio monitor allows listening for when the
+ * window.devicePixelRatio value changes. This is done not with polling but with
+ * the use of window.matchMedia to watch media queries. When the event fires,
+ * the listener will be reattached using a different media query to ensure that
+ * any further changes will register.
+ *
+ * The listener should fire on both window zoom changes and switching to a
+ * monitor with a different DPI.
+ */
+export class ScreenDprMonitor extends Disposable {
+  private _currentDevicePixelRatio: number = window.devicePixelRatio;
+  private _outerListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | undefined;
+  private _listener: ScreenDprListener | undefined;
+  private _resolutionMediaMatchList: MediaQueryList | undefined;
+
+  public setListener(listener: ScreenDprListener): void {
+    if (this._listener) {
+      this.clearListener();
+    }
+    this._listener = listener;
+    this._outerListener = () => {
+      if (!this._listener) {
+        return;
+      }
+      this._listener(window.devicePixelRatio, this._currentDevicePixelRatio);
+      this._updateDpr();
+    };
+    this._updateDpr();
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this.clearListener();
+  }
+
+  private _updateDpr(): void {
+    if (!this._resolutionMediaMatchList || !this._outerListener) {
+      return;
+    }
+
+    // Clear listeners for old DPR
+    this._resolutionMediaMatchList.removeListener(this._outerListener);
+
+    // Add listeners for new DPR
+    this._currentDevicePixelRatio = window.devicePixelRatio;
+    this._resolutionMediaMatchList = window.matchMedia(`screen and (resolution: ${window.devicePixelRatio}dppx)`);
+    this._resolutionMediaMatchList.addListener(this._outerListener);
+  }
+
+  public clearListener(): void {
+    if (!this._resolutionMediaMatchList || !this._listener || !this._outerListener) {
+      return;
+    }
+    this._resolutionMediaMatchList.removeListener(this._outerListener);
+    this._resolutionMediaMatchList = undefined;
+    this._listener = undefined;
+    this._outerListener = undefined;
+  }
+}
diff --git a/node_modules/xterm/src/browser/Types.d.ts b/node_modules/xterm/src/browser/Types.d.ts
new file mode 100644 (file)
index 0000000..aa7a4c8
--- /dev/null
@@ -0,0 +1,145 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent } from 'common/EventEmitter';
+import { IDisposable } from 'common/Types';
+
+export interface IColorManager {
+  colors: IColorSet;
+}
+
+export interface IColor {
+  css: string;
+  rgba: number; // 32-bit int with rgba in each byte
+}
+
+export interface IColorSet {
+  foreground: IColor;
+  background: IColor;
+  cursor: IColor;
+  cursorAccent: IColor;
+  selection: IColor;
+  ansi: IColor[];
+}
+
+export interface IPartialColorSet {
+  foreground: IColor;
+  background: IColor;
+  cursor?: IColor;
+  cursorAccent?: IColor;
+  selection?: IColor;
+  ansi: IColor[];
+}
+
+export interface IViewport extends IDisposable {
+  scrollBarWidth: number;
+  syncScrollArea(immediate?: boolean): void;
+  getLinesScrolled(ev: WheelEvent): number;
+  onWheel(ev: WheelEvent): boolean;
+  onTouchStart(ev: TouchEvent): void;
+  onTouchMove(ev: TouchEvent): boolean;
+  onThemeChange(colors: IColorSet): void;
+}
+
+export interface IViewportRange {
+  start: IViewportRangePosition;
+  end: IViewportRangePosition;
+}
+
+export interface IViewportRangePosition {
+  x: number;
+  y: number;
+}
+
+export type LinkMatcherHandler = (event: MouseEvent, uri: string) => void;
+export type LinkMatcherHoverTooltipCallback = (event: MouseEvent, uri: string, position: IViewportRange) => void;
+export type LinkMatcherValidationCallback = (uri: string, callback: (isValid: boolean) => void) => void;
+
+export interface ILinkMatcher {
+  id: number;
+  regex: RegExp;
+  handler: LinkMatcherHandler;
+  hoverTooltipCallback?: LinkMatcherHoverTooltipCallback;
+  hoverLeaveCallback?: () => void;
+  matchIndex?: number;
+  validationCallback?: LinkMatcherValidationCallback;
+  priority?: number;
+  willLinkActivate?: (event: MouseEvent, uri: string) => boolean;
+}
+
+export interface IRegisteredLinkMatcher extends ILinkMatcher {
+  priority: number;
+}
+
+export interface ILinkifierEvent {
+  x1: number;
+  y1: number;
+  x2: number;
+  y2: number;
+  cols: number;
+  fg: number | undefined;
+}
+
+export interface ILinkifier {
+  onLinkHover: IEvent<ILinkifierEvent>;
+  onLinkLeave: IEvent<ILinkifierEvent>;
+  onLinkTooltip: IEvent<ILinkifierEvent>;
+
+  attachToDom(element: HTMLElement, mouseZoneManager: IMouseZoneManager): void;
+  linkifyRows(start: number, end: number): void;
+  registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?: ILinkMatcherOptions): number;
+  deregisterLinkMatcher(matcherId: number): boolean;
+}
+
+export interface ILinkMatcherOptions {
+  /**
+   * The index of the link from the regex.match(text) call. This defaults to 0
+   * (for regular expressions without capture groups).
+   */
+  matchIndex?: number;
+  /**
+   * A callback that validates an individual link, returning true if valid and
+   * false if invalid.
+   */
+  validationCallback?: LinkMatcherValidationCallback;
+  /**
+   * A callback that fires when the mouse hovers over a link.
+   */
+  tooltipCallback?: LinkMatcherHoverTooltipCallback;
+  /**
+   * A callback that fires when the mouse leaves a link that was hovered.
+   */
+  leaveCallback?: () => void;
+  /**
+   * The priority of the link matcher, this defines the order in which the link
+   * matcher is evaluated relative to others, from highest to lowest. The
+   * default value is 0.
+   */
+  priority?: number;
+  /**
+   * A callback that fires when the mousedown and click events occur that
+   * determines whether a link will be activated upon click. This enables
+   * only activating a link when a certain modifier is held down, if not the
+   * mouse event will continue propagation (eg. double click to select word).
+   */
+  willLinkActivate?: (event: MouseEvent, uri: string) => boolean;
+}
+
+export interface IMouseZoneManager extends IDisposable {
+  add(zone: IMouseZone): void;
+  clearAll(start?: number, end?: number): void;
+}
+
+export interface IMouseZone {
+  x1: number;
+  x2: number;
+  y1: number;
+  y2: number;
+  clickCallback: (e: MouseEvent) => any;
+  hoverCallback: (e: MouseEvent) => any | undefined;
+  tooltipCallback: (e: MouseEvent) => any | undefined;
+  leaveCallback: () => any | undefined;
+  willLinkActivate: (e: MouseEvent) => boolean;
+}
diff --git a/node_modules/xterm/src/browser/Viewport.ts b/node_modules/xterm/src/browser/Viewport.ts
new file mode 100644 (file)
index 0000000..b88f381
--- /dev/null
@@ -0,0 +1,267 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Disposable } from 'common/Lifecycle';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { IColorSet, IViewport } from 'browser/Types';
+import { ICharSizeService, IRenderService } from 'browser/services/Services';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+const FALLBACK_SCROLL_BAR_WIDTH = 15;
+
+/**
+ * Represents the viewport of a terminal, the visible area within the larger buffer of output.
+ * Logic for the virtual scroll bar is included in this object.
+ */
+export class Viewport extends Disposable implements IViewport {
+  public scrollBarWidth: number = 0;
+  private _currentRowHeight: number = 0;
+  private _lastRecordedBufferLength: number = 0;
+  private _lastRecordedViewportHeight: number = 0;
+  private _lastRecordedBufferHeight: number = 0;
+  private _lastTouchY: number = 0;
+  private _lastScrollTop: number = 0;
+
+  // Stores a partial line amount when scrolling, this is used to keep track of how much of a line
+  // is scrolled so we can "scroll" over partial lines and feel natural on touchpads. This is a
+  // quick fix and could have a more robust solution in place that reset the value when needed.
+  private _wheelPartialScroll: number = 0;
+
+  private _refreshAnimationFrame: number | null = null;
+  private _ignoreNextScrollEvent: boolean = false;
+
+  constructor(
+    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,
+    private readonly _viewportElement: HTMLElement,
+    private readonly _scrollArea: HTMLElement,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @IOptionsService private readonly _optionsService: IOptionsService,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService,
+    @IRenderService private readonly _renderService: IRenderService
+  ) {
+    super();
+
+    // Measure the width of the scrollbar. If it is 0 we can assume it's an OSX overlay scrollbar.
+    // Unfortunately the overlay scrollbar would be hidden underneath the screen element in that case,
+    // therefore we account for a standard amount to make it visible
+    this.scrollBarWidth = (this._viewportElement.offsetWidth - this._scrollArea.offsetWidth) || FALLBACK_SCROLL_BAR_WIDTH;
+    this.register(addDisposableDomListener(this._viewportElement, 'scroll', this._onScroll.bind(this)));
+
+    // Perform this async to ensure the ICharSizeService is ready.
+    setTimeout(() => this.syncScrollArea(), 0);
+  }
+
+  public onThemeChange(colors: IColorSet): void {
+    this._viewportElement.style.backgroundColor = colors.background.css;
+  }
+
+  /**
+   * Refreshes row height, setting line-height, viewport height and scroll area height if
+   * necessary.
+   */
+  private _refresh(immediate: boolean): void {
+    if (immediate) {
+      this._innerRefresh();
+      if (this._refreshAnimationFrame !== null) {
+        cancelAnimationFrame(this._refreshAnimationFrame);
+      }
+      return;
+    }
+    if (this._refreshAnimationFrame === null) {
+      this._refreshAnimationFrame = requestAnimationFrame(() => this._innerRefresh());
+    }
+  }
+
+  private _innerRefresh(): void {
+    if (this._charSizeService.height > 0) {
+      this._currentRowHeight = this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio;
+      this._lastRecordedViewportHeight = this._viewportElement.offsetHeight;
+      const newBufferHeight = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._renderService.dimensions.canvasHeight);
+      if (this._lastRecordedBufferHeight !== newBufferHeight) {
+        this._lastRecordedBufferHeight = newBufferHeight;
+        this._scrollArea.style.height = this._lastRecordedBufferHeight + 'px';
+      }
+    }
+
+    // Sync scrollTop
+    const scrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;
+    if (this._viewportElement.scrollTop !== scrollTop) {
+      // Ignore the next scroll event which will be triggered by setting the scrollTop as we do not
+      // want this event to scroll the terminal
+      this._ignoreNextScrollEvent = true;
+      this._viewportElement.scrollTop = scrollTop;
+    }
+
+    this._refreshAnimationFrame = null;
+  }
+  /**
+   * Updates dimensions and synchronizes the scroll area if necessary.
+   */
+  public syncScrollArea(immediate: boolean = false): void {
+    // If buffer height changed
+    if (this._lastRecordedBufferLength !== this._bufferService.buffer.lines.length) {
+      this._lastRecordedBufferLength = this._bufferService.buffer.lines.length;
+      this._refresh(immediate);
+      return;
+    }
+
+    // If viewport height changed
+    if (this._lastRecordedViewportHeight !== this._renderService.dimensions.canvasHeight) {
+      this._refresh(immediate);
+      return;
+    }
+
+    // If the buffer position doesn't match last scroll top
+    const newScrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;
+    if (this._lastScrollTop !== newScrollTop) {
+      this._refresh(immediate);
+      return;
+    }
+
+    // If element's scroll top changed, this can happen when hiding the element
+    if (this._lastScrollTop !== this._viewportElement.scrollTop) {
+      this._refresh(immediate);
+      return;
+    }
+
+    // If row height changed
+    if (this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio !== this._currentRowHeight) {
+      this._refresh(immediate);
+      return;
+    }
+  }
+
+  /**
+   * Handles scroll events on the viewport, calculating the new viewport and requesting the
+   * terminal to scroll to it.
+   * @param ev The scroll event.
+   */
+  private _onScroll(ev: Event): void {
+    // Record current scroll top position
+    this._lastScrollTop = this._viewportElement.scrollTop;
+
+    // Don't attempt to scroll if the element is not visible, otherwise scrollTop will be corrupt
+    // which causes the terminal to scroll the buffer to the top
+    if (!this._viewportElement.offsetParent) {
+      return;
+    }
+
+    // Ignore the event if it was flagged to ignore (when the source of the event is from Viewport)
+    if (this._ignoreNextScrollEvent) {
+      this._ignoreNextScrollEvent = false;
+      return;
+    }
+
+    const newRow = Math.round(this._lastScrollTop / this._currentRowHeight);
+    const diff = newRow - this._bufferService.buffer.ydisp;
+    this._scrollLines(diff, true);
+  }
+
+  /**
+   * Handles bubbling of scroll event in case the viewport has reached top or bottom
+   * @param ev The scroll event.
+   * @param amount The amount scrolled
+   */
+  private _bubbleScroll(ev: Event, amount: number): boolean {
+    const scrollPosFromTop = this._viewportElement.scrollTop + this._lastRecordedViewportHeight;
+    if ((amount < 0 && this._viewportElement.scrollTop !== 0) ||
+        (amount > 0 &&  scrollPosFromTop < this._lastRecordedBufferHeight)) {
+      if (ev.cancelable) {
+        ev.preventDefault();
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Handles mouse wheel events by adjusting the viewport's scrollTop and delegating the actual
+   * scrolling to `onScroll`, this event needs to be attached manually by the consumer of
+   * `Viewport`.
+   * @param ev The mouse wheel event.
+   */
+  public onWheel(ev: WheelEvent): boolean {
+    const amount = this._getPixelsScrolled(ev);
+    if (amount === 0) {
+      return false;
+    }
+    this._viewportElement.scrollTop += amount;
+    return this._bubbleScroll(ev, amount);
+  }
+
+  private _getPixelsScrolled(ev: WheelEvent): number {
+    // Do nothing if it's not a vertical scroll event
+    if (ev.deltaY === 0) {
+      return 0;
+    }
+
+    // Fallback to WheelEvent.DOM_DELTA_PIXEL
+    let amount = this._applyScrollModifier(ev.deltaY, ev);
+    if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {
+      amount *= this._currentRowHeight;
+    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
+      amount *= this._currentRowHeight * this._bufferService.rows;
+    }
+    return amount;
+  }
+
+  /**
+   * Gets the number of pixels scrolled by the mouse event taking into account what type of delta
+   * is being used.
+   * @param ev The mouse wheel event.
+   */
+  public getLinesScrolled(ev: WheelEvent): number {
+    // Do nothing if it's not a vertical scroll event
+    if (ev.deltaY === 0) {
+      return 0;
+    }
+
+    // Fallback to WheelEvent.DOM_DELTA_LINE
+    let amount = this._applyScrollModifier(ev.deltaY, ev);
+    if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
+      amount /= this._currentRowHeight + 0.0; // Prevent integer division
+      this._wheelPartialScroll += amount;
+      amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);
+      this._wheelPartialScroll %= 1;
+    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
+      amount *= this._bufferService.rows;
+    }
+    return amount;
+  }
+
+  private _applyScrollModifier(amount: number, ev: WheelEvent): number {
+    const modifier = this._optionsService.options.fastScrollModifier;
+    // Multiply the scroll speed when the modifier is down
+    if ((modifier === 'alt' && ev.altKey) ||
+        (modifier === 'ctrl' && ev.ctrlKey) ||
+        (modifier === 'shift' && ev.shiftKey)) {
+      return amount * this._optionsService.options.fastScrollSensitivity * this._optionsService.options.scrollSensitivity;
+    }
+
+    return amount * this._optionsService.options.scrollSensitivity;
+  }
+
+  /**
+   * Handles the touchstart event, recording the touch occurred.
+   * @param ev The touch event.
+   */
+  public onTouchStart(ev: TouchEvent): void {
+    this._lastTouchY = ev.touches[0].pageY;
+  }
+
+  /**
+   * Handles the touchmove event, scrolling the viewport if the position shifted.
+   * @param ev The touch event.
+   */
+  public onTouchMove(ev: TouchEvent): boolean {
+    const deltaY = this._lastTouchY - ev.touches[0].pageY;
+    this._lastTouchY = ev.touches[0].pageY;
+    if (deltaY === 0) {
+      return false;
+    }
+    this._viewportElement.scrollTop += deltaY;
+    return this._bubbleScroll(ev, deltaY);
+  }
+}
diff --git a/node_modules/xterm/src/browser/input/CompositionHelper.ts b/node_modules/xterm/src/browser/input/CompositionHelper.ts
new file mode 100644 (file)
index 0000000..e6994ea
--- /dev/null
@@ -0,0 +1,229 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharSizeService } from 'browser/services/Services';
+import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';
+
+interface IPosition {
+  start: number;
+  end: number;
+}
+
+/**
+ * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend
+ * events, displaying the in-progress composition to the UI and forwarding the final composition
+ * to the handler.
+ */
+export class CompositionHelper {
+  /**
+   * Whether input composition is currently happening, eg. via a mobile keyboard, speech input or
+   * IME. This variable determines whether the compositionText should be displayed on the UI.
+   */
+  private _isComposing: boolean;
+
+  /**
+   * The position within the input textarea's value of the current composition.
+   */
+  private _compositionPosition: IPosition;
+
+  /**
+   * Whether a composition is in the process of being sent, setting this to false will cancel any
+   * in-progress composition.
+   */
+  private _isSendingComposition: boolean;
+
+  constructor(
+    private readonly _textarea: HTMLTextAreaElement,
+    private readonly _compositionView: HTMLElement,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @IOptionsService private readonly _optionsService: IOptionsService,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService,
+    @ICoreService private readonly _coreService: ICoreService
+  ) {
+    this._isComposing = false;
+    this._isSendingComposition = false;
+    this._compositionPosition = { start: 0, end: 0 };
+  }
+
+  /**
+   * Handles the compositionstart event, activating the composition view.
+   */
+  public compositionstart(): void {
+    this._isComposing = true;
+    this._compositionPosition.start = this._textarea.value.length;
+    this._compositionView.textContent = '';
+    this._compositionView.classList.add('active');
+  }
+
+  /**
+   * Handles the compositionupdate event, updating the composition view.
+   * @param ev The event.
+   */
+  public compositionupdate(ev: CompositionEvent): void {
+    this._compositionView.textContent = ev.data;
+    this.updateCompositionElements();
+    setTimeout(() => {
+      this._compositionPosition.end = this._textarea.value.length;
+    }, 0);
+  }
+
+  /**
+   * Handles the compositionend event, hiding the composition view and sending the composition to
+   * the handler.
+   */
+  public compositionend(): void {
+    this._finalizeComposition(true);
+  }
+
+  /**
+   * Handles the keydown event, routing any necessary events to the CompositionHelper functions.
+   * @param ev The keydown event.
+   * @return Whether the Terminal should continue processing the keydown event.
+   */
+  public keydown(ev: KeyboardEvent): boolean {
+    if (this._isComposing || this._isSendingComposition) {
+      if (ev.keyCode === 229) {
+        // Continue composing if the keyCode is the "composition character"
+        return false;
+      } else if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {
+        // Continue composing if the keyCode is a modifier key
+        return false;
+      }
+      // Finish composition immediately. This is mainly here for the case where enter is
+      // pressed and the handler needs to be triggered before the command is executed.
+      this._finalizeComposition(false);
+    }
+
+    if (ev.keyCode === 229) {
+      // If the "composition character" is used but gets to this point it means a non-composition
+      // character (eg. numbers and punctuation) was pressed when the IME was active.
+      this._handleAnyTextareaChanges();
+      return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Finalizes the composition, resuming regular input actions. This is called when a composition
+   * is ending.
+   * @param waitForPropagation Whether to wait for events to propagate before sending
+   *   the input. This should be false if a non-composition keystroke is entered before the
+   *   compositionend event is triggered, such as enter, so that the composition is sent before
+   *   the command is executed.
+   */
+  private _finalizeComposition(waitForPropagation: boolean): void {
+    this._compositionView.classList.remove('active');
+    this._isComposing = false;
+    this._clearTextareaPosition();
+
+    if (!waitForPropagation) {
+      // Cancel any delayed composition send requests and send the input immediately.
+      this._isSendingComposition = false;
+      const input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);
+      this._coreService.triggerDataEvent(input, true);
+    } else {
+      // Make a deep copy of the composition position here as a new compositionstart event may
+      // fire before the setTimeout executes.
+      const currentCompositionPosition = {
+        start: this._compositionPosition.start,
+        end: this._compositionPosition.end
+      };
+
+      // Since composition* events happen before the changes take place in the textarea on most
+      // browsers, use a setTimeout with 0ms time to allow the native compositionend event to
+      // complete. This ensures the correct character is retrieved.
+      // This solution was used because:
+      // - The compositionend event's data property is unreliable, at least on Chromium
+      // - The last compositionupdate event's data property does not always accurately describe
+      //   the character, a counter example being Korean where an ending consonsant can move to
+      //   the following character if the following input is a vowel.
+      this._isSendingComposition = true;
+      setTimeout(() => {
+        // Ensure that the input has not already been sent
+        if (this._isSendingComposition) {
+          this._isSendingComposition = false;
+          let input;
+          if (this._isComposing) {
+            // Use the end position to get the string if a new composition has started.
+            input = this._textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);
+          } else {
+            // Don't use the end position here in order to pick up any characters after the
+            // composition has finished, for example when typing a non-composition character
+            // (eg. 2) after a composition character.
+            input = this._textarea.value.substring(currentCompositionPosition.start);
+          }
+          this._coreService.triggerDataEvent(input, true);
+        }
+      }, 0);
+    }
+  }
+
+  /**
+   * Apply any changes made to the textarea after the current event chain is allowed to complete.
+   * This should be called when not currently composing but a keydown event with the "composition
+   * character" (229) is triggered, in order to allow non-composition text to be entered when an
+   * IME is active.
+   */
+  private _handleAnyTextareaChanges(): void {
+    const oldValue = this._textarea.value;
+    setTimeout(() => {
+      // Ignore if a composition has started since the timeout
+      if (!this._isComposing) {
+        const newValue = this._textarea.value;
+        const diff = newValue.replace(oldValue, '');
+        if (diff.length > 0) {
+          this._coreService.triggerDataEvent(diff, true);
+        }
+      }
+    }, 0);
+  }
+
+  /**
+   * Positions the composition view on top of the cursor and the textarea just below it (so the
+   * IME helper dialog is positioned correctly).
+   * @param dontRecurse Whether to use setTimeout to recursively trigger another update, this is
+   *   necessary as the IME events across browsers are not consistently triggered.
+   */
+  public updateCompositionElements(dontRecurse?: boolean): void {
+    if (!this._isComposing) {
+      return;
+    }
+
+    if (this._bufferService.buffer.isCursorInViewport) {
+      const cellHeight = Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);
+      const cursorTop = this._bufferService.buffer.y * cellHeight;
+      const cursorLeft = this._bufferService.buffer.x * this._charSizeService.width;
+
+      this._compositionView.style.left = cursorLeft + 'px';
+      this._compositionView.style.top = cursorTop + 'px';
+      this._compositionView.style.height = cellHeight + 'px';
+      this._compositionView.style.lineHeight = cellHeight + 'px';
+      this._compositionView.style.fontFamily = this._optionsService.options.fontFamily;
+      this._compositionView.style.fontSize = this._optionsService.options.fontSize + 'px';
+      // Sync the textarea to the exact position of the composition view so the IME knows where the
+      // text is.
+      const compositionViewBounds = this._compositionView.getBoundingClientRect();
+      this._textarea.style.left = cursorLeft + 'px';
+      this._textarea.style.top = cursorTop + 'px';
+      this._textarea.style.width = compositionViewBounds.width + 'px';
+      this._textarea.style.height = compositionViewBounds.height + 'px';
+      this._textarea.style.lineHeight = compositionViewBounds.height + 'px';
+    }
+
+    if (!dontRecurse) {
+      setTimeout(() => this.updateCompositionElements(true), 0);
+    }
+  }
+
+  /**
+   * Clears the textarea's position so that the cursor does not blink on IE.
+   * @private
+   */
+  private _clearTextareaPosition(): void {
+    this._textarea.style.left = '';
+    this._textarea.style.top = '';
+  }
+}
diff --git a/node_modules/xterm/src/browser/input/Mouse.ts b/node_modules/xterm/src/browser/input/Mouse.ts
new file mode 100644 (file)
index 0000000..2986fb3
--- /dev/null
@@ -0,0 +1,58 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export function getCoordsRelativeToElement(event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] {
+  const rect = element.getBoundingClientRect();
+  return [event.clientX - rect.left, event.clientY - rect.top];
+}
+
+/**
+ * Gets coordinates within the terminal for a particular mouse event. The result
+ * is returned as an array in the form [x, y] instead of an object as it's a
+ * little faster and this function is used in some low level code.
+ * @param event The mouse event.
+ * @param element The terminal's container element.
+ * @param colCount The number of columns in the terminal.
+ * @param rowCount The number of rows n the terminal.
+ * @param isSelection Whether the request is for the selection or not. This will
+ * apply an offset to the x value such that the left half of the cell will
+ * select that cell and the right half will select the next cell.
+ */
+export function getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, actualCellWidth: number, actualCellHeight: number, isSelection?: boolean): [number, number] | undefined {
+  // Coordinates cannot be measured if there are no valid
+  if (!hasValidCharSize) {
+    return undefined;
+  }
+
+  const coords = getCoordsRelativeToElement(event, element);
+  if (!coords) {
+    return undefined;
+  }
+
+  coords[0] = Math.ceil((coords[0] + (isSelection ? actualCellWidth / 2 : 0)) / actualCellWidth);
+  coords[1] = Math.ceil(coords[1] / actualCellHeight);
+
+  // Ensure coordinates are within the terminal viewport. Note that selections
+  // need an addition point of precision to cover the end point (as characters
+  // cover half of one char and half of the next).
+  coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));
+  coords[1] = Math.min(Math.max(coords[1], 1), rowCount);
+
+  return coords;
+}
+
+/**
+ * Gets coordinates within the terminal for a particular mouse event, wrapping
+ * them to the bounds of the terminal and adding 32 to both the x and y values
+ * as expected by xterm.
+ */
+export function getRawByteCoords(coords: [number, number] | undefined): { x: number, y: number } | undefined {
+  if (!coords) {
+    return undefined;
+  }
+
+  // xterm sends raw bytes and starts at 32 (SP) for each.
+  return { x: coords[0] + 32, y: coords[1] + 32 };
+}
diff --git a/node_modules/xterm/src/browser/input/MoveToCell.ts b/node_modules/xterm/src/browser/input/MoveToCell.ts
new file mode 100644 (file)
index 0000000..406ec80
--- /dev/null
@@ -0,0 +1,230 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { C0 } from 'common/data/EscapeSequences';
+import { IBufferService } from 'common/services/Services';
+
+const enum Direction {
+  UP = 'A',
+  DOWN = 'B',
+  RIGHT = 'C',
+  LEFT = 'D'
+}
+
+/**
+ * Concatenates all the arrow sequences together.
+ * Resets the starting row to an unwrapped row, moves to the requested row,
+ * then moves to requested col.
+ */
+export function moveToCellSequence(targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  const startX = bufferService.buffer.x;
+  const startY = bufferService.buffer.y;
+
+  // The alt buffer should try to navigate between rows
+  if (!bufferService.buffer.hasScrollback) {
+    return resetStartingRow(startX, startY, targetX, targetY, bufferService, applicationCursor) +
+      moveToRequestedRow(startY, targetY, bufferService, applicationCursor) +
+      moveToRequestedCol(startX, startY, targetX, targetY, bufferService, applicationCursor);
+  }
+
+  // Only move horizontally for the normal buffer
+  return moveHorizontallyOnly(startX, startY, targetX, targetY, bufferService, applicationCursor);
+}
+
+/**
+ * If the initial position of the cursor is on a row that is wrapped, move the
+ * cursor up to the first row that is not wrapped to have accurate vertical
+ * positioning.
+ */
+function resetStartingRow(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length === 0) {
+    return '';
+  }
+  return repeat(bufferLine(
+    startX, startY, startX,
+    startY - wrappedRowsForRow(bufferService, startY), false, bufferService
+  ).length, sequence(Direction.LEFT, applicationCursor));
+}
+
+/**
+ * Using the reset starting and ending row, move to the requested row,
+ * ignoring wrapped rows
+ */
+function moveToRequestedRow(startY: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  const startRow = startY - wrappedRowsForRow(bufferService, startY);
+  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);
+
+  const rowsToMove = Math.abs(startRow - endRow) - wrappedRowsCount(startY, targetY, bufferService);
+
+  return repeat(rowsToMove, sequence(verticalDirection(startY, targetY), applicationCursor));
+}
+
+/**
+ * Move to the requested col on the ending row
+ */
+function moveToRequestedCol(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  let startRow;
+  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length > 0) {
+    startRow = targetY - wrappedRowsForRow(bufferService, targetY);
+  } else {
+    startRow = startY;
+  }
+
+  const endRow = targetY;
+  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);
+
+  return repeat(bufferLine(
+    startX, startRow, targetX, endRow,
+    direction === Direction.RIGHT, bufferService
+  ).length, sequence(direction, applicationCursor));
+}
+
+function moveHorizontallyOnly(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);
+  return repeat(Math.abs(startX - targetX), sequence(direction, applicationCursor));
+}
+
+/**
+ * Utility functions
+ */
+
+/**
+ * Calculates the number of wrapped rows between the unwrapped starting and
+ * ending rows. These rows need to ignored since the cursor skips over them.
+ */
+function wrappedRowsCount(startY: number, targetY: number, bufferService: IBufferService): number {
+  let wrappedRows = 0;
+  const startRow = startY - wrappedRowsForRow(bufferService, startY);
+  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);
+
+  for (let i = 0; i < Math.abs(startRow - endRow); i++) {
+    const direction = verticalDirection(startY, targetY) === Direction.UP ? -1 : 1;
+    const line = bufferService.buffer.lines.get(startRow + (direction * i));
+    if (line && line.isWrapped) {
+      wrappedRows++;
+    }
+  }
+
+  return wrappedRows;
+}
+
+/**
+ * Calculates the number of wrapped rows that make up a given row.
+ * @param currentRow The row to determine how many wrapped rows make it up
+ */
+function wrappedRowsForRow(bufferService: IBufferService, currentRow: number): number {
+  let rowCount = 0;
+  let line = bufferService.buffer.lines.get(currentRow);
+  let lineWraps = line && line.isWrapped;
+
+  while (lineWraps && currentRow >= 0 && currentRow < bufferService.rows) {
+    rowCount++;
+    line = bufferService.buffer.lines.get(--currentRow);
+    lineWraps = line && line.isWrapped;
+  }
+
+  return rowCount;
+}
+
+/**
+ * Direction determiners
+ */
+
+/**
+ * Determines if the right or left arrow is needed
+ */
+function horizontalDirection(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): Direction {
+  let startRow;
+  if (moveToRequestedRow(targetX, targetY, bufferService, applicationCursor).length > 0) {
+    startRow = targetY - wrappedRowsForRow(bufferService, targetY);
+  } else {
+    startRow = startY;
+  }
+
+  if ((startX < targetX &&
+    startRow <= targetY) || // down/right or same y/right
+    (startX >= targetX &&
+    startRow < targetY)) {  // down/left or same y/left
+    return Direction.RIGHT;
+  }
+  return Direction.LEFT;
+}
+
+/**
+ * Determines if the up or down arrow is needed
+ */
+function verticalDirection(startY: number, targetY: number): Direction {
+  return startY > targetY ? Direction.UP : Direction.DOWN;
+}
+
+/**
+ * Constructs the string of chars in the buffer from a starting row and col
+ * to an ending row and col
+ * @param startCol The starting column position
+ * @param startRow The starting row position
+ * @param endCol The ending column position
+ * @param endRow The ending row position
+ * @param forward Direction to move
+ */
+function bufferLine(
+  startCol: number,
+  startRow: number,
+  endCol: number,
+  endRow: number,
+  forward: boolean,
+  bufferService: IBufferService
+): string {
+  let currentCol = startCol;
+  let currentRow = startRow;
+  let bufferStr = '';
+
+  while (currentCol !== endCol || currentRow !== endRow) {
+    currentCol += forward ? 1 : -1;
+
+    if (forward && currentCol > bufferService.cols - 1) {
+      bufferStr += bufferService.buffer.translateBufferLineToString(
+        currentRow, false, startCol, currentCol
+      );
+      currentCol = 0;
+      startCol = 0;
+      currentRow++;
+    } else if (!forward && currentCol < 0) {
+      bufferStr += bufferService.buffer.translateBufferLineToString(
+        currentRow, false, 0, startCol + 1
+      );
+      currentCol = bufferService.cols - 1;
+      startCol = currentCol;
+      currentRow--;
+    }
+  }
+
+  return bufferStr + bufferService.buffer.translateBufferLineToString(
+    currentRow, false, startCol, currentCol
+  );
+}
+
+/**
+ * Constructs the escape sequence for clicking an arrow
+ * @param direction The direction to move
+ */
+function sequence(direction: Direction, applicationCursor: boolean): string {
+  const mod =  applicationCursor ? 'O' : '[';
+  return C0.ESC + mod + direction;
+}
+
+/**
+ * Returns a string repeated a given number of times
+ * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
+ * @param count The number of times to repeat the string
+ * @param string The string that is to be repeated
+ */
+function repeat(count: number, str: string): string {
+  count = Math.floor(count);
+  let rpt = '';
+  for (let i = 0; i < count; i++) {
+    rpt += str;
+  }
+  return rpt;
+}
diff --git a/node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts b/node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts
new file mode 100644 (file)
index 0000000..e9ad5b3
--- /dev/null
@@ -0,0 +1,385 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions, IRenderLayer } from 'browser/renderer/Types';
+import { ICellData } from 'common/Types';
+import { DEFAULT_COLOR, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';
+import { IGlyphIdentifier } from 'browser/renderer/atlas/Types';
+import { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';
+import { acquireCharAtlas } from 'browser/renderer/atlas/CharAtlasCache';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { IColorSet } from 'browser/Types';
+import { CellData } from 'common/buffer/CellData';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+import { throwIfFalsy } from 'browser/renderer/RendererUtils';
+
+export abstract class BaseRenderLayer implements IRenderLayer {
+  private _canvas: HTMLCanvasElement;
+  protected _ctx!: CanvasRenderingContext2D;
+  private _scaledCharWidth: number = 0;
+  private _scaledCharHeight: number = 0;
+  private _scaledCellWidth: number = 0;
+  private _scaledCellHeight: number = 0;
+  private _scaledCharLeft: number = 0;
+  private _scaledCharTop: number = 0;
+
+  protected _charAtlas: BaseCharAtlas | undefined;
+
+  /**
+   * An object that's reused when drawing glyphs in order to reduce GC.
+   */
+  private _currentGlyphIdentifier: IGlyphIdentifier = {
+    chars: '',
+    code: 0,
+    bg: 0,
+    fg: 0,
+    bold: false,
+    dim: false,
+    italic: false
+  };
+
+  constructor(
+    private _container: HTMLElement,
+    id: string,
+    zIndex: number,
+    private _alpha: boolean,
+    protected _colors: IColorSet,
+    private _rendererId: number,
+    protected readonly _bufferService: IBufferService,
+    protected readonly _optionsService: IOptionsService
+  ) {
+    this._canvas = document.createElement('canvas');
+    this._canvas.classList.add(`xterm-${id}-layer`);
+    this._canvas.style.zIndex = zIndex.toString();
+    this._initCanvas();
+    this._container.appendChild(this._canvas);
+  }
+
+  public dispose(): void {
+    this._container.removeChild(this._canvas);
+    if (this._charAtlas) {
+      this._charAtlas.dispose();
+    }
+  }
+
+  private _initCanvas(): void {
+    this._ctx = throwIfFalsy(this._canvas.getContext('2d', {alpha: this._alpha}));
+    // Draw the background if this is an opaque layer
+    if (!this._alpha) {
+      this._clearAll();
+    }
+  }
+
+  public onOptionsChanged(): void {}
+  public onBlur(): void {}
+  public onFocus(): void {}
+  public onCursorMove(): void {}
+  public onGridChanged(startRow: number, endRow: number): void {}
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {}
+
+  public setColors(colorSet: IColorSet): void {
+    this._refreshCharAtlas(colorSet);
+  }
+
+  protected _setTransparency(alpha: boolean): void {
+    // Do nothing when alpha doesn't change
+    if (alpha === this._alpha) {
+      return;
+    }
+
+    // Create new canvas and replace old one
+    const oldCanvas = this._canvas;
+    this._alpha = alpha;
+    // Cloning preserves properties
+    this._canvas = <HTMLCanvasElement>this._canvas.cloneNode();
+    this._initCanvas();
+    this._container.replaceChild(this._canvas, oldCanvas);
+
+    // Regenerate char atlas and force a full redraw
+    this._refreshCharAtlas(this._colors);
+    this.onGridChanged(0, this._bufferService.rows - 1);
+  }
+
+  /**
+   * Refreshes the char atlas, aquiring a new one if necessary.
+   * @param colorSet The color set to use for the char atlas.
+   */
+  private _refreshCharAtlas(colorSet: IColorSet): void {
+    if (this._scaledCharWidth <= 0 && this._scaledCharHeight <= 0) {
+      return;
+    }
+    this._charAtlas = acquireCharAtlas(this._optionsService.options, this._rendererId, colorSet, this._scaledCharWidth, this._scaledCharHeight);
+    this._charAtlas.warmUp();
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    this._scaledCellWidth = dim.scaledCellWidth;
+    this._scaledCellHeight = dim.scaledCellHeight;
+    this._scaledCharWidth = dim.scaledCharWidth;
+    this._scaledCharHeight = dim.scaledCharHeight;
+    this._scaledCharLeft = dim.scaledCharLeft;
+    this._scaledCharTop = dim.scaledCharTop;
+    this._canvas.width = dim.scaledCanvasWidth;
+    this._canvas.height = dim.scaledCanvasHeight;
+    this._canvas.style.width = `${dim.canvasWidth}px`;
+    this._canvas.style.height = `${dim.canvasHeight}px`;
+
+    // Draw the background if this is an opaque layer
+    if (!this._alpha) {
+      this._clearAll();
+    }
+
+    this._refreshCharAtlas(this._colors);
+  }
+
+  public abstract reset(): void;
+
+  /**
+   * Fills 1+ cells completely. This uses the existing fillStyle on the context.
+   * @param x The column to start at.
+   * @param y The row to start at
+   * @param width The number of columns to fill.
+   * @param height The number of rows to fill.
+   */
+  protected _fillCells(x: number, y: number, width: number, height: number): void {
+    this._ctx.fillRect(
+        x * this._scaledCellWidth,
+        y * this._scaledCellHeight,
+        width * this._scaledCellWidth,
+        height * this._scaledCellHeight);
+  }
+
+  /**
+   * Fills a 1px line (2px on HDPI) at the bottom of the cell. This uses the
+   * existing fillStyle on the context.
+   * @param x The column to fill.
+   * @param y The row to fill.
+   */
+  protected _fillBottomLineAtCells(x: number, y: number, width: number = 1): void {
+    this._ctx.fillRect(
+        x * this._scaledCellWidth,
+        (y + 1) * this._scaledCellHeight - window.devicePixelRatio - 1 /* Ensure it's drawn within the cell */,
+        width * this._scaledCellWidth,
+        window.devicePixelRatio);
+  }
+
+  /**
+   * Fills a 1px line (2px on HDPI) at the left of the cell. This uses the
+   * existing fillStyle on the context.
+   * @param x The column to fill.
+   * @param y The row to fill.
+   */
+  protected _fillLeftLineAtCell(x: number, y: number): void {
+    this._ctx.fillRect(
+        x * this._scaledCellWidth,
+        y * this._scaledCellHeight,
+        window.devicePixelRatio,
+        this._scaledCellHeight);
+  }
+
+  /**
+   * Strokes a 1px rectangle (2px on HDPI) around a cell. This uses the existing
+   * strokeStyle on the context.
+   * @param x The column to fill.
+   * @param y The row to fill.
+   */
+  protected _strokeRectAtCell(x: number, y: number, width: number, height: number): void {
+    this._ctx.lineWidth = window.devicePixelRatio;
+    this._ctx.strokeRect(
+        x * this._scaledCellWidth + window.devicePixelRatio / 2,
+        y * this._scaledCellHeight + (window.devicePixelRatio / 2),
+        width * this._scaledCellWidth - window.devicePixelRatio,
+        (height * this._scaledCellHeight) - window.devicePixelRatio);
+  }
+
+  /**
+   * Clears the entire canvas.
+   */
+  protected _clearAll(): void {
+    if (this._alpha) {
+      this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
+    } else {
+      this._ctx.fillStyle = this._colors.background.css;
+      this._ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);
+    }
+  }
+
+  /**
+   * Clears 1+ cells completely.
+   * @param x The column to start at.
+   * @param y The row to start at.
+   * @param width The number of columns to clear.
+   * @param height The number of rows to clear.
+   */
+  protected _clearCells(x: number, y: number, width: number, height: number): void {
+    if (this._alpha) {
+      this._ctx.clearRect(
+          x * this._scaledCellWidth,
+          y * this._scaledCellHeight,
+          width * this._scaledCellWidth,
+          height * this._scaledCellHeight);
+    } else {
+      this._ctx.fillStyle = this._colors.background.css;
+      this._ctx.fillRect(
+          x * this._scaledCellWidth,
+          y * this._scaledCellHeight,
+          width * this._scaledCellWidth,
+          height * this._scaledCellHeight);
+    }
+  }
+
+  /**
+   * Draws a truecolor character at the cell. The character will be clipped to
+   * ensure that it fits with the cell, including the cell to the right if it's
+   * a wide character. This uses the existing fillStyle on the context.
+   * @param cell The cell data for the character to draw.
+   * @param x The column to draw at.
+   * @param y The row to draw at.
+   * @param color The color of the character.
+   */
+  protected _fillCharTrueColor(cell: CellData, x: number, y: number): void {
+    this._ctx.font = this._getFont(false, false);
+    this._ctx.textBaseline = 'middle';
+    this._clipRow(y);
+    this._ctx.fillText(
+        cell.getChars(),
+        x * this._scaledCellWidth + this._scaledCharLeft,
+        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);
+  }
+
+  /**
+   * Draws one or more characters at a cell. If possible this will draw using
+   * the character atlas to reduce draw time.
+   * @param chars The character or characters.
+   * @param code The character code.
+   * @param width The width of the characters.
+   * @param x The column to draw at.
+   * @param y The row to draw at.
+   * @param fg The foreground color, in the format stored within the attributes.
+   * @param bg The background color, in the format stored within the attributes.
+   * This is used to validate whether a cached image can be used.
+   * @param bold Whether the text is bold.
+   */
+  protected _drawChars(cell: ICellData, x: number, y: number): void {
+
+    // skip cache right away if we draw in RGB
+    // Note: to avoid bad runtime JoinedCellData will be skipped
+    //       in the cache handler itself (atlasDidDraw == false) and
+    //       fall through to uncached later down below
+    if (cell.isFgRGB() || cell.isBgRGB()) {
+      this._drawUncachedChars(cell, x, y);
+      return;
+    }
+
+    let fg;
+    let bg;
+    if (cell.isInverse()) {
+      fg = (cell.isBgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getBgColor();
+      bg = (cell.isFgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getFgColor();
+    } else {
+      bg = (cell.isBgDefault()) ? DEFAULT_COLOR : cell.getBgColor();
+      fg = (cell.isFgDefault()) ? DEFAULT_COLOR : cell.getFgColor();
+    }
+
+    const drawInBrightColor = this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8 && fg !== INVERTED_DEFAULT_COLOR;
+
+    fg += drawInBrightColor ? 8 : 0;
+    this._currentGlyphIdentifier.chars = cell.getChars() || WHITESPACE_CELL_CHAR;
+    this._currentGlyphIdentifier.code = cell.getCode() || WHITESPACE_CELL_CODE;
+    this._currentGlyphIdentifier.bg = bg;
+    this._currentGlyphIdentifier.fg = fg;
+    this._currentGlyphIdentifier.bold = !!cell.isBold();
+    this._currentGlyphIdentifier.dim = !!cell.isDim();
+    this._currentGlyphIdentifier.italic = !!cell.isItalic();
+    const atlasDidDraw = this._charAtlas && this._charAtlas.draw(
+      this._ctx,
+      this._currentGlyphIdentifier,
+      x * this._scaledCellWidth + this._scaledCharLeft,
+      y * this._scaledCellHeight + this._scaledCharTop
+    );
+
+    if (!atlasDidDraw) {
+      this._drawUncachedChars(cell, x, y);
+    }
+  }
+
+  /**
+   * Draws one or more characters at one or more cells. The character(s) will be
+   * clipped to ensure that they fit with the cell(s), including the cell to the
+   * right if the last character is a wide character.
+   * @param chars The character.
+   * @param width The width of the character.
+   * @param fg The foreground color, in the format stored within the attributes.
+   * @param x The column to draw at.
+   * @param y The row to draw at.
+   */
+  private _drawUncachedChars(cell: ICellData, x: number, y: number): void {
+    this._ctx.save();
+    this._ctx.font = this._getFont(!!cell.isBold(), !!cell.isItalic());
+    this._ctx.textBaseline = 'middle';
+
+    if (cell.isInverse()) {
+      if (cell.isBgDefault()) {
+        this._ctx.fillStyle = this._colors.background.css;
+      } else if (cell.isBgRGB()) {
+        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;
+      } else {
+        this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;
+      }
+    } else {
+      if (cell.isFgDefault()) {
+        this._ctx.fillStyle = this._colors.foreground.css;
+      } else if (cell.isFgRGB()) {
+        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;
+      } else {
+        let fg = cell.getFgColor();
+        if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {
+          fg += 8;
+        }
+        this._ctx.fillStyle = this._colors.ansi[fg].css;
+      }
+    }
+
+    this._clipRow(y);
+
+    // Apply alpha to dim the character
+    if (cell.isDim()) {
+      this._ctx.globalAlpha = DIM_OPACITY;
+    }
+    // Draw the character
+    this._ctx.fillText(
+        cell.getChars(),
+        x * this._scaledCellWidth + this._scaledCharLeft,
+        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);
+    this._ctx.restore();
+  }
+
+  /**
+   * Clips a row to ensure no pixels will be drawn outside the cells in the row.
+   * @param y The row to clip.
+   */
+  private _clipRow(y: number): void {
+    this._ctx.beginPath();
+    this._ctx.rect(
+        0,
+        y * this._scaledCellHeight,
+        this._bufferService.cols * this._scaledCellWidth,
+        this._scaledCellHeight);
+    this._ctx.clip();
+  }
+
+  /**
+   * Gets the current font.
+   * @param isBold If we should use the bold fontWeight.
+   */
+  protected _getFont(isBold: boolean, isItalic: boolean): string {
+    const fontWeight = isBold ? this._optionsService.options.fontWeightBold : this._optionsService.options.fontWeight;
+    const fontStyle = isItalic ? 'italic' : '';
+
+    return `${fontStyle} ${fontWeight} ${this._optionsService.options.fontSize * window.devicePixelRatio}px ${this._optionsService.options.fontFamily}`;
+  }
+}
+
diff --git a/node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts b/node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts
new file mode 100644 (file)
index 0000000..5385b76
--- /dev/null
@@ -0,0 +1,326 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferLine, ICellData, CharData } from 'common/Types';
+import { ICharacterJoinerRegistry, ICharacterJoiner } from 'browser/renderer/Types';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { IBufferService } from 'common/services/Services';
+
+export class JoinedCellData extends AttributeData implements ICellData {
+  private _width: number;
+  // .content carries no meaning for joined CellData, simply nullify it
+  // thus we have to overload all other .content accessors
+  public content: number = 0;
+  public fg: number;
+  public bg: number;
+  public combinedData: string = '';
+
+  constructor(firstCell: ICellData, chars: string, width: number) {
+    super();
+    this.fg = firstCell.fg;
+    this.bg = firstCell.bg;
+    this.combinedData = chars;
+    this._width = width;
+  }
+
+  public isCombined(): number {
+    // always mark joined cell data as combined
+    return Content.IS_COMBINED_MASK;
+  }
+
+  public getWidth(): number {
+    return this._width;
+  }
+
+  public getChars(): string {
+    return this.combinedData;
+  }
+
+  public getCode(): number {
+    // code always gets the highest possible fake codepoint (read as -1)
+    // this is needed as code is used by caches as identifier
+    return 0x1FFFFF;
+  }
+
+  public setFromCharData(value: CharData): void {
+    throw new Error('not implemented');
+  }
+
+  public getAsCharData(): CharData {
+    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
+  }
+}
+
+export class CharacterJoinerRegistry implements ICharacterJoinerRegistry {
+
+  private _characterJoiners: ICharacterJoiner[] = [];
+  private _nextCharacterJoinerId: number = 0;
+  private _workCell: CellData = new CellData();
+
+  constructor(private _bufferService: IBufferService) { }
+
+  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {
+    const joiner: ICharacterJoiner = {
+      id: this._nextCharacterJoinerId++,
+      handler
+    };
+
+    this._characterJoiners.push(joiner);
+    return joiner.id;
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): boolean {
+    for (let i = 0; i < this._characterJoiners.length; i++) {
+      if (this._characterJoiners[i].id === joinerId) {
+        this._characterJoiners.splice(i, 1);
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  public getJoinedCharacters(row: number): [number, number][] {
+    if (this._characterJoiners.length === 0) {
+      return [];
+    }
+
+    const line = this._bufferService.buffer.lines.get(row);
+    if (!line || line.length === 0) {
+      return [];
+    }
+
+    const ranges: [number, number][] = [];
+    const lineStr = line.translateToString(true);
+
+    // Because some cells can be represented by multiple javascript characters,
+    // we track the cell and the string indexes separately. This allows us to
+    // translate the string ranges we get from the joiners back into cell ranges
+    // for use when rendering
+    let rangeStartColumn = 0;
+    let currentStringIndex = 0;
+    let rangeStartStringIndex = 0;
+    let rangeAttrFG = line.getFg(0);
+    let rangeAttrBG = line.getBg(0);
+
+    for (let x = 0; x < line.getTrimmedLength(); x++) {
+      line.loadCell(x, this._workCell);
+
+      if (this._workCell.getWidth() === 0) {
+        // If this character is of width 0, skip it.
+        continue;
+      }
+
+      // End of range
+      if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) {
+        // If we ended up with a sequence of more than one character,
+        // look for ranges to join.
+        if (x - rangeStartColumn > 1) {
+          const joinedRanges = this._getJoinedRanges(
+            lineStr,
+            rangeStartStringIndex,
+            currentStringIndex,
+            line,
+            rangeStartColumn
+          );
+          for (let i = 0; i < joinedRanges.length; i++) {
+            ranges.push(joinedRanges[i]);
+          }
+        }
+
+        // Reset our markers for a new range.
+        rangeStartColumn = x;
+        rangeStartStringIndex = currentStringIndex;
+        rangeAttrFG = this._workCell.fg;
+        rangeAttrBG = this._workCell.bg;
+      }
+
+      currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length;
+    }
+
+    // Process any trailing ranges.
+    if (this._bufferService.cols - rangeStartColumn > 1) {
+      const joinedRanges = this._getJoinedRanges(
+        lineStr,
+        rangeStartStringIndex,
+        currentStringIndex,
+        line,
+        rangeStartColumn
+      );
+      for (let i = 0; i < joinedRanges.length; i++) {
+        ranges.push(joinedRanges[i]);
+      }
+    }
+
+    return ranges;
+  }
+
+  /**
+   * Given a segment of a line of text, find all ranges of text that should be
+   * joined in a single rendering unit. Ranges are internally converted to
+   * column ranges, rather than string ranges.
+   * @param line String representation of the full line of text
+   * @param startIndex Start position of the range to search in the string (inclusive)
+   * @param endIndex End position of the range to search in the string (exclusive)
+   */
+  private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] {
+    const text = line.substring(startIndex, endIndex);
+    // At this point we already know that there is at least one joiner so
+    // we can just pull its value and assign it directly rather than
+    // merging it into an empty array, which incurs unnecessary writes.
+    const joinedRanges: [number, number][] = this._characterJoiners[0].handler(text);
+    for (let i = 1; i < this._characterJoiners.length; i++) {
+      // We merge any overlapping ranges across the different joiners
+      const joinerRanges = this._characterJoiners[i].handler(text);
+      for (let j = 0; j < joinerRanges.length; j++) {
+        CharacterJoinerRegistry._mergeRanges(joinedRanges, joinerRanges[j]);
+      }
+    }
+    this._stringRangesToCellRanges(joinedRanges, lineData, startCol);
+    return joinedRanges;
+  }
+
+  /**
+   * Modifies the provided ranges in-place to adjust for variations between
+   * string length and cell width so that the range represents a cell range,
+   * rather than the string range the joiner provides.
+   * @param ranges String ranges containing start (inclusive) and end (exclusive) index
+   * @param line Cell data for the relevant line in the terminal
+   * @param startCol Offset within the line to start from
+   */
+  private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void {
+    let currentRangeIndex = 0;
+    let currentRangeStarted = false;
+    let currentStringIndex = 0;
+    let currentRange = ranges[currentRangeIndex];
+
+    // If we got through all of the ranges, stop searching
+    if (!currentRange) {
+      return;
+    }
+
+    for (let x = startCol; x < this._bufferService.cols; x++) {
+      const width = line.getWidth(x);
+      const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length;
+
+      // We skip zero-width characters when creating the string to join the text
+      // so we do the same here
+      if (width === 0) {
+        continue;
+      }
+
+      // Adjust the start of the range
+      if (!currentRangeStarted && currentRange[0] <= currentStringIndex) {
+        currentRange[0] = x;
+        currentRangeStarted = true;
+      }
+
+      // Adjust the end of the range
+      if (currentRange[1] <= currentStringIndex) {
+        currentRange[1] = x;
+
+        // We're finished with this range, so we move to the next one
+        currentRange = ranges[++currentRangeIndex];
+
+        // If there are no more ranges left, stop searching
+        if (!currentRange) {
+          break;
+        }
+
+        // Ranges can be on adjacent characters. Because the end index of the
+        // ranges are exclusive, this means that the index for the start of a
+        // range can be the same as the end index of the previous range. To
+        // account for the start of the next range, we check here just in case.
+        if (currentRange[0] <= currentStringIndex) {
+          currentRange[0] = x;
+          currentRangeStarted = true;
+        } else {
+          currentRangeStarted = false;
+        }
+      }
+
+      // Adjust the string index based on the character length to line up with
+      // the column adjustment
+      currentStringIndex += length;
+    }
+
+    // If there is still a range left at the end, it must extend all the way to
+    // the end of the line.
+    if (currentRange) {
+      currentRange[1] = this._bufferService.cols;
+    }
+  }
+
+  /**
+   * Merges the range defined by the provided start and end into the list of
+   * existing ranges. The merge is done in place on the existing range for
+   * performance and is also returned.
+   * @param ranges Existing range list
+   * @param newRange Tuple of two numbers representing the new range to merge in.
+   * @returns The ranges input with the new range merged in place
+   */
+  private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] {
+    let inRange = false;
+    for (let i = 0; i < ranges.length; i++) {
+      const range = ranges[i];
+      if (!inRange) {
+        if (newRange[1] <= range[0]) {
+          // Case 1: New range is before the search range
+          ranges.splice(i, 0, newRange);
+          return ranges;
+        }
+
+        if (newRange[1] <= range[1]) {
+          // Case 2: New range is either wholly contained within the
+          // search range or overlaps with the front of it
+          range[0] = Math.min(newRange[0], range[0]);
+          return ranges;
+        }
+
+        if (newRange[0] < range[1]) {
+          // Case 3: New range either wholly contains the search range
+          // or overlaps with the end of it
+          range[0] = Math.min(newRange[0], range[0]);
+          inRange = true;
+        }
+
+        // Case 4: New range starts after the search range
+        continue;
+      } else {
+        if (newRange[1] <= range[0]) {
+          // Case 5: New range extends from previous range but doesn't
+          // reach the current one
+          ranges[i - 1][1] = newRange[1];
+          return ranges;
+        }
+
+        if (newRange[1] <= range[1]) {
+          // Case 6: New range extends from prvious range into the
+          // current range
+          ranges[i - 1][1] = Math.max(newRange[1], range[1]);
+          ranges.splice(i, 1);
+          return ranges;
+        }
+
+        // Case 7: New range extends from previous range past the
+        // end of the current range
+        ranges.splice(i, 1);
+        i--;
+      }
+    }
+
+    if (inRange) {
+      // Case 8: New range extends past the last existing range
+      ranges[ranges.length - 1][1] = newRange[1];
+    } else {
+      // Case 9: New range starts after the last existing range
+      ranges.push(newRange);
+    }
+
+    return ranges;
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/GridCache.ts b/node_modules/xterm/src/browser/renderer/GridCache.ts
new file mode 100644 (file)
index 0000000..b48798d
--- /dev/null
@@ -0,0 +1,33 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export class GridCache<T> {
+  public cache: (T | undefined)[][];
+
+  public constructor() {
+    this.cache = [];
+  }
+
+  public resize(width: number, height: number): void {
+    for (let x = 0; x < width; x++) {
+      if (this.cache.length <= x) {
+        this.cache.push([]);
+      }
+      for (let y = this.cache[x].length; y < height; y++) {
+        this.cache[x].push(undefined);
+      }
+      this.cache[x].length = height;
+    }
+    this.cache.length = width;
+  }
+
+  public clear(): void {
+    for (let x = 0; x < this.cache.length; x++) {
+      for (let y = 0; y < this.cache[x].length; y++) {
+        this.cache[x][y] = undefined;
+      }
+    }
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts b/node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts
new file mode 100644 (file)
index 0000000..a7be54e
--- /dev/null
@@ -0,0 +1,79 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions } from 'browser/renderer/Types';
+import { BaseRenderLayer } from './BaseRenderLayer';
+import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { is256Color } from 'browser/renderer/atlas/CharAtlasUtils';
+import { IColorSet, ILinkifierEvent, ILinkifier } from 'browser/Types';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+export class LinkRenderLayer extends BaseRenderLayer {
+  private _state: ILinkifierEvent | undefined;
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    rendererId: number,
+    linkifier: ILinkifier,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'link', zIndex, true, colors, rendererId, bufferService, optionsService);
+    linkifier.onLinkHover(e => this._onLinkHover(e));
+    linkifier.onLinkLeave(e => this._onLinkLeave(e));
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._state = undefined;
+  }
+
+  public reset(): void {
+    this._clearCurrentLink();
+  }
+
+  private _clearCurrentLink(): void {
+    if (this._state) {
+      this._clearCells(this._state.x1, this._state.y1, this._state.cols - this._state.x1, 1);
+      const middleRowCount = this._state.y2 - this._state.y1 - 1;
+      if (middleRowCount > 0) {
+        this._clearCells(0, this._state.y1 + 1, this._state.cols, middleRowCount);
+      }
+      this._clearCells(0, this._state.y2, this._state.x2, 1);
+      this._state = undefined;
+    }
+  }
+
+  private _onLinkHover(e: ILinkifierEvent): void {
+    if (e.fg === INVERTED_DEFAULT_COLOR) {
+      this._ctx.fillStyle = this._colors.background.css;
+    } else if (e.fg && is256Color(e.fg)) {
+      // 256 color support
+      this._ctx.fillStyle = this._colors.ansi[e.fg].css;
+    } else {
+      this._ctx.fillStyle = this._colors.foreground.css;
+    }
+
+    if (e.y1 === e.y2) {
+      // Single line link
+      this._fillBottomLineAtCells(e.x1, e.y1, e.x2 - e.x1);
+    } else {
+      // Multi-line link
+      this._fillBottomLineAtCells(e.x1, e.y1, e.cols - e.x1);
+      for (let y = e.y1 + 1; y < e.y2; y++) {
+        this._fillBottomLineAtCells(0, y, e.cols);
+      }
+      this._fillBottomLineAtCells(0, e.y2, e.x2);
+    }
+    this._state = e;
+  }
+
+  private _onLinkLeave(e: ILinkifierEvent): void {
+    this._clearCurrentLink();
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/RendererUtils.ts b/node_modules/xterm/src/browser/renderer/RendererUtils.ts
new file mode 100644 (file)
index 0000000..48fd26a
--- /dev/null
@@ -0,0 +1,11 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export function throwIfFalsy<T>(value: T | undefined | null): T {
+  if (!value) {
+    throw new Error('value must not be falsy');
+  }
+  return value;
+}
diff --git a/node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts b/node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts
new file mode 100644 (file)
index 0000000..5cd2fd9
--- /dev/null
@@ -0,0 +1,127 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions } from 'browser/renderer/Types';
+import { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';
+import { IColorSet } from 'browser/Types';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+interface ISelectionState {
+  start?: [number, number];
+  end?: [number, number];
+  columnSelectMode?: boolean;
+  ydisp?: number;
+}
+
+export class SelectionRenderLayer extends BaseRenderLayer {
+  private _state!: ISelectionState;
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    rendererId: number,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'selection', zIndex, true, colors, rendererId, bufferService, optionsService);
+    this._clearState();
+  }
+
+  private _clearState(): void {
+    this._state = {
+      start: undefined,
+      end: undefined,
+      columnSelectMode: undefined,
+      ydisp: undefined
+    };
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._clearState();
+  }
+
+  public reset(): void {
+    if (this._state.start && this._state.end) {
+      this._clearState();
+      this._clearAll();
+    }
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {
+    // Selection has not changed
+    if (!this._didStateChange(start, end, columnSelectMode, this._bufferService.buffer.ydisp)) {
+      return;
+    }
+
+    // Remove all selections
+    this._clearAll();
+
+    // Selection does not exist
+    if (!start || !end) {
+      this._clearState();
+      return;
+    }
+
+    // Translate from buffer position to viewport position
+    const viewportStartRow = start[1] - this._bufferService.buffer.ydisp;
+    const viewportEndRow = end[1] - this._bufferService.buffer.ydisp;
+    const viewportCappedStartRow = Math.max(viewportStartRow, 0);
+    const viewportCappedEndRow = Math.min(viewportEndRow, this._bufferService.rows - 1);
+
+    // No need to draw the selection
+    if (viewportCappedStartRow >= this._bufferService.rows || viewportCappedEndRow < 0) {
+      return;
+    }
+
+    this._ctx.fillStyle = this._colors.selection.css;
+
+    if (columnSelectMode) {
+      const startCol = start[0];
+      const width = end[0] - startCol;
+      const height = viewportCappedEndRow - viewportCappedStartRow + 1;
+      this._fillCells(startCol, viewportCappedStartRow, width, height);
+    } else {
+      // Draw first row
+      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;
+      const startRowEndCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;
+      this._fillCells(startCol, viewportCappedStartRow, startRowEndCol - startCol, 1);
+
+      // Draw middle rows
+      const middleRowsCount = Math.max(viewportCappedEndRow - viewportCappedStartRow - 1, 0);
+      this._fillCells(0, viewportCappedStartRow + 1, this._bufferService.cols, middleRowsCount);
+
+      // Draw final row
+      if (viewportCappedStartRow !== viewportCappedEndRow) {
+        // Only draw viewportEndRow if it's not the same as viewportStartRow
+        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;
+        this._fillCells(0, viewportCappedEndRow, endCol, 1);
+      }
+    }
+
+    // Save state for next render
+    this._state.start = [start[0], start[1]];
+    this._state.end = [end[0], end[1]];
+    this._state.columnSelectMode = columnSelectMode;
+    this._state.ydisp = this._bufferService.buffer.ydisp;
+  }
+
+  private _didStateChange(start: [number, number], end: [number, number], columnSelectMode: boolean, ydisp: number): boolean {
+    return !this._areCoordinatesEqual(start, this._state.start) ||
+      !this._areCoordinatesEqual(end, this._state.end) ||
+      columnSelectMode !== this._state.columnSelectMode ||
+      ydisp !== this._state.ydisp;
+  }
+
+  private _areCoordinatesEqual(coord1: [number, number] | undefined, coord2: [number, number] | undefined): boolean {
+    if (!coord1 || !coord2) {
+      return false;
+    }
+
+    return coord1[0] === coord2[0] && coord1[1] === coord2[1];
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/TextRenderLayer.ts b/node_modules/xterm/src/browser/renderer/TextRenderLayer.ts
new file mode 100644 (file)
index 0000000..330400c
--- /dev/null
@@ -0,0 +1,324 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharacterJoinerRegistry, IRenderDimensions } from 'browser/renderer/Types';
+import { CharData, ICellData } from 'common/Types';
+import { GridCache } from 'browser/renderer/GridCache';
+import { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { NULL_CELL_CODE, Content } from 'common/buffer/Constants';
+import { JoinedCellData } from 'browser/renderer/CharacterJoinerRegistry';
+import { IColorSet } from 'browser/Types';
+import { CellData } from 'common/buffer/CellData';
+import { IOptionsService, IBufferService } from 'common/services/Services';
+
+/**
+ * This CharData looks like a null character, which will forc a clear and render
+ * when the character changes (a regular space ' ' character may not as it's
+ * drawn state is a cleared cell).
+ */
+// const OVERLAP_OWNED_CHAR_DATA: CharData = [null, '', 0, -1];
+
+export class TextRenderLayer extends BaseRenderLayer {
+  private _state: GridCache<CharData>;
+  private _characterWidth: number = 0;
+  private _characterFont: string = '';
+  private _characterOverlapCache: { [key: string]: boolean } = {};
+  private _characterJoinerRegistry: ICharacterJoinerRegistry;
+  private _workCell = new CellData();
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    characterJoinerRegistry: ICharacterJoinerRegistry,
+    alpha: boolean,
+    rendererId: number,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'text', zIndex, alpha, colors, rendererId, bufferService, optionsService);
+    this._state = new GridCache<CharData>();
+    this._characterJoinerRegistry = characterJoinerRegistry;
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+
+    // Clear the character width cache if the font or width has changed
+    const terminalFont = this._getFont(false, false);
+    if (this._characterWidth !== dim.scaledCharWidth || this._characterFont !== terminalFont) {
+      this._characterWidth = dim.scaledCharWidth;
+      this._characterFont = terminalFont;
+      this._characterOverlapCache = {};
+    }
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._state.clear();
+    this._state.resize(this._bufferService.cols, this._bufferService.rows);
+  }
+
+  public reset(): void {
+    this._state.clear();
+    this._clearAll();
+  }
+
+  private _forEachCell(
+    firstRow: number,
+    lastRow: number,
+    joinerRegistry: ICharacterJoinerRegistry | null,
+    callback: (
+      cell: ICellData,
+      x: number,
+      y: number
+    ) => void
+  ): void {
+    for (let y = firstRow; y <= lastRow; y++) {
+      const row = y + this._bufferService.buffer.ydisp;
+      const line = this._bufferService.buffer.lines.get(row);
+      const joinedRanges = joinerRegistry ? joinerRegistry.getJoinedCharacters(row) : [];
+      for (let x = 0; x < this._bufferService.cols; x++) {
+        line!.loadCell(x, this._workCell);
+        let cell = this._workCell;
+
+        // If true, indicates that the current character(s) to draw were joined.
+        let isJoined = false;
+        let lastCharX = x;
+
+        // The character to the left is a wide character, drawing is owned by
+        // the char at x-1
+        if (cell.getWidth() === 0) {
+          continue;
+        }
+
+        // Process any joined character ranges as needed. Because of how the
+        // ranges are produced, we know that they are valid for the characters
+        // and attributes of our input.
+        if (joinedRanges.length > 0 && x === joinedRanges[0][0]) {
+          isJoined = true;
+          const range = joinedRanges.shift()!;
+
+          // We already know the exact start and end column of the joined range,
+          // so we get the string and width representing it directly
+
+          cell = new JoinedCellData(
+            this._workCell,
+            line!.translateToString(true, range[0], range[1]),
+            range[1] - range[0]
+          );
+
+          // Skip over the cells occupied by this range in the loop
+          lastCharX = range[1] - 1;
+        }
+
+        // If the character is an overlapping char and the character to the
+        // right is a space, take ownership of the cell to the right. We skip
+        // this check for joined characters because their rendering likely won't
+        // yield the same result as rendering the last character individually.
+        if (!isJoined && this._isOverlapping(cell)) {
+          // If the character is overlapping, we want to force a re-render on every
+          // frame. This is specifically to work around the case where two
+          // overlaping chars `a` and `b` are adjacent, the cursor is moved to b and a
+          // space is added. Without this, the first half of `b` would never
+          // get removed, and `a` would not re-render because it thinks it's
+          // already in the correct state.
+          // this._state.cache[x][y] = OVERLAP_OWNED_CHAR_DATA;
+          if (lastCharX < line!.length - 1 && line!.getCodePoint(lastCharX + 1) === NULL_CELL_CODE) {
+            // patch width to 2
+            cell.content &= ~Content.WIDTH_MASK;
+            cell.content |= 2 << Content.WIDTH_SHIFT;
+            // this._clearChar(x + 1, y);
+            // The overlapping char's char data will force a clear and render when the
+            // overlapping char is no longer to the left of the character and also when
+            // the space changes to another character.
+            // this._state.cache[x + 1][y] = OVERLAP_OWNED_CHAR_DATA;
+          }
+        }
+
+        callback(
+          cell,
+          x,
+          y
+        );
+
+        x = lastCharX;
+      }
+    }
+  }
+
+  /**
+   * Draws the background for a specified range of columns. Tries to batch adjacent cells of the
+   * same color together to reduce draw calls.
+   */
+  private _drawBackground(firstRow: number, lastRow: number): void {
+    const ctx = this._ctx;
+    const cols = this._bufferService.cols;
+    let startX: number = 0;
+    let startY: number = 0;
+    let prevFillStyle: string | null = null;
+
+    ctx.save();
+
+    this._forEachCell(firstRow, lastRow, null, (cell, x, y) => {
+      // libvte and xterm both draw the background (but not foreground) of invisible characters,
+      // so we should too.
+      let nextFillStyle = null; // null represents default background color
+
+      if (cell.isInverse()) {
+        if (cell.isFgDefault()) {
+          nextFillStyle = this._colors.foreground.css;
+        } else if (cell.isFgRGB()) {
+          nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;
+        } else {
+          nextFillStyle = this._colors.ansi[cell.getFgColor()].css;
+        }
+      } else if (cell.isBgRGB()) {
+        nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;
+      } else if (cell.isBgPalette()) {
+        nextFillStyle = this._colors.ansi[cell.getBgColor()].css;
+      }
+
+      if (prevFillStyle === null) {
+        // This is either the first iteration, or the default background was set. Either way, we
+        // don't need to draw anything.
+        startX = x;
+        startY = y;
+      }
+
+      if (y !== startY) {
+        // our row changed, draw the previous row
+        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';
+        this._fillCells(startX, startY, cols - startX, 1);
+        startX = x;
+        startY = y;
+      } else if (prevFillStyle !== nextFillStyle) {
+        // our color changed, draw the previous characters in this row
+        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';
+        this._fillCells(startX, startY, x - startX, 1);
+        startX = x;
+        startY = y;
+      }
+
+      prevFillStyle = nextFillStyle;
+    });
+
+    // flush the last color we encountered
+    if (prevFillStyle !== null) {
+      ctx.fillStyle = prevFillStyle;
+      this._fillCells(startX, startY, cols - startX, 1);
+    }
+
+    ctx.restore();
+  }
+
+  private _drawForeground(firstRow: number, lastRow: number): void {
+    this._forEachCell(firstRow, lastRow, this._characterJoinerRegistry, (cell, x, y) => {
+      if (cell.isInvisible()) {
+        return;
+      }
+      this._drawChars(cell, x, y);
+      if (cell.isUnderline()) {
+        this._ctx.save();
+
+        if (cell.isInverse()) {
+          if (cell.isBgDefault()) {
+            this._ctx.fillStyle = this._colors.background.css;
+          } else if (cell.isBgRGB()) {
+            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;
+          } else {
+            this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;
+          }
+        } else {
+          if (cell.isFgDefault()) {
+            this._ctx.fillStyle = this._colors.foreground.css;
+          } else if (cell.isFgRGB()) {
+            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;
+          } else {
+            let fg = cell.getFgColor();
+            if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {
+              fg += 8;
+            }
+            this._ctx.fillStyle = this._colors.ansi[fg].css;
+          }
+        }
+
+        this._fillBottomLineAtCells(x, y, cell.getWidth());
+        this._ctx.restore();
+      }
+    });
+  }
+
+  public onGridChanged(firstRow: number, lastRow: number): void {
+    // Resize has not been called yet
+    if (this._state.cache.length === 0) {
+      return;
+    }
+
+    if (this._charAtlas) {
+      this._charAtlas.beginFrame();
+    }
+
+    this._clearCells(0, firstRow, this._bufferService.cols, lastRow - firstRow + 1);
+    this._drawBackground(firstRow, lastRow);
+    this._drawForeground(firstRow, lastRow);
+  }
+
+  public onOptionsChanged(): void {
+    this._setTransparency(this._optionsService.options.allowTransparency);
+  }
+
+  /**
+   * Whether a character is overlapping to the next cell.
+   */
+  private _isOverlapping(cell: ICellData): boolean {
+    // Only single cell characters can be overlapping, rendering issues can
+    // occur without this check
+    if (cell.getWidth() !== 1) {
+      return false;
+    }
+
+    // We assume that any ascii character will not overlap
+    if (cell.getCode() < 256) {
+      return false;
+    }
+
+    const chars = cell.getChars();
+
+    // Deliver from cache if available
+    if (this._characterOverlapCache.hasOwnProperty(chars)) {
+      return this._characterOverlapCache[chars];
+    }
+
+    // Setup the font
+    this._ctx.save();
+    this._ctx.font = this._characterFont;
+
+    // Measure the width of the character, but Math.floor it
+    // because that is what the renderer does when it calculates
+    // the character dimensions we are comparing against
+    const overlaps = Math.floor(this._ctx.measureText(chars).width) > this._characterWidth;
+
+    // Restore the original context
+    this._ctx.restore();
+
+    // Cache and return
+    this._characterOverlapCache[chars] = overlaps;
+    return overlaps;
+  }
+
+  /**
+   * Clear the charcater at the cell specified.
+   * @param x The column of the char.
+   * @param y The row of the char.
+   */
+  // private _clearChar(x: number, y: number): void {
+  //   let colsToClear = 1;
+  //   // Clear the adjacent character if it was wide
+  //   const state = this._state.cache[x][y];
+  //   if (state && state[CHAR_DATA_WIDTH_INDEX] === 2) {
+  //     colsToClear = 2;
+  //   }
+  //   this.clearCells(x, y, colsToClear, 1);
+  // }
+}
diff --git a/node_modules/xterm/src/browser/renderer/Types.d.ts b/node_modules/xterm/src/browser/renderer/Types.d.ts
new file mode 100644 (file)
index 0000000..7f84dfd
--- /dev/null
@@ -0,0 +1,116 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+import { IColorSet } from 'browser/Types';
+
+export type CharacterJoinerHandler = (text: string) => [number, number][];
+
+export interface IRenderDimensions {
+  scaledCharWidth: number;
+  scaledCharHeight: number;
+  scaledCellWidth: number;
+  scaledCellHeight: number;
+  scaledCharLeft: number;
+  scaledCharTop: number;
+  scaledCanvasWidth: number;
+  scaledCanvasHeight: number;
+  canvasWidth: number;
+  canvasHeight: number;
+  actualCellWidth: number;
+  actualCellHeight: number;
+}
+
+/**
+ * Note that IRenderer implementations should emit the refresh event after
+ * rendering rows to the screen.
+ */
+export interface IRenderer extends IDisposable {
+  readonly dimensions: IRenderDimensions;
+
+  dispose(): void;
+  setColors(colors: IColorSet): void;
+  onDevicePixelRatioChange(): void;
+  onResize(cols: number, rows: number): void;
+  onCharSizeChanged(): void;
+  onBlur(): void;
+  onFocus(): void;
+  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;
+  onCursorMove(): void;
+  onOptionsChanged(): void;
+  clear(): void;
+  renderRows(start: number, end: number): void;
+  registerCharacterJoiner(handler: CharacterJoinerHandler): number;
+  deregisterCharacterJoiner(joinerId: number): boolean;
+}
+
+export interface ICharacterJoiner {
+  id: number;
+  handler: CharacterJoinerHandler;
+}
+
+export interface ICharacterJoinerRegistry {
+  registerCharacterJoiner(handler: (text: string) => [number, number][]): number;
+  deregisterCharacterJoiner(joinerId: number): boolean;
+  getJoinedCharacters(row: number): [number, number][];
+}
+
+export interface IRenderLayer extends IDisposable {
+  /**
+   * Called when the terminal loses focus.
+   */
+  onBlur(): void;
+
+  /**
+   * * Called when the terminal gets focus.
+   */
+  onFocus(): void;
+
+  /**
+   * Called when the cursor is moved.
+   */
+  onCursorMove(): void;
+
+  /**
+   * Called when options change.
+   */
+  onOptionsChanged(): void;
+
+  /**
+   * Called when the theme changes.
+   */
+  setColors(colorSet: IColorSet): void;
+
+  /**
+   * Called when the data in the grid has changed (or needs to be rendered
+   * again).
+   */
+  onGridChanged(startRow: number, endRow: number): void;
+
+  /**
+   * Calls when the selection changes.
+   */
+  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;
+
+  /**
+   * Registers a handler to join characters to render as a group
+   */
+  registerCharacterJoiner?(joiner: ICharacterJoiner): void;
+
+  /**
+   * Deregisters the specified character joiner handler
+   */
+  deregisterCharacterJoiner?(joinerId: number): void;
+
+  /**
+   * Resize the render layer.
+   */
+  resize(dim: IRenderDimensions): void;
+
+  /**
+   * Clear the state of the render layer.
+   */
+  reset(): void;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts b/node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts
new file mode 100644 (file)
index 0000000..dc11460
--- /dev/null
@@ -0,0 +1,56 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IGlyphIdentifier } from 'browser/renderer/atlas/Types';
+import { IDisposable } from 'common/Types';
+
+export abstract class BaseCharAtlas implements IDisposable {
+  private _didWarmUp: boolean = false;
+
+  public dispose(): void { }
+
+  /**
+   * Perform any work needed to warm the cache before it can be used. May be called multiple times.
+   * Implement _doWarmUp instead if you only want to get called once.
+   */
+  public warmUp(): void {
+    if (!this._didWarmUp) {
+      this._doWarmUp();
+      this._didWarmUp = true;
+    }
+  }
+
+  /**
+   * Perform any work needed to warm the cache before it can be used. Used by the default
+   * implementation of warmUp(), and will only be called once.
+   */
+  protected _doWarmUp(): void { }
+
+  /**
+   * Called when we start drawing a new frame.
+   *
+   * TODO: We rely on this getting called by TextRenderLayer. This should really be called by
+   * Renderer instead, but we need to make Renderer the source-of-truth for the char atlas, instead
+   * of BaseRenderLayer.
+   */
+  public beginFrame(): void { }
+
+  /**
+   * May be called before warmUp finishes, however it is okay for the implementation to
+   * do nothing and return false in that case.
+   *
+   * @param ctx Where to draw the character onto.
+   * @param glyph Information about what to draw
+   * @param x The position on the context to start drawing at
+   * @param y The position on the context to start drawing at
+   * @returns The success state. True if we drew the character.
+   */
+  public abstract draw(
+    ctx: CanvasRenderingContext2D,
+    glyph: IGlyphIdentifier,
+    x: number,
+    y: number
+  ): boolean;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts b/node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts
new file mode 100644 (file)
index 0000000..257835b
--- /dev/null
@@ -0,0 +1,95 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { generateConfig, configEquals } from 'browser/renderer/atlas/CharAtlasUtils';
+import { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';
+import { DynamicCharAtlas } from 'browser/renderer/atlas/DynamicCharAtlas';
+import { ICharAtlasConfig } from 'browser/renderer/atlas/Types';
+import { IColorSet } from 'browser/Types';
+import { ITerminalOptions } from 'common/services/Services';
+
+interface ICharAtlasCacheEntry {
+  atlas: BaseCharAtlas;
+  config: ICharAtlasConfig;
+  // N.B. This implementation potentially holds onto copies of the terminal forever, so
+  // this may cause memory leaks.
+  ownedBy: number[];
+}
+
+const charAtlasCache: ICharAtlasCacheEntry[] = [];
+
+/**
+ * Acquires a char atlas, either generating a new one or returning an existing
+ * one that is in use by another terminal.
+ */
+export function acquireCharAtlas(
+  options: ITerminalOptions,
+  rendererId: number,
+  colors: IColorSet,
+  scaledCharWidth: number,
+  scaledCharHeight: number
+): BaseCharAtlas {
+  const newConfig = generateConfig(scaledCharWidth, scaledCharHeight, options, colors);
+
+  // Check to see if the renderer already owns this config
+  for (let i = 0; i < charAtlasCache.length; i++) {
+    const entry = charAtlasCache[i];
+    const ownedByIndex = entry.ownedBy.indexOf(rendererId);
+    if (ownedByIndex >= 0) {
+      if (configEquals(entry.config, newConfig)) {
+        return entry.atlas;
+      }
+      // The configs differ, release the renderer from the entry
+      if (entry.ownedBy.length === 1) {
+        entry.atlas.dispose();
+        charAtlasCache.splice(i, 1);
+      } else {
+        entry.ownedBy.splice(ownedByIndex, 1);
+      }
+      break;
+    }
+  }
+
+  // Try match a char atlas from the cache
+  for (let i = 0; i < charAtlasCache.length; i++) {
+    const entry = charAtlasCache[i];
+    if (configEquals(entry.config, newConfig)) {
+      // Add the renderer to the cache entry and return
+      entry.ownedBy.push(rendererId);
+      return entry.atlas;
+    }
+  }
+
+  const newEntry: ICharAtlasCacheEntry = {
+    atlas: new DynamicCharAtlas(
+      document,
+      newConfig
+    ),
+    config: newConfig,
+    ownedBy: [rendererId]
+  };
+  charAtlasCache.push(newEntry);
+  return newEntry.atlas;
+}
+
+/**
+ * Removes a terminal reference from the cache, allowing its memory to be freed.
+ */
+export function removeTerminalFromCache(rendererId: number): void {
+  for (let i = 0; i < charAtlasCache.length; i++) {
+    const index = charAtlasCache[i].ownedBy.indexOf(rendererId);
+    if (index !== -1) {
+      if (charAtlasCache[i].ownedBy.length === 1) {
+        // Remove the cache entry if it's the only renderer
+        charAtlasCache[i].atlas.dispose();
+        charAtlasCache.splice(i, 1);
+      } else {
+        // Remove the reference from the cache entry
+        charAtlasCache[i].ownedBy.splice(index, 1);
+      }
+      break;
+    }
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts b/node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts
new file mode 100644 (file)
index 0000000..346b35f
--- /dev/null
@@ -0,0 +1,56 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharAtlasConfig } from 'browser/renderer/atlas/Types';
+import { DEFAULT_COLOR } from 'common/buffer/Constants';
+import { IColorSet, IPartialColorSet } from 'browser/Types';
+import { ITerminalOptions } from 'common/services/Services';
+
+export function generateConfig(scaledCharWidth: number, scaledCharHeight: number, options: ITerminalOptions, colors: IColorSet): ICharAtlasConfig {
+  // null out some fields that don't matter
+  const clonedColors = <IPartialColorSet>{
+    foreground: colors.foreground,
+    background: colors.background,
+    cursor: undefined,
+    cursorAccent: undefined,
+    selection: undefined,
+    // For the static char atlas, we only use the first 16 colors, but we need all 256 for the
+    // dynamic character atlas.
+    ansi: colors.ansi.slice(0, 16)
+  };
+  return {
+    devicePixelRatio: window.devicePixelRatio,
+    scaledCharWidth,
+    scaledCharHeight,
+    fontFamily: options.fontFamily,
+    fontSize: options.fontSize,
+    fontWeight: options.fontWeight,
+    fontWeightBold: options.fontWeightBold,
+    allowTransparency: options.allowTransparency,
+    colors: clonedColors
+  };
+}
+
+export function configEquals(a: ICharAtlasConfig, b: ICharAtlasConfig): boolean {
+  for (let i = 0; i < a.colors.ansi.length; i++) {
+    if (a.colors.ansi[i].rgba !== b.colors.ansi[i].rgba) {
+      return false;
+    }
+  }
+  return a.devicePixelRatio === b.devicePixelRatio &&
+      a.fontFamily === b.fontFamily &&
+      a.fontSize === b.fontSize &&
+      a.fontWeight === b.fontWeight &&
+      a.fontWeightBold === b.fontWeightBold &&
+      a.allowTransparency === b.allowTransparency &&
+      a.scaledCharWidth === b.scaledCharWidth &&
+      a.scaledCharHeight === b.scaledCharHeight &&
+      a.colors.foreground === b.colors.foreground &&
+      a.colors.background === b.colors.background;
+}
+
+export function is256Color(colorCode: number): boolean {
+  return colorCode < DEFAULT_COLOR;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/Constants.ts b/node_modules/xterm/src/browser/renderer/atlas/Constants.ts
new file mode 100644 (file)
index 0000000..150aad8
--- /dev/null
@@ -0,0 +1,9 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export const INVERTED_DEFAULT_COLOR = 257;
+export const DIM_OPACITY = 0.5;
+
+export const CHAR_ATLAS_CELL_SPACING = 1;
diff --git a/node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts b/node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts
new file mode 100644 (file)
index 0000000..40103bc
--- /dev/null
@@ -0,0 +1,369 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { IGlyphIdentifier, ICharAtlasConfig } from 'browser/renderer/atlas/Types';
+import { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';
+import { DEFAULT_ANSI_COLORS } from 'browser/ColorManager';
+import { LRUMap } from 'browser/renderer/atlas/LRUMap';
+import { isFirefox, isSafari } from 'common/Platform';
+import { IColor } from 'browser/Types';
+import { throwIfFalsy } from 'browser/renderer/RendererUtils';
+
+// In practice we're probably never going to exhaust a texture this large. For debugging purposes,
+// however, it can be useful to set this to a really tiny value, to verify that LRU eviction works.
+const TEXTURE_WIDTH = 1024;
+const TEXTURE_HEIGHT = 1024;
+
+const TRANSPARENT_COLOR = {
+  css: 'rgba(0, 0, 0, 0)',
+  rgba: 0
+};
+
+// Drawing to the cache is expensive: If we have to draw more than this number of glyphs to the
+// cache in a single frame, give up on trying to cache anything else, and try to finish the current
+// frame ASAP.
+//
+// This helps to limit the amount of damage a program can do when it would otherwise thrash the
+// cache.
+const FRAME_CACHE_DRAW_LIMIT = 100;
+
+/**
+ * The number of milliseconds to wait before generating the ImageBitmap, this is to debounce/batch
+ * the operation as window.createImageBitmap is asynchronous.
+ */
+const GLYPH_BITMAP_COMMIT_DELAY = 100;
+
+interface IGlyphCacheValue {
+  index: number;
+  isEmpty: boolean;
+  inBitmap: boolean;
+}
+
+export function getGlyphCacheKey(glyph: IGlyphIdentifier): number {
+  // Note that this only returns a valid key when code < 256
+  // Layout:
+  // 0b00000000000000000000000000000001: italic (1)
+  // 0b00000000000000000000000000000010: dim (1)
+  // 0b00000000000000000000000000000100: bold (1)
+  // 0b00000000000000000000111111111000: fg (9)
+  // 0b00000000000111111111000000000000: bg (9)
+  // 0b00011111111000000000000000000000: code (8)
+  // 0b11100000000000000000000000000000: unused (3)
+  return glyph.code << 21 | glyph.bg << 12 | glyph.fg << 3 | (glyph.bold ? 0 : 4) + (glyph.dim ? 0 : 2) + (glyph.italic ? 0 : 1);
+}
+
+export class DynamicCharAtlas extends BaseCharAtlas {
+  // An ordered map that we're using to keep track of where each glyph is in the atlas texture.
+  // It's ordered so that we can determine when to remove the old entries.
+  private _cacheMap: LRUMap<IGlyphCacheValue>;
+
+  // The texture that the atlas is drawn to
+  private _cacheCanvas: HTMLCanvasElement;
+  private _cacheCtx: CanvasRenderingContext2D;
+
+  // A temporary context that glyphs are drawn to before being transfered to the atlas.
+  private _tmpCtx: CanvasRenderingContext2D;
+
+  // The number of characters stored in the atlas by width/height
+  private _width: number;
+  private _height: number;
+
+  private _drawToCacheCount: number = 0;
+
+  // An array of glyph keys that are waiting on the bitmap to be generated.
+  private _glyphsWaitingOnBitmap: IGlyphCacheValue[] = [];
+
+  // The timeout that is used to batch bitmap generation so it's not requested for every new glyph.
+  private _bitmapCommitTimeout: number | null = null;
+
+  // The bitmap to draw from, this is much faster on other browsers than others.
+  private _bitmap: ImageBitmap | null = null;
+
+  constructor(document: Document, private _config: ICharAtlasConfig) {
+    super();
+    this._cacheCanvas = document.createElement('canvas');
+    this._cacheCanvas.width = TEXTURE_WIDTH;
+    this._cacheCanvas.height = TEXTURE_HEIGHT;
+    // The canvas needs alpha because we use clearColor to convert the background color to alpha.
+    // It might also contain some characters with transparent backgrounds if allowTransparency is
+    // set.
+    this._cacheCtx = throwIfFalsy(this._cacheCanvas.getContext('2d', {alpha: true}));
+
+    const tmpCanvas = document.createElement('canvas');
+    tmpCanvas.width = this._config.scaledCharWidth;
+    tmpCanvas.height = this._config.scaledCharHeight;
+    this._tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d', {alpha: this._config.allowTransparency}));
+
+    this._width = Math.floor(TEXTURE_WIDTH / this._config.scaledCharWidth);
+    this._height = Math.floor(TEXTURE_HEIGHT / this._config.scaledCharHeight);
+    const capacity = this._width * this._height;
+    this._cacheMap = new LRUMap(capacity);
+    this._cacheMap.prealloc(capacity);
+
+    // This is useful for debugging
+    // document.body.appendChild(this._cacheCanvas);
+  }
+
+  public dispose(): void {
+    if (this._bitmapCommitTimeout !== null) {
+      window.clearTimeout(this._bitmapCommitTimeout);
+      this._bitmapCommitTimeout = null;
+    }
+  }
+
+  public beginFrame(): void {
+    this._drawToCacheCount = 0;
+  }
+
+  public draw(
+    ctx: CanvasRenderingContext2D,
+    glyph: IGlyphIdentifier,
+    x: number,
+    y: number
+  ): boolean {
+    // Space is always an empty cell, special case this as it's so common
+    if (glyph.code === 32) {
+      return true;
+    }
+
+    // Exit early for uncachable glyphs
+    if (!this._canCache(glyph)) {
+      return false;
+    }
+
+    const glyphKey = getGlyphCacheKey(glyph);
+    const cacheValue = this._cacheMap.get(glyphKey);
+    if (cacheValue !== null && cacheValue !== undefined) {
+      this._drawFromCache(ctx, cacheValue, x, y);
+      return true;
+    } else if (this._drawToCacheCount < FRAME_CACHE_DRAW_LIMIT) {
+      let index;
+      if (this._cacheMap.size < this._cacheMap.capacity) {
+        index = this._cacheMap.size;
+      } else {
+        // we're out of space, so our call to set will delete this item
+        index = this._cacheMap.peek()!.index;
+      }
+      const cacheValue = this._drawToCache(glyph, index);
+      this._cacheMap.set(glyphKey, cacheValue);
+      this._drawFromCache(ctx, cacheValue, x, y);
+      return true;
+    }
+    return false;
+  }
+
+  private _canCache(glyph: IGlyphIdentifier): boolean {
+    // Only cache ascii and extended characters for now, to be safe. In the future, we could do
+    // something more complicated to determine the expected width of a character.
+    //
+    // If we switch the renderer over to webgl at some point, we may be able to use blending modes
+    // to draw overlapping glyphs from the atlas:
+    // https://github.com/servo/webrender/issues/464#issuecomment-255632875
+    // https://webglfundamentals.org/webgl/lessons/webgl-text-texture.html
+    return glyph.code < 256;
+  }
+
+  private _toCoordinateX(index: number): number {
+    return (index % this._width) * this._config.scaledCharWidth;
+  }
+
+  private _toCoordinateY(index: number): number {
+    return Math.floor(index / this._width) * this._config.scaledCharHeight;
+  }
+
+  private _drawFromCache(
+    ctx: CanvasRenderingContext2D,
+    cacheValue: IGlyphCacheValue,
+    x: number,
+    y: number
+  ): void {
+    // We don't actually need to do anything if this is whitespace.
+    if (cacheValue.isEmpty) {
+      return;
+    }
+    const cacheX = this._toCoordinateX(cacheValue.index);
+    const cacheY = this._toCoordinateY(cacheValue.index);
+    ctx.drawImage(
+      cacheValue.inBitmap ? this._bitmap! : this._cacheCanvas,
+      cacheX,
+      cacheY,
+      this._config.scaledCharWidth,
+      this._config.scaledCharHeight,
+      x,
+      y,
+      this._config.scaledCharWidth,
+      this._config.scaledCharHeight
+    );
+  }
+
+  private _getColorFromAnsiIndex(idx: number): IColor {
+    if (idx < this._config.colors.ansi.length) {
+      return this._config.colors.ansi[idx];
+    }
+    return DEFAULT_ANSI_COLORS[idx];
+  }
+
+  private _getBackgroundColor(glyph: IGlyphIdentifier): IColor {
+    if (this._config.allowTransparency) {
+      // The background color might have some transparency, so we need to render it as fully
+      // transparent in the atlas. Otherwise we'd end up drawing the transparent background twice
+      // around the anti-aliased edges of the glyph, and it would look too dark.
+      return TRANSPARENT_COLOR;
+    } else if (glyph.bg === INVERTED_DEFAULT_COLOR) {
+      return this._config.colors.foreground;
+    } else if (glyph.bg < 256) {
+      return this._getColorFromAnsiIndex(glyph.bg);
+    }
+    return this._config.colors.background;
+  }
+
+  private _getForegroundColor(glyph: IGlyphIdentifier): IColor {
+    if (glyph.fg === INVERTED_DEFAULT_COLOR) {
+      return this._config.colors.background;
+    } else if (glyph.fg < 256) {
+      // 256 color support
+      return this._getColorFromAnsiIndex(glyph.fg);
+    }
+    return this._config.colors.foreground;
+  }
+
+  // TODO: We do this (or something similar) in multiple places. We should split this off
+  // into a shared function.
+  private _drawToCache(glyph: IGlyphIdentifier, index: number): IGlyphCacheValue {
+    this._drawToCacheCount++;
+
+    this._tmpCtx.save();
+
+    // draw the background
+    const backgroundColor = this._getBackgroundColor(glyph);
+    // Use a 'copy' composite operation to clear any existing glyph out of _tmpCtxWithAlpha, regardless of
+    // transparency in backgroundColor
+    this._tmpCtx.globalCompositeOperation = 'copy';
+    this._tmpCtx.fillStyle = backgroundColor.css;
+    this._tmpCtx.fillRect(0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight);
+    this._tmpCtx.globalCompositeOperation = 'source-over';
+
+    // draw the foreground/glyph
+    const fontWeight = glyph.bold ? this._config.fontWeightBold : this._config.fontWeight;
+    const fontStyle = glyph.italic ? 'italic' : '';
+    this._tmpCtx.font =
+      `${fontStyle} ${fontWeight} ${this._config.fontSize * this._config.devicePixelRatio}px ${this._config.fontFamily}`;
+    this._tmpCtx.textBaseline = 'middle';
+
+    this._tmpCtx.fillStyle = this._getForegroundColor(glyph).css;
+
+    // Apply alpha to dim the character
+    if (glyph.dim) {
+      this._tmpCtx.globalAlpha = DIM_OPACITY;
+    }
+    // Draw the character
+    this._tmpCtx.fillText(glyph.chars, 0, this._config.scaledCharHeight / 2);
+    this._tmpCtx.restore();
+
+    // clear the background from the character to avoid issues with drawing over the previous
+    // character if it extends past it's bounds
+    const imageData = this._tmpCtx.getImageData(
+      0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight
+    );
+    let isEmpty = false;
+    if (!this._config.allowTransparency) {
+      isEmpty = clearColor(imageData, backgroundColor);
+    }
+
+    // copy the data from imageData to _cacheCanvas
+    const x = this._toCoordinateX(index);
+    const y = this._toCoordinateY(index);
+    // putImageData doesn't do any blending, so it will overwrite any existing cache entry for us
+    this._cacheCtx.putImageData(imageData, x, y);
+
+    // Add the glyph and queue it to the bitmap (if the browser supports it)
+    const cacheValue = {
+      index,
+      isEmpty,
+      inBitmap: false
+    };
+    this._addGlyphToBitmap(cacheValue);
+
+    return cacheValue;
+  }
+
+  private _addGlyphToBitmap(cacheValue: IGlyphCacheValue): void {
+    // Support is patchy for createImageBitmap at the moment, pass a canvas back
+    // if support is lacking as drawImage works there too. Firefox is also
+    // included here as ImageBitmap appears both buggy and has horrible
+    // performance (tested on v55).
+    if (!('createImageBitmap' in window) || isFirefox || isSafari) {
+      return;
+    }
+
+    // Add the glyph to the queue
+    this._glyphsWaitingOnBitmap.push(cacheValue);
+
+    // Check if bitmap generation timeout already exists
+    if (this._bitmapCommitTimeout !== null) {
+      return;
+    }
+
+    this._bitmapCommitTimeout = window.setTimeout(() => this._generateBitmap(), GLYPH_BITMAP_COMMIT_DELAY);
+  }
+
+  private _generateBitmap(): void {
+    const glyphsMovingToBitmap = this._glyphsWaitingOnBitmap;
+    this._glyphsWaitingOnBitmap = [];
+    window.createImageBitmap(this._cacheCanvas).then(bitmap => {
+      // Set bitmap
+      this._bitmap = bitmap;
+
+      // Mark all new glyphs as in bitmap, excluding glyphs that came in after
+      // the bitmap was requested
+      for (let i = 0; i < glyphsMovingToBitmap.length; i++) {
+        const value = glyphsMovingToBitmap[i];
+        // It doesn't matter if the value was already evicted, it will be
+        // released from memory after this block if so.
+        value.inBitmap = true;
+      }
+    });
+    this._bitmapCommitTimeout = null;
+  }
+}
+
+// This is used for debugging the renderer, just swap out `new DynamicCharAtlas` with
+// `new NoneCharAtlas`.
+export class NoneCharAtlas extends BaseCharAtlas {
+  constructor(document: Document, config: ICharAtlasConfig) {
+    super();
+  }
+
+  public draw(
+    ctx: CanvasRenderingContext2D,
+    glyph: IGlyphIdentifier,
+    x: number,
+    y: number
+  ): boolean {
+    return false;
+  }
+}
+
+/**
+ * Makes a partiicular rgb color in an ImageData completely transparent.
+ * @returns True if the result is "empty", meaning all pixels are fully transparent.
+ */
+function clearColor(imageData: ImageData, color: IColor): boolean {
+  let isEmpty = true;
+  const r = color.rgba >>> 24;
+  const g = color.rgba >>> 16 & 0xFF;
+  const b = color.rgba >>> 8 & 0xFF;
+  for (let offset = 0; offset < imageData.data.length; offset += 4) {
+    if (imageData.data[offset] === r &&
+        imageData.data[offset + 1] === g &&
+        imageData.data[offset + 2] === b) {
+      imageData.data[offset + 3] = 0;
+    } else {
+      isEmpty = false;
+    }
+  }
+  return isEmpty;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts b/node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts
new file mode 100644 (file)
index 0000000..f70962f
--- /dev/null
@@ -0,0 +1,136 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+interface ILinkedListNode<T> {
+  prev: ILinkedListNode<T> | null;
+  next: ILinkedListNode<T> | null;
+  key: number | null;
+  value: T | null;
+}
+
+export class LRUMap<T> {
+  private _map: { [key: number]: ILinkedListNode<T> } = {};
+  private _head: ILinkedListNode<T> | null = null;
+  private _tail: ILinkedListNode<T> | null = null;
+  private _nodePool: ILinkedListNode<T>[] = [];
+  public size: number = 0;
+
+  constructor(public capacity: number) { }
+
+  private _unlinkNode(node: ILinkedListNode<T>): void {
+    const prev = node.prev;
+    const next = node.next;
+    if (node === this._head) {
+      this._head = next;
+    }
+    if (node === this._tail) {
+      this._tail = prev;
+    }
+    if (prev !== null) {
+      prev.next = next;
+    }
+    if (next !== null) {
+      next.prev = prev;
+    }
+  }
+
+  private _appendNode(node: ILinkedListNode<T>): void {
+    const tail = this._tail;
+    if (tail !== null) {
+      tail.next = node;
+    }
+    node.prev = tail;
+    node.next = null;
+    this._tail = node;
+    if (this._head === null) {
+      this._head = node;
+    }
+  }
+
+  /**
+   * Preallocate a bunch of linked-list nodes. Allocating these nodes ahead of time means that
+   * they're more likely to live next to each other in memory, which seems to improve performance.
+   *
+   * Each empty object only consumes about 60 bytes of memory, so this is pretty cheap, even for
+   * large maps.
+   */
+  public prealloc(count: number): void {
+    const nodePool = this._nodePool;
+    for (let i = 0; i < count; i++) {
+      nodePool.push({
+        prev: null,
+        next: null,
+        key: null,
+        value: null
+      });
+    }
+  }
+
+  public get(key: number): T | null {
+    // This is unsafe: We're assuming our keyspace doesn't overlap with Object.prototype. However,
+    // it's faster than calling hasOwnProperty, and in our case, it would never overlap.
+    const node = this._map[key];
+    if (node !== undefined) {
+      this._unlinkNode(node);
+      this._appendNode(node);
+      return node.value;
+    }
+    return null;
+  }
+
+  /**
+   * Gets a value from a key without marking it as the most recently used item.
+   */
+  public peekValue(key: number): T | null {
+    const node = this._map[key];
+    if (node !== undefined) {
+      return node.value;
+    }
+    return null;
+  }
+
+  public peek(): T | null {
+    const head = this._head;
+    return head === null ? null : head.value;
+  }
+
+  public set(key: number, value: T): void {
+    // This is unsafe: See note above.
+    let node = this._map[key];
+    if (node !== undefined) {
+      // already exists, we just need to mutate it and move it to the end of the list
+      node = this._map[key];
+      this._unlinkNode(node);
+      node.value = value;
+    } else if (this.size >= this.capacity) {
+      // we're out of space: recycle the head node, move it to the tail
+      node = this._head!;
+      this._unlinkNode(node);
+      delete this._map[node.key!];
+      node.key = key;
+      node.value = value;
+      this._map[key] = node;
+    } else {
+      // make a new element
+      const nodePool = this._nodePool;
+      if (nodePool.length > 0) {
+        // use a preallocated node if we can
+        node = nodePool.pop()!;
+        node.key = key;
+        node.value = value;
+      } else {
+        node = {
+          prev: null,
+          next: null,
+          key,
+          value
+        };
+      }
+      this._map[key] = node;
+      this.size++;
+    }
+    this._appendNode(node);
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/Types.d.ts b/node_modules/xterm/src/browser/renderer/atlas/Types.d.ts
new file mode 100644 (file)
index 0000000..d8bc54c
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { FontWeight } from 'common/services/Services';
+import { IPartialColorSet } from 'browser/Types';
+
+export interface IGlyphIdentifier {
+  chars: string;
+  code: number;
+  bg: number;
+  fg: number;
+  bold: boolean;
+  dim: boolean;
+  italic: boolean;
+}
+
+export interface ICharAtlasConfig {
+  devicePixelRatio: number;
+  fontSize: number;
+  fontFamily: string;
+  fontWeight: FontWeight;
+  fontWeightBold: FontWeight;
+  scaledCharWidth: number;
+  scaledCharHeight: number;
+  allowTransparency: boolean;
+  colors: IPartialColorSet;
+}
diff --git a/node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts b/node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts
new file mode 100644 (file)
index 0000000..3e3b5df
--- /dev/null
@@ -0,0 +1,132 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferLine } from 'common/Types';
+import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { NULL_CELL_CODE, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { IOptionsService } from 'common/services/Services';
+
+export const BOLD_CLASS = 'xterm-bold';
+export const DIM_CLASS = 'xterm-dim';
+export const ITALIC_CLASS = 'xterm-italic';
+export const UNDERLINE_CLASS = 'xterm-underline';
+export const CURSOR_CLASS = 'xterm-cursor';
+export const CURSOR_BLINK_CLASS = 'xterm-cursor-blink';
+export const CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block';
+export const CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar';
+export const CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline';
+
+export class DomRendererRowFactory {
+  private _workCell: CellData = new CellData();
+
+  constructor(
+    private _document: Document,
+    private _optionsService: IOptionsService
+  ) {
+  }
+
+  public createRow(lineData: IBufferLine, isCursorRow: boolean, cursorStyle: string | undefined, cursorX: number, cursorBlink: boolean, cellWidth: number, cols: number): DocumentFragment {
+    const fragment = this._document.createDocumentFragment();
+
+    // Find the line length first, this prevents the need to output a bunch of
+    // empty cells at the end. This cannot easily be integrated into the main
+    // loop below because of the colCount feature (which can be removed after we
+    // properly support reflow and disallow data to go beyond the right-side of
+    // the viewport).
+    let lineLength = 0;
+    for (let x = Math.min(lineData.length, cols) - 1; x >= 0; x--) {
+      if (lineData.loadCell(x, this._workCell).getCode() !== NULL_CELL_CODE || (isCursorRow && x === cursorX)) {
+        lineLength = x + 1;
+        break;
+      }
+    }
+
+    for (let x = 0; x < lineLength; x++) {
+      lineData.loadCell(x, this._workCell);
+      const width = this._workCell.getWidth();
+
+      // The character to the left is a wide character, drawing is owned by the char at x-1
+      if (width === 0) {
+        continue;
+      }
+
+      const charElement = this._document.createElement('span');
+      if (width > 1) {
+        charElement.style.width = `${cellWidth * width}px`;
+      }
+
+      if (isCursorRow && x === cursorX) {
+        charElement.classList.add(CURSOR_CLASS);
+
+        if (cursorBlink) {
+          charElement.classList.add(CURSOR_BLINK_CLASS);
+        }
+
+        switch (cursorStyle) {
+          case 'bar':
+            charElement.classList.add(CURSOR_STYLE_BAR_CLASS);
+            break;
+          case 'underline':
+            charElement.classList.add(CURSOR_STYLE_UNDERLINE_CLASS);
+            break;
+          default:
+            charElement.classList.add(CURSOR_STYLE_BLOCK_CLASS);
+            break;
+        }
+      }
+
+      if (this._workCell.isBold()) {
+        charElement.classList.add(BOLD_CLASS);
+      }
+
+      if (this._workCell.isItalic()) {
+        charElement.classList.add(ITALIC_CLASS);
+      }
+
+      if (this._workCell.isDim()) {
+        charElement.classList.add(DIM_CLASS);
+      }
+
+      if (this._workCell.isUnderline()) {
+        charElement.classList.add(UNDERLINE_CLASS);
+      }
+
+      charElement.textContent = this._workCell.getChars() || WHITESPACE_CELL_CHAR;
+
+      const swapColor = this._workCell.isInverse();
+
+      // fg
+      if (this._workCell.isFgRGB()) {
+        let style = charElement.getAttribute('style') || '';
+        style += `${swapColor ? 'background-' : ''}color:rgb(${(AttributeData.toColorRGB(this._workCell.getFgColor())).join(',')});`;
+        charElement.setAttribute('style', style);
+      } else if (this._workCell.isFgPalette()) {
+        let fg = this._workCell.getFgColor();
+        if (this._workCell.isBold() && fg < 8 && !swapColor && this._optionsService.options.drawBoldTextInBrightColors) {
+          fg += 8;
+        }
+        charElement.classList.add(`xterm-${swapColor ? 'b' : 'f'}g-${fg}`);
+      } else if (swapColor) {
+        charElement.classList.add(`xterm-bg-${INVERTED_DEFAULT_COLOR}`);
+      }
+
+      // bg
+      if (this._workCell.isBgRGB()) {
+        let style = charElement.getAttribute('style') || '';
+        style += `${swapColor ? '' : 'background-'}color:rgb(${(AttributeData.toColorRGB(this._workCell.getBgColor())).join(',')});`;
+        charElement.setAttribute('style', style);
+      } else if (this._workCell.isBgPalette()) {
+        charElement.classList.add(`xterm-${swapColor ? 'f' : 'b'}g-${this._workCell.getBgColor()}`);
+      } else if (swapColor) {
+        charElement.classList.add(`xterm-fg-${INVERTED_DEFAULT_COLOR}`);
+      }
+
+      fragment.appendChild(charElement);
+    }
+    return fragment;
+  }
+}
diff --git a/node_modules/xterm/src/browser/selection/SelectionModel.ts b/node_modules/xterm/src/browser/selection/SelectionModel.ts
new file mode 100644 (file)
index 0000000..1420444
--- /dev/null
@@ -0,0 +1,135 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferService } from 'common/services/Services';
+
+/**
+ * Represents a selection within the buffer. This model only cares about column
+ * and row coordinates, not wide characters.
+ */
+export class SelectionModel {
+  /**
+   * Whether select all is currently active.
+   */
+  public isSelectAllActive: boolean = false;
+
+  /**
+   * The minimal length of the selection from the start position. When double
+   * clicking on a word, the word will be selected which makes the selection
+   * start at the start of the word and makes this variable the length.
+   */
+  public selectionStartLength: number = 0;
+
+  /**
+   * The [x, y] position the selection starts at.
+   */
+  public selectionStart: [number, number] | undefined;
+
+  /**
+   * The [x, y] position the selection ends at.
+   */
+  public selectionEnd: [number, number] | undefined;
+
+  constructor(
+    private _bufferService: IBufferService
+  ) {
+  }
+
+  /**
+   * Clears the current selection.
+   */
+  public clearSelection(): void {
+    this.selectionStart = undefined;
+    this.selectionEnd = undefined;
+    this.isSelectAllActive = false;
+    this.selectionStartLength = 0;
+  }
+
+  /**
+   * The final selection start, taking into consideration select all.
+   */
+  public get finalSelectionStart(): [number, number] | undefined {
+    if (this.isSelectAllActive) {
+      return [0, 0];
+    }
+
+    if (!this.selectionEnd || !this.selectionStart) {
+      return this.selectionStart;
+    }
+
+    return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;
+  }
+
+  /**
+   * The final selection end, taking into consideration select all, double click
+   * word selection and triple click line selection.
+   */
+  public get finalSelectionEnd(): [number, number] | undefined {
+    if (this.isSelectAllActive) {
+      return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1];
+    }
+
+    if (!this.selectionStart) {
+      return undefined;
+    }
+
+    // Use the selection start + length if the end doesn't exist or they're reversed
+    if (!this.selectionEnd || this.areSelectionValuesReversed()) {
+      const startPlusLength = this.selectionStart[0] + this.selectionStartLength;
+      if (startPlusLength > this._bufferService.cols) {
+        return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];
+      }
+      return [startPlusLength, this.selectionStart[1]];
+    }
+
+    // Ensure the the word/line is selected after a double/triple click
+    if (this.selectionStartLength) {
+      // Select the larger of the two when start and end are on the same line
+      if (this.selectionEnd[1] === this.selectionStart[1]) {
+        return [Math.max(this.selectionStart[0] + this.selectionStartLength, this.selectionEnd[0]), this.selectionEnd[1]];
+      }
+    }
+    return this.selectionEnd;
+  }
+
+  /**
+   * Returns whether the selection start and end are reversed.
+   */
+  public areSelectionValuesReversed(): boolean {
+    const start = this.selectionStart;
+    const end = this.selectionEnd;
+    if (!start || !end) {
+      return false;
+    }
+    return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]);
+  }
+
+  /**
+   * Handle the buffer being trimmed, adjust the selection position.
+   * @param amount The amount the buffer is being trimmed.
+   * @return Whether a refresh is necessary.
+   */
+  public onTrim(amount: number): boolean {
+    // Adjust the selection position based on the trimmed amount.
+    if (this.selectionStart) {
+      this.selectionStart[1] -= amount;
+    }
+    if (this.selectionEnd) {
+      this.selectionEnd[1] -= amount;
+    }
+
+    // The selection has moved off the buffer, clear it.
+    if (this.selectionEnd && this.selectionEnd[1] < 0) {
+      this.clearSelection();
+      return true;
+    }
+
+    // If the selection start is trimmed, ensure the start column is 0.
+    if (this.selectionStart && this.selectionStart[1] < 0) {
+      this.selectionStart[1] = 0;
+    }
+    return false;
+  }
+}
diff --git a/node_modules/xterm/src/browser/selection/Types.d.ts b/node_modules/xterm/src/browser/selection/Types.d.ts
new file mode 100644 (file)
index 0000000..d5a03ec
--- /dev/null
@@ -0,0 +1,10 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export interface ISelectionRedrawRequestEvent {
+  start: [number, number] | undefined;
+  end: [number, number] | undefined;
+  columnSelectMode: boolean;
+}
diff --git a/node_modules/xterm/src/browser/services/CharSizeService.ts b/node_modules/xterm/src/browser/services/CharSizeService.ts
new file mode 100644 (file)
index 0000000..0749a42
--- /dev/null
@@ -0,0 +1,87 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOptionsService } from 'common/services/Services';
+import { IEvent, EventEmitter } from 'common/EventEmitter';
+import { ICharSizeService } from 'browser/services/Services';
+
+export class CharSizeService implements ICharSizeService {
+  serviceBrand: any;
+
+  public width: number = 0;
+  public height: number = 0;
+  private _measureStrategy: IMeasureStrategy;
+
+  public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; }
+
+  private _onCharSizeChange = new EventEmitter<void>();
+  public get onCharSizeChange(): IEvent<void> { return this._onCharSizeChange.event; }
+
+  constructor(
+    readonly document: Document,
+    readonly parentElement: HTMLElement,
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    this._measureStrategy = new DomMeasureStrategy(document, parentElement, this._optionsService);
+  }
+
+  public measure(): void {
+    const result = this._measureStrategy.measure();
+    if (result.width !== this.width || result.height !== this.height) {
+      this.width = result.width;
+      this.height = result.height;
+      this._onCharSizeChange.fire();
+    }
+  }
+}
+
+interface IMeasureStrategy {
+  measure(): IReadonlyMeasureResult;
+}
+
+interface IReadonlyMeasureResult {
+  readonly width: number;
+  readonly height: number;
+}
+
+interface IMeasureResult {
+  width: number;
+  height: number;
+}
+
+// TODO: For supporting browsers we should also provide a CanvasCharDimensionsProvider that uses ctx.measureText
+class DomMeasureStrategy implements IMeasureStrategy {
+  private _result: IMeasureResult = { width: 0, height: 0 };
+  private _measureElement: HTMLElement;
+
+  constructor(
+    private _document: Document,
+    private _parentElement: HTMLElement,
+    private _optionsService: IOptionsService
+  ) {
+    this._measureElement = this._document.createElement('span');
+    this._measureElement.classList.add('xterm-char-measure-element');
+    this._measureElement.textContent = 'W';
+    this._measureElement.setAttribute('aria-hidden', 'true');
+    this._parentElement.appendChild(this._measureElement);
+  }
+
+  public measure(): IReadonlyMeasureResult {
+    this._measureElement.style.fontFamily = this._optionsService.options.fontFamily;
+    this._measureElement.style.fontSize = `${this._optionsService.options.fontSize}px`;
+
+    // Note that this triggers a synchronous layout
+    const geometry = this._measureElement.getBoundingClientRect();
+
+    // If values are 0 then the element is likely currently display:none, in which case we should
+    // retain the previous value.
+    if (geometry.width !== 0 && geometry.height !== 0) {
+      this._result.width = geometry.width;
+      this._result.height = Math.ceil(geometry.height);
+    }
+
+    return this._result;
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/MouseService.ts b/node_modules/xterm/src/browser/services/MouseService.ts
new file mode 100644 (file)
index 0000000..b0f8c35
--- /dev/null
@@ -0,0 +1,35 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharSizeService, IRenderService, IMouseService } from './Services';
+import { getCoords, getRawByteCoords } from 'browser/input/Mouse';
+
+export class MouseService implements IMouseService {
+  serviceBrand: any;
+
+  constructor(
+    @IRenderService private readonly _renderService: IRenderService,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService
+  ) {
+  }
+
+  public getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined {
+    return getCoords(
+      event,
+      element,
+      colCount,
+      rowCount,
+      this._charSizeService.hasValidSize,
+      this._renderService.dimensions.actualCellWidth,
+      this._renderService.dimensions.actualCellHeight,
+      isSelection
+    );
+  }
+
+  public getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined {
+    const coords = this.getCoords(event, element, colCount, rowCount);
+    return getRawByteCoords(coords);
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/RenderService.ts b/node_modules/xterm/src/browser/services/RenderService.ts
new file mode 100644 (file)
index 0000000..63084f5
--- /dev/null
@@ -0,0 +1,172 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { RenderDebouncer } from 'browser/RenderDebouncer';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { Disposable } from 'common/Lifecycle';
+import { ScreenDprMonitor } from 'browser/ScreenDprMonitor';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { IColorSet } from 'browser/Types';
+import { IOptionsService } from 'common/services/Services';
+import { ICharSizeService, IRenderService } from 'browser/services/Services';
+
+export class RenderService extends Disposable implements IRenderService {
+  serviceBrand: any;
+
+  private _renderDebouncer: RenderDebouncer;
+  private _screenDprMonitor: ScreenDprMonitor;
+
+  private _isPaused: boolean = false;
+  private _needsFullRefresh: boolean = false;
+  private _canvasWidth: number = 0;
+  private _canvasHeight: number = 0;
+
+  private _onDimensionsChange = new EventEmitter<IRenderDimensions>();
+  public get onDimensionsChange(): IEvent<IRenderDimensions> { return this._onDimensionsChange.event; }
+  private _onRender = new EventEmitter<{ start: number, end: number }>();
+  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }
+  private _onRefreshRequest = new EventEmitter<{ start: number, end: number }>();
+  public get onRefreshRequest(): IEvent<{ start: number, end: number }> { return this._onRefreshRequest.event; }
+
+  public get dimensions(): IRenderDimensions { return this._renderer.dimensions; }
+
+  constructor(
+    private _renderer: IRenderer,
+    private _rowCount: number,
+    readonly screenElement: HTMLElement,
+    @IOptionsService readonly optionsService: IOptionsService,
+    @ICharSizeService readonly charSizeService: ICharSizeService
+  ) {
+    super();
+    this._renderDebouncer = new RenderDebouncer((start, end) => this._renderRows(start, end));
+    this.register(this._renderDebouncer);
+
+    this._screenDprMonitor = new ScreenDprMonitor();
+    this._screenDprMonitor.setListener(() => this.onDevicePixelRatioChange());
+    this.register(this._screenDprMonitor);
+
+    this.register(optionsService.onOptionChange(() => this._renderer.onOptionsChanged()));
+    this.register(charSizeService.onCharSizeChange(() => this.onCharSizeChanged()));
+
+    // dprchange should handle this case, we need this as well for browsers that don't support the
+    // matchMedia query.
+    this.register(addDisposableDomListener(window, 'resize', () => this.onDevicePixelRatioChange()));
+
+    // Detect whether IntersectionObserver is detected and enable renderer pause
+    // and resume based on terminal visibility if so
+    if ('IntersectionObserver' in window) {
+      const observer = new IntersectionObserver(e => this._onIntersectionChange(e[e.length - 1]), { threshold: 0 });
+      observer.observe(screenElement);
+      this.register({ dispose: () => observer.disconnect() });
+    }
+  }
+
+  private _onIntersectionChange(entry: IntersectionObserverEntry): void {
+    this._isPaused = entry.intersectionRatio === 0;
+    if (!this._isPaused && this._needsFullRefresh) {
+      this.refreshRows(0, this._rowCount - 1);
+      this._needsFullRefresh = false;
+    }
+  }
+
+  public refreshRows(start: number, end: number): void {
+    if (this._isPaused) {
+      this._needsFullRefresh = true;
+      return;
+    }
+    this._renderDebouncer.refresh(start, end, this._rowCount);
+  }
+
+  private _renderRows(start: number, end: number): void {
+    this._renderer.renderRows(start, end);
+    this._onRender.fire({ start, end });
+  }
+
+  public resize(cols: number, rows: number): void {
+    this._rowCount = rows;
+    this._fireOnCanvasResize();
+  }
+
+  public changeOptions(): void {
+    this._renderer.onOptionsChanged();
+    this._fireOnCanvasResize();
+  }
+
+  private _fireOnCanvasResize(): void {
+    // Don't fire the event if the dimensions haven't changed
+    if (this._renderer.dimensions.canvasWidth === this._canvasWidth && this._renderer.dimensions.canvasHeight === this._canvasHeight) {
+      return;
+    }
+    this._onDimensionsChange.fire(this._renderer.dimensions);
+  }
+
+  public dispose(): void {
+    this._renderer.dispose();
+  }
+
+  public setRenderer(renderer: IRenderer): void {
+    // TODO: RenderService should be the only one to dispose the renderer
+    this._renderer.dispose();
+    this._renderer = renderer;
+    this.refreshRows(0, this._rowCount - 1);
+  }
+
+  private _fullRefresh(): void {
+    if (this._isPaused) {
+      this._needsFullRefresh = true;
+    } else {
+      this.refreshRows(0, this._rowCount - 1);
+    }
+  }
+
+  public setColors(colors: IColorSet): void {
+    this._renderer.setColors(colors);
+    this._fullRefresh();
+  }
+
+  public onDevicePixelRatioChange(): void {
+    this._renderer.onDevicePixelRatioChange();
+    this.refreshRows(0, this._rowCount - 1);
+  }
+
+  public onResize(cols: number, rows: number): void {
+    this._renderer.onResize(cols, rows);
+    this._fullRefresh();
+  }
+
+  // TODO: Is this useful when we have onResize?
+  public onCharSizeChanged(): void {
+    this._renderer.onCharSizeChanged();
+  }
+
+  public onBlur(): void {
+    this._renderer.onBlur();
+  }
+
+  public onFocus(): void {
+    this._renderer.onFocus();
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {
+    this._renderer.onSelectionChanged(start, end, columnSelectMode);
+  }
+
+  public onCursorMove(): void {
+    this._renderer.onCursorMove();
+  }
+
+  public clear(): void {
+    this._renderer.clear();
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {
+    return this._renderer.registerCharacterJoiner(handler);
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): boolean {
+    return this._renderer.deregisterCharacterJoiner(joinerId);
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/SelectionService.ts b/node_modules/xterm/src/browser/services/SelectionService.ts
new file mode 100644 (file)
index 0000000..3631bbb
--- /dev/null
@@ -0,0 +1,952 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ISelectionRedrawRequestEvent } from 'browser/selection/Types';
+import { IBuffer } from 'common/buffer/Types';
+import { IBufferLine, IDisposable } from 'common/Types';
+import * as Browser from 'common/Platform';
+import { SelectionModel } from 'browser/selection/SelectionModel';
+import { CellData } from 'common/buffer/CellData';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { ICharSizeService, IMouseService, ISelectionService } from 'browser/services/Services';
+import { IBufferService, IOptionsService, ICoreService } from 'common/services/Services';
+import { getCoordsRelativeToElement } from 'browser/input/Mouse';
+import { moveToCellSequence } from 'browser/input/MoveToCell';
+
+/**
+ * The number of pixels the mouse needs to be above or below the viewport in
+ * order to scroll at the maximum speed.
+ */
+const DRAG_SCROLL_MAX_THRESHOLD = 50;
+
+/**
+ * The maximum scrolling speed
+ */
+const DRAG_SCROLL_MAX_SPEED = 15;
+
+/**
+ * The number of milliseconds between drag scroll updates.
+ */
+const DRAG_SCROLL_INTERVAL = 50;
+
+/**
+ * The maximum amount of time that can have elapsed for an alt click to move the
+ * cursor.
+ */
+const ALT_CLICK_MOVE_CURSOR_TIME = 500;
+
+const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
+const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
+
+/**
+ * Represents a position of a word on a line.
+ */
+interface IWordPosition {
+  start: number;
+  length: number;
+}
+
+/**
+ * A selection mode, this drives how the selection behaves on mouse move.
+ */
+export const enum SelectionMode {
+  NORMAL,
+  WORD,
+  LINE,
+  COLUMN
+}
+
+/**
+ * A class that manages the selection of the terminal. With help from
+ * SelectionModel, SelectionService handles with all logic associated with
+ * dealing with the selection, including handling mouse interaction, wide
+ * characters and fetching the actual text within the selection. Rendering is
+ * not handled by the SelectionService but the onRedrawRequest event is fired
+ * when the selection is ready to be redrawn (on an animation frame).
+ */
+export class SelectionService implements ISelectionService {
+  serviceBrand: any;
+
+  protected _model: SelectionModel;
+
+  /**
+   * The amount to scroll every drag scroll update (depends on how far the mouse
+   * drag is above or below the terminal).
+   */
+  private _dragScrollAmount: number = 0;
+
+  /**
+   * The current selection mode.
+   */
+  protected _activeSelectionMode: SelectionMode;
+
+  /**
+   * A setInterval timer that is active while the mouse is down whose callback
+   * scrolls the viewport when necessary.
+   */
+  private _dragScrollIntervalTimer: number | undefined;
+
+  /**
+   * The animation frame ID used for refreshing the selection.
+   */
+  private _refreshAnimationFrame: number | undefined;
+
+  /**
+   * Whether selection is enabled.
+   */
+  private _enabled = true;
+
+  private _mouseMoveListener: EventListener;
+  private _mouseUpListener: EventListener;
+  private _trimListener: IDisposable;
+  private _workCell: CellData = new CellData();
+
+  private _mouseDownTimeStamp: number = 0;
+
+  private _onLinuxMouseSelection = new EventEmitter<string>();
+  public get onLinuxMouseSelection(): IEvent<string> { return this._onLinuxMouseSelection.event; }
+  private _onRedrawRequest = new EventEmitter<ISelectionRedrawRequestEvent>();
+  public get onRedrawRequest(): IEvent<ISelectionRedrawRequestEvent> { return this._onRedrawRequest.event; }
+  private _onSelectionChange = new EventEmitter<void>();
+  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }
+
+  constructor(
+    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,
+    private readonly _element: HTMLElement,
+    private readonly _screenElement: HTMLElement,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @ICoreService private readonly _coreService: ICoreService,
+    @IMouseService private readonly _mouseService: IMouseService,
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    // Init listeners
+    this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
+    this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
+    this._coreService.onUserInput(() => {
+      if (this.hasSelection) {
+        this.clearSelection();
+      }
+    });
+    this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._onTrim(amount));
+    this._bufferService.buffers.onBufferActivate(e => this._onBufferActivate(e));
+
+    this.enable();
+
+    this._model = new SelectionModel(this._bufferService);
+    this._activeSelectionMode = SelectionMode.NORMAL;
+  }
+
+  public dispose(): void {
+    this._removeMouseDownListeners();
+  }
+
+  public reset(): void {
+    this.clearSelection();
+  }
+
+  /**
+   * Disables the selection manager. This is useful for when terminal mouse
+   * are enabled.
+   */
+  public disable(): void {
+    this.clearSelection();
+    this._enabled = false;
+  }
+
+  /**
+   * Enable the selection manager.
+   */
+  public enable(): void {
+    this._enabled = true;
+  }
+
+  public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }
+  public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }
+
+  /**
+   * Gets whether there is an active text selection.
+   */
+  public get hasSelection(): boolean {
+    const start = this._model.finalSelectionStart;
+    const end = this._model.finalSelectionEnd;
+    if (!start || !end) {
+      return false;
+    }
+    return start[0] !== end[0] || start[1] !== end[1];
+  }
+
+  /**
+   * Gets the text currently selected.
+   */
+  public get selectionText(): string {
+    const start = this._model.finalSelectionStart;
+    const end = this._model.finalSelectionEnd;
+    if (!start || !end) {
+      return '';
+    }
+
+    const buffer = this._bufferService.buffer;
+    const result: string[] = [];
+
+    if (this._activeSelectionMode === SelectionMode.COLUMN) {
+      // Ignore zero width selections
+      if (start[0] === end[0]) {
+        return '';
+      }
+
+      for (let i = start[1]; i <= end[1]; i++) {
+        const lineText = buffer.translateBufferLineToString(i, true, start[0], end[0]);
+        result.push(lineText);
+      }
+    } else {
+      // Get first row
+      const startRowEndCol = start[1] === end[1] ? end[0] : undefined;
+      result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));
+
+      // Get middle rows
+      for (let i = start[1] + 1; i <= end[1] - 1; i++) {
+        const bufferLine = buffer.lines.get(i);
+        const lineText = buffer.translateBufferLineToString(i, true);
+        if (bufferLine && bufferLine.isWrapped) {
+          result[result.length - 1] += lineText;
+        } else {
+          result.push(lineText);
+        }
+      }
+
+      // Get final row
+      if (start[1] !== end[1]) {
+        const bufferLine = buffer.lines.get(end[1]);
+        const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);
+        if (bufferLine && bufferLine!.isWrapped) {
+          result[result.length - 1] += lineText;
+        } else {
+          result.push(lineText);
+        }
+      }
+    }
+
+    // Format string by replacing non-breaking space chars with regular spaces
+    // and joining the array into a multi-line string.
+    const formattedResult = result.map(line => {
+      return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
+    }).join(Browser.isWindows ? '\r\n' : '\n');
+
+    return formattedResult;
+  }
+
+  /**
+   * Clears the current terminal selection.
+   */
+  public clearSelection(): void {
+    this._model.clearSelection();
+    this._removeMouseDownListeners();
+    this.refresh();
+    this._onSelectionChange.fire();
+  }
+
+  /**
+   * Queues a refresh, redrawing the selection on the next opportunity.
+   * @param isLinuxMouseSelection Whether the selection should be registered as a new
+   * selection on Linux.
+   */
+  public refresh(isLinuxMouseSelection?: boolean): void {
+    // Queue the refresh for the renderer
+    if (!this._refreshAnimationFrame) {
+      this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
+    }
+
+    // If the platform is Linux and the refresh call comes from a mouse event,
+    // we need to update the selection for middle click to paste selection.
+    if (Browser.isLinux && isLinuxMouseSelection) {
+      const selectionText = this.selectionText;
+      if (selectionText.length) {
+        this._onLinuxMouseSelection.fire(this.selectionText);
+      }
+    }
+  }
+
+  /**
+   * Fires the refresh event, causing consumers to pick it up and redraw the
+   * selection state.
+   */
+  private _refresh(): void {
+    this._refreshAnimationFrame = undefined;
+    this._onRedrawRequest.fire({
+      start: this._model.finalSelectionStart,
+      end: this._model.finalSelectionEnd,
+      columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN
+    });
+  }
+
+  /**
+   * Checks if the current click was inside the current selection
+   * @param event The mouse event
+   */
+  public isClickInSelection(event: MouseEvent): boolean {
+    const coords = this._getMouseBufferCoords(event);
+    const start = this._model.finalSelectionStart;
+    const end = this._model.finalSelectionEnd;
+
+    if (!start || !end || !coords) {
+      return false;
+    }
+
+    return this._areCoordsInSelection(coords, start, end);
+  }
+
+  protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {
+    return (coords[1] > start[1] && coords[1] < end[1]) ||
+        (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||
+        (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||
+        (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);
+  }
+
+  /**
+   * Selects word at the current mouse event coordinates.
+   * @param event The mouse event.
+   */
+  public selectWordAtCursor(event: MouseEvent): void {
+    const coords = this._getMouseBufferCoords(event);
+    if (coords) {
+      this._selectWordAt(coords, false);
+      this._model.selectionEnd = undefined;
+      this.refresh(true);
+    }
+  }
+
+  /**
+   * Selects all text within the terminal.
+   */
+  public selectAll(): void {
+    this._model.isSelectAllActive = true;
+    this.refresh();
+    this._onSelectionChange.fire();
+  }
+
+  public selectLines(start: number, end: number): void {
+    this._model.clearSelection();
+    start = Math.max(start, 0);
+    end = Math.min(end, this._bufferService.buffer.lines.length - 1);
+    this._model.selectionStart = [0, start];
+    this._model.selectionEnd = [this._bufferService.cols, end];
+    this.refresh();
+    this._onSelectionChange.fire();
+  }
+
+  /**
+   * Handle the buffer being trimmed, adjust the selection position.
+   * @param amount The amount the buffer is being trimmed.
+   */
+  private _onTrim(amount: number): void {
+    const needsRefresh = this._model.onTrim(amount);
+    if (needsRefresh) {
+      this.refresh();
+    }
+  }
+
+  /**
+   * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
+   * @param event The mouse event.
+   */
+  private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {
+    const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);
+    if (!coords) {
+      return undefined;
+    }
+
+    // Convert to 0-based
+    coords[0]--;
+    coords[1]--;
+
+    // Convert viewport coords to buffer coords
+    coords[1] += this._bufferService.buffer.ydisp;
+    return coords;
+  }
+
+  /**
+   * Gets the amount the viewport should be scrolled based on how far out of the
+   * terminal the mouse is.
+   * @param event The mouse event.
+   */
+  private _getMouseEventScrollAmount(event: MouseEvent): number {
+    let offset = getCoordsRelativeToElement(event, this._screenElement)[1];
+    const terminalHeight = this._bufferService.rows * Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);
+    if (offset >= 0 && offset <= terminalHeight) {
+      return 0;
+    }
+    if (offset > terminalHeight) {
+      offset -= terminalHeight;
+    }
+
+    offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
+    offset /= DRAG_SCROLL_MAX_THRESHOLD;
+    return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
+  }
+
+  /**
+   * Returns whether the selection manager should force selection, regardless of
+   * whether the terminal is in mouse events mode.
+   * @param event The mouse event.
+   */
+  public shouldForceSelection(event: MouseEvent): boolean {
+    if (Browser.isMac) {
+      return event.altKey && this._optionsService.options.macOptionClickForcesSelection;
+    }
+
+    return event.shiftKey;
+  }
+
+  /**
+   * Handles te mousedown event, setting up for a new selection.
+   * @param event The mousedown event.
+   */
+  public onMouseDown(event: MouseEvent): void {
+    this._mouseDownTimeStamp = event.timeStamp;
+    // If we have selection, we want the context menu on right click even if the
+    // terminal is in mouse mode.
+    if (event.button === 2 && this.hasSelection) {
+      return;
+    }
+
+    // Only action the primary button
+    if (event.button !== 0) {
+      return;
+    }
+
+    // Allow selection when using a specific modifier key, even when disabled
+    if (!this._enabled) {
+      if (!this.shouldForceSelection(event)) {
+        return;
+      }
+
+      // Don't send the mouse down event to the current process, we want to select
+      event.stopPropagation();
+    }
+
+    // Tell the browser not to start a regular selection
+    event.preventDefault();
+
+    // Reset drag scroll state
+    this._dragScrollAmount = 0;
+
+    if (this._enabled && event.shiftKey) {
+      this._onIncrementalClick(event);
+    } else {
+      if (event.detail === 1) {
+        this._onSingleClick(event);
+      } else if (event.detail === 2) {
+        this._onDoubleClick(event);
+      } else if (event.detail === 3) {
+        this._onTripleClick(event);
+      }
+    }
+
+    this._addMouseDownListeners();
+    this.refresh(true);
+  }
+
+  /**
+   * Adds listeners when mousedown is triggered.
+   */
+  private _addMouseDownListeners(): void {
+    // Listen on the document so that dragging outside of viewport works
+    if (this._screenElement.ownerDocument) {
+      this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
+      this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
+    }
+    this._dragScrollIntervalTimer = window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
+  }
+
+  /**
+   * Removes the listeners that are registered when mousedown is triggered.
+   */
+  private _removeMouseDownListeners(): void {
+    if (this._screenElement.ownerDocument) {
+      this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
+      this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
+    }
+    clearInterval(this._dragScrollIntervalTimer);
+    this._dragScrollIntervalTimer = undefined;
+  }
+
+  /**
+   * Performs an incremental click, setting the selection end position to the mouse
+   * position.
+   * @param event The mouse event.
+   */
+  private _onIncrementalClick(event: MouseEvent): void {
+    if (this._model.selectionStart) {
+      this._model.selectionEnd = this._getMouseBufferCoords(event);
+    }
+  }
+
+  /**
+   * Performs a single click, resetting relevant state and setting the selection
+   * start position.
+   * @param event The mouse event.
+   */
+  private _onSingleClick(event: MouseEvent): void {
+    this._model.selectionStartLength = 0;
+    this._model.isSelectAllActive = false;
+    this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;
+
+    // Initialize the new selection
+    this._model.selectionStart = this._getMouseBufferCoords(event);
+    if (!this._model.selectionStart) {
+      return;
+    }
+    this._model.selectionEnd = undefined;
+
+    // Ensure the line exists
+    const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);
+    if (!line) {
+      return;
+    }
+
+    // Return early if the click event is not in the buffer (eg. in scroll bar)
+    if (line.length === this._model.selectionStart[0]) {
+      return;
+    }
+
+    // If the mouse is over the second half of a wide character, adjust the
+    // selection to cover the whole character
+    if (line.hasWidth(this._model.selectionStart[0]) === 0) {
+      this._model.selectionStart[0]++;
+    }
+  }
+
+  /**
+   * Performs a double click, selecting the current work.
+   * @param event The mouse event.
+   */
+  private _onDoubleClick(event: MouseEvent): void {
+    const coords = this._getMouseBufferCoords(event);
+    if (coords) {
+      this._activeSelectionMode = SelectionMode.WORD;
+      this._selectWordAt(coords, true);
+    }
+  }
+
+  /**
+   * Performs a triple click, selecting the current line and activating line
+   * select mode.
+   * @param event The mouse event.
+   */
+  private _onTripleClick(event: MouseEvent): void {
+    const coords = this._getMouseBufferCoords(event);
+    if (coords) {
+      this._activeSelectionMode = SelectionMode.LINE;
+      this._selectLineAt(coords[1]);
+    }
+  }
+
+  /**
+   * Returns whether the selection manager should operate in column select mode
+   * @param event the mouse or keyboard event
+   */
+  public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {
+    return event.altKey && !(Browser.isMac && this._optionsService.options.macOptionClickForcesSelection);
+  }
+
+  /**
+   * Handles the mousemove event when the mouse button is down, recording the
+   * end of the selection and refreshing the selection.
+   * @param event The mousemove event.
+   */
+  private _onMouseMove(event: MouseEvent): void {
+    // If the mousemove listener is active it means that a selection is
+    // currently being made, we should stop propagation to prevent mouse events
+    // to be sent to the pty.
+    event.stopImmediatePropagation();
+
+    // Do nothing if there is no selection start, this can happen if the first
+    // click in the terminal is an incremental click
+    if (!this._model.selectionStart) {
+      return;
+    }
+
+    // Record the previous position so we know whether to redraw the selection
+    // at the end.
+    const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
+
+    // Set the initial selection end based on the mouse coordinates
+    this._model.selectionEnd = this._getMouseBufferCoords(event);
+    if (!this._model.selectionEnd) {
+      this.refresh(true);
+      return;
+    }
+
+    // Select the entire line if line select mode is active.
+    if (this._activeSelectionMode === SelectionMode.LINE) {
+      if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
+        this._model.selectionEnd[0] = 0;
+      } else {
+        this._model.selectionEnd[0] = this._bufferService.cols;
+      }
+    } else if (this._activeSelectionMode === SelectionMode.WORD) {
+      this._selectToWordAt(this._model.selectionEnd);
+    }
+
+    // Determine the amount of scrolling that will happen.
+    this._dragScrollAmount = this._getMouseEventScrollAmount(event);
+
+    // If the cursor was above or below the viewport, make sure it's at the
+    // start or end of the viewport respectively. This should only happen when
+    // NOT in column select mode.
+    if (this._activeSelectionMode !== SelectionMode.COLUMN) {
+      if (this._dragScrollAmount > 0) {
+        this._model.selectionEnd[0] = this._bufferService.cols;
+      } else if (this._dragScrollAmount < 0) {
+        this._model.selectionEnd[0] = 0;
+      }
+    }
+
+    // If the character is a wide character include the cell to the right in the
+    // selection. Note that selections at the very end of the line will never
+    // have a character.
+    const buffer = this._bufferService.buffer;
+    if (this._model.selectionEnd[1] < buffer.lines.length) {
+      const line = buffer.lines.get(this._model.selectionEnd[1]);
+      if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {
+        this._model.selectionEnd[0]++;
+      }
+    }
+
+    // Only draw here if the selection changes.
+    if (!previousSelectionEnd ||
+      previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
+      previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
+      this.refresh(true);
+    }
+  }
+
+  /**
+   * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
+   * scrolling of the viewport.
+   */
+  private _dragScroll(): void {
+    if (!this._model.selectionEnd || !this._model.selectionStart) {
+      return;
+    }
+    if (this._dragScrollAmount) {
+      this._scrollLines(this._dragScrollAmount, false);
+      // Re-evaluate selection
+      // If the cursor was above or below the viewport, make sure it's at the
+      // start or end of the viewport respectively. This should only happen when
+      // NOT in column select mode.
+      const buffer = this._bufferService.buffer;
+      if (this._dragScrollAmount > 0) {
+        if (this._activeSelectionMode !== SelectionMode.COLUMN) {
+          this._model.selectionEnd[0] = this._bufferService.cols;
+        }
+        this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);
+      } else {
+        if (this._activeSelectionMode !== SelectionMode.COLUMN) {
+          this._model.selectionEnd[0] = 0;
+        }
+        this._model.selectionEnd[1] = buffer.ydisp;
+      }
+      this.refresh();
+    }
+  }
+
+  /**
+   * Handles the mouseup event, removing the mousedown listeners.
+   * @param event The mouseup event.
+   */
+  private _onMouseUp(event: MouseEvent): void {
+    const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;
+
+    this._removeMouseDownListeners();
+
+    if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME) {
+      if (event.altKey && this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {
+        const coordinates = this._mouseService.getCoords(
+          event,
+          this._element,
+          this._bufferService.cols,
+          this._bufferService.rows,
+          false
+        );
+        if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {
+          const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);
+          this._coreService.triggerDataEvent(sequence, true);
+        }
+      }
+    } else if (this.hasSelection) {
+      this._onSelectionChange.fire();
+    }
+  }
+
+  private _onBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {
+    this.clearSelection();
+    // Only adjust the selection on trim, shiftElements is rarely used (only in
+    // reverseIndex) and delete in a splice is only ever used when the same
+    // number of elements was just added. Given this is could actually be
+    // beneficial to leave the selection as is for these cases.
+    if (this._trimListener) {
+      this._trimListener.dispose();
+    }
+    this._trimListener = e.activeBuffer.lines.onTrim(amount => this._onTrim(amount));
+  }
+
+  /**
+   * Converts a viewport column to the character index on the buffer line, the
+   * latter takes into account wide characters.
+   * @param coords The coordinates to find the 2 index for.
+   */
+  private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, coords: [number, number]): number {
+    let charIndex = coords[0];
+    for (let i = 0; coords[0] >= i; i++) {
+      const length = bufferLine.loadCell(i, this._workCell).getChars().length;
+      if (this._workCell.getWidth() === 0) {
+        // Wide characters aren't included in the line string so decrement the
+        // index so the index is back on the wide character.
+        charIndex--;
+      } else if (length > 1 && coords[0] !== i) {
+        // Emojis take up multiple characters, so adjust accordingly. For these
+        // we don't want ot include the character at the column as we're
+        // returning the start index in the string, not the end index.
+        charIndex += length - 1;
+      }
+    }
+    return charIndex;
+  }
+
+  public setSelection(col: number, row: number, length: number): void {
+    this._model.clearSelection();
+    this._removeMouseDownListeners();
+    this._model.selectionStart = [col, row];
+    this._model.selectionStartLength = length;
+    this.refresh();
+  }
+
+  /**
+   * Gets positional information for the word at the coordinated specified.
+   * @param coords The coordinates to get the word at.
+   */
+  private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {
+    // Ensure coords are within viewport (eg. not within scroll bar)
+    if (coords[0] >= this._bufferService.cols) {
+      return undefined;
+    }
+
+    const buffer = this._bufferService.buffer;
+    const bufferLine = buffer.lines.get(coords[1]);
+    if (!bufferLine) {
+      return undefined;
+    }
+
+    const line = buffer.translateBufferLineToString(coords[1], false);
+
+    // Get actual index, taking into consideration wide characters
+    let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
+    let endIndex = startIndex;
+
+    // Record offset to be used later
+    const charOffset = coords[0] - startIndex;
+    let leftWideCharCount = 0;
+    let rightWideCharCount = 0;
+    let leftLongCharOffset = 0;
+    let rightLongCharOffset = 0;
+
+    if (line.charAt(startIndex) === ' ') {
+      // Expand until non-whitespace is hit
+      while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
+        startIndex--;
+      }
+      while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
+        endIndex++;
+      }
+    } else {
+      // Expand until whitespace is hit. This algorithm works by scanning left
+      // and right from the starting position, keeping both the index format
+      // (line) and the column format (bufferLine) in sync. When a wide
+      // character is hit, it is recorded and the column index is adjusted.
+      let startCol = coords[0];
+      let endCol = coords[0];
+
+      // Consider the initial position, skip it and increment the wide char
+      // variable
+      if (bufferLine.getWidth(startCol) === 0) {
+        leftWideCharCount++;
+        startCol--;
+      }
+      if (bufferLine.getWidth(endCol) === 2) {
+        rightWideCharCount++;
+        endCol++;
+      }
+
+      // Adjust the end index for characters whose length are > 1 (emojis)
+      const length = bufferLine.getString(endCol).length;
+      if (length > 1) {
+        rightLongCharOffset += length - 1;
+        endIndex += length - 1;
+      }
+
+      // Expand the string in both directions until a space is hit
+      while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {
+        bufferLine.loadCell(startCol - 1, this._workCell);
+        const length = this._workCell.getChars().length;
+        if (this._workCell.getWidth() === 0) {
+          // If the next character is a wide char, record it and skip the column
+          leftWideCharCount++;
+          startCol--;
+        } else if (length > 1) {
+          // If the next character's string is longer than 1 char (eg. emoji),
+          // adjust the index
+          leftLongCharOffset += length - 1;
+          startIndex -= length - 1;
+        }
+        startIndex--;
+        startCol--;
+      }
+      while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {
+        bufferLine.loadCell(endCol + 1, this._workCell);
+        const length = this._workCell.getChars().length;
+        if (this._workCell.getWidth() === 2) {
+          // If the next character is a wide char, record it and skip the column
+          rightWideCharCount++;
+          endCol++;
+        } else if (length > 1) {
+          // If the next character's string is longer than 1 char (eg. emoji),
+          // adjust the index
+          rightLongCharOffset += length - 1;
+          endIndex += length - 1;
+        }
+        endIndex++;
+        endCol++;
+      }
+    }
+
+    // Incremenet the end index so it is at the start of the next character
+    endIndex++;
+
+    // Calculate the start _column_, converting the the string indexes back to
+    // column coordinates.
+    let start =
+        startIndex // The index of the selection's start char in the line string
+        + charOffset // The difference between the initial char's column and index
+        - leftWideCharCount // The number of wide chars left of the initial char
+        + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
+
+    // Calculate the length in _columns_, converting the the string indexes back
+    // to column coordinates.
+    let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols
+        endIndex // The index of the selection's end char in the line string
+        - startIndex // The index of the selection's start char in the line string
+        + leftWideCharCount // The number of wide chars left of the initial char
+        + rightWideCharCount // The number of wide chars right of the initial char (inclusive)
+        - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
+        - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)
+
+    if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {
+      return undefined;
+    }
+
+    // Recurse upwards if the line is wrapped and the word wraps to the above line
+    if (followWrappedLinesAbove) {
+      if (start === 0 && bufferLine.getCodePoint(0) !== 32 /*' '*/) {
+        const previousBufferLine = buffer.lines.get(coords[1] - 1);
+        if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {
+          const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);
+          if (previousLineWordPosition) {
+            const offset = this._bufferService.cols - previousLineWordPosition.start;
+            start -= offset;
+            length += offset;
+          }
+        }
+      }
+    }
+
+    // Recurse downwards if the line is wrapped and the word wraps to the next line
+    if (followWrappedLinesBelow) {
+      if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {
+        const nextBufferLine = buffer.lines.get(coords[1] + 1);
+        if (nextBufferLine && nextBufferLine.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /*' '*/) {
+          const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);
+          if (nextLineWordPosition) {
+            length += nextLineWordPosition.length;
+          }
+        }
+      }
+    }
+
+    return { start, length };
+  }
+
+  /**
+   * Selects the word at the coordinates specified.
+   * @param coords The coordinates to get the word at.
+   * @param allowWhitespaceOnlySelection If whitespace should be selected
+   */
+  protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {
+    const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);
+    if (wordPosition) {
+      // Adjust negative start value
+      while (wordPosition.start < 0) {
+        wordPosition.start += this._bufferService.cols;
+        coords[1]--;
+      }
+      this._model.selectionStart = [wordPosition.start, coords[1]];
+      this._model.selectionStartLength = wordPosition.length;
+    }
+  }
+
+  /**
+   * Sets the selection end to the word at the coordinated specified.
+   * @param coords The coordinates to get the word at.
+   */
+  private _selectToWordAt(coords: [number, number]): void {
+    const wordPosition = this._getWordAt(coords, true);
+    if (wordPosition) {
+      let endRow = coords[1];
+
+      // Adjust negative start value
+      while (wordPosition.start < 0) {
+        wordPosition.start += this._bufferService.cols;
+        endRow--;
+      }
+
+      // Adjust wrapped length value, this only needs to happen when values are reversed as in that
+      // case we're interested in the start of the word, not the end
+      if (!this._model.areSelectionValuesReversed()) {
+        while (wordPosition.start + wordPosition.length > this._bufferService.cols) {
+          wordPosition.length -= this._bufferService.cols;
+          endRow++;
+        }
+      }
+
+      this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];
+    }
+  }
+
+  /**
+   * Gets whether the character is considered a word separator by the select
+   * word logic.
+   * @param char The character to check.
+   */
+  private _isCharWordSeparator(cell: CellData): boolean {
+    // Zero width characters are never separators as they are always to the
+    // right of wide characters
+    if (cell.getWidth() === 0) {
+      return false;
+    }
+    return this._optionsService.options.wordSeparator.indexOf(cell.getChars()) >= 0;
+  }
+
+  /**
+   * Selects the line specified.
+   * @param line The line index.
+   */
+  protected _selectLineAt(line: number): void {
+    const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);
+    this._model.selectionStart = [0, wrappedRange.first];
+    this._model.selectionEnd = [this._bufferService.cols, wrappedRange.last];
+    this._model.selectionStartLength = 0;
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/Services.ts b/node_modules/xterm/src/browser/services/Services.ts
new file mode 100644 (file)
index 0000000..2170a04
--- /dev/null
@@ -0,0 +1,95 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent } from 'common/EventEmitter';
+import { IRenderDimensions, IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { IColorSet } from 'browser/Types';
+import { ISelectionRedrawRequestEvent } from 'browser/selection/Types';
+import { createDecorator } from 'common/services/ServiceRegistry';
+import { IDisposable } from 'common/Types';
+
+export const ICharSizeService = createDecorator<ICharSizeService>('CharSizeService');
+export interface ICharSizeService {
+  serviceBrand: any;
+
+  readonly width: number;
+  readonly height: number;
+  readonly hasValidSize: boolean;
+
+  readonly onCharSizeChange: IEvent<void>;
+
+  measure(): void;
+}
+
+export const IMouseService = createDecorator<IMouseService>('MouseService');
+export interface IMouseService {
+  serviceBrand: any;
+
+  getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined;
+  getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined;
+}
+
+export const IRenderService = createDecorator<IRenderService>('RenderService');
+export interface IRenderService extends IDisposable {
+  serviceBrand: any;
+
+  onDimensionsChange: IEvent<IRenderDimensions>;
+  onRender: IEvent<{ start: number, end: number }>;
+  onRefreshRequest: IEvent<{ start: number, end: number }>;
+
+  dimensions: IRenderDimensions;
+
+  refreshRows(start: number, end: number): void;
+  resize(cols: number, rows: number): void;
+  changeOptions(): void;
+  setRenderer(renderer: IRenderer): void;
+  setColors(colors: IColorSet): void;
+  onDevicePixelRatioChange(): void;
+  onResize(cols: number, rows: number): void;
+  // TODO: Is this useful when we have onResize?
+  onCharSizeChanged(): void;
+  onBlur(): void;
+  onFocus(): void;
+  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;
+  onCursorMove(): void;
+  clear(): void;
+  registerCharacterJoiner(handler: CharacterJoinerHandler): number;
+  deregisterCharacterJoiner(joinerId: number): boolean;
+}
+
+export const ISelectionService = createDecorator<ISelectionService>('SelectionService');
+export interface ISelectionService {
+  serviceBrand: any;
+
+  readonly selectionText: string;
+  readonly hasSelection: boolean;
+  readonly selectionStart: [number, number] | undefined;
+  readonly selectionEnd: [number, number] | undefined;
+
+  readonly onLinuxMouseSelection: IEvent<string>;
+  readonly onRedrawRequest: IEvent<ISelectionRedrawRequestEvent>;
+  readonly onSelectionChange: IEvent<void>;
+
+  disable(): void;
+  enable(): void;
+  reset(): void;
+  setSelection(row: number, col: number, length: number): void;
+  selectAll(): void;
+  selectLines(start: number, end: number): void;
+  clearSelection(): void;
+  isClickInSelection(event: MouseEvent): boolean;
+  selectWordAtCursor(event: MouseEvent): void;
+  shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean;
+  shouldForceSelection(event: MouseEvent): boolean;
+  refresh(isLinuxMouseSelection?: boolean): void;
+  onMouseDown(event: MouseEvent): void;
+}
+
+export const ISoundService = createDecorator<ISoundService>('SoundService');
+export interface ISoundService {
+  serviceBrand: any;
+
+  playBellSound(): void;
+}
diff --git a/node_modules/xterm/src/browser/services/SoundService.ts b/node_modules/xterm/src/browser/services/SoundService.ts
new file mode 100644 (file)
index 0000000..1772c75
--- /dev/null
@@ -0,0 +1,63 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOptionsService } from 'common/services/Services';
+import { ISoundService } from 'browser/services/Services';
+
+export class SoundService implements ISoundService {
+  serviceBrand: any;
+
+  private static _audioContext: AudioContext;
+
+  static get audioContext(): AudioContext | null {
+    if (!SoundService._audioContext) {
+      const audioContextCtor: typeof AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;
+      if (!audioContextCtor) {
+        console.warn('Web Audio API is not supported by this browser. Consider upgrading to the latest version');
+        return null;
+      }
+      SoundService._audioContext = new audioContextCtor();
+    }
+    return SoundService._audioContext;
+  }
+
+  constructor(
+    @IOptionsService private _optionsService: IOptionsService
+  ) {
+  }
+
+  public playBellSound(): void {
+    const ctx = SoundService.audioContext;
+    if (!ctx) {
+      return;
+    }
+    const bellAudioSource = ctx.createBufferSource();
+    ctx.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)), (buffer) => {
+      bellAudioSource.buffer = buffer;
+      bellAudioSource.connect(ctx.destination);
+      bellAudioSource.start(0);
+    });
+  }
+
+  private _base64ToArrayBuffer(base64: string): ArrayBuffer {
+    const binaryString = window.atob(base64);
+    const len = binaryString.length;
+    const bytes = new Uint8Array(len);
+
+    for (let i = 0; i < len; i++) {
+      bytes[i] = binaryString.charCodeAt(i);
+    }
+
+    return bytes.buffer;
+  }
+
+  private _removeMimeType(dataURI: string): string {
+    // Split the input to get the mime-type and the data itself
+    const splitUri = dataURI.split(',');
+
+    // Return only the data
+    return splitUri[1];
+  }
+}
diff --git a/node_modules/xterm/src/browser/tsconfig.json b/node_modules/xterm/src/browser/tsconfig.json
new file mode 100644 (file)
index 0000000..7465bbd
--- /dev/null
@@ -0,0 +1,21 @@
+{
+  "extends": "../tsconfig-library-base",
+  "compilerOptions": {
+    "lib": [
+      "dom",
+      "es2015",
+    ],
+    "outDir": "../../out",
+    "types": [
+      "../../node_modules/@types/mocha"
+    ],
+    "baseUrl": "..",
+    "paths": {
+      "common/*": [ "./common/*" ]
+    }
+  },
+  "include": [ "./**/*" ],
+  "references": [
+    { "path": "../common" }
+  ]
+}
diff --git a/node_modules/xterm/src/common/CharWidth.ts b/node_modules/xterm/src/common/CharWidth.ts
new file mode 100644 (file)
index 0000000..24f5345
--- /dev/null
@@ -0,0 +1,171 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { fill } from 'common/TypedArrayUtils';
+
+export const wcwidth = (function(opts: {nul: number, control: number}): (ucs: number) => number {
+  // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c
+  // combining characters
+  const COMBINING_BMP = [
+    [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],
+    [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],
+    [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],
+    [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],
+    [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],
+    [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],
+    [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],
+    [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],
+    [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],
+    [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],
+    [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],
+    [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],
+    [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],
+    [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],
+    [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],
+    [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],
+    [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],
+    [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],
+    [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],
+    [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],
+    [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],
+    [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],
+    [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],
+    [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],
+    [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],
+    [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],
+    [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],
+    [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],
+    [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],
+    [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],
+    [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],
+    [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],
+    [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],
+    [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],
+    [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],
+    [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],
+    [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],
+    [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],
+    [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],
+    [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],
+    [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],
+    [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],
+    [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB]
+  ];
+  const COMBINING_HIGH = [
+    [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],
+    [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],
+    [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],
+    [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],
+    [0xE0100, 0xE01EF]
+  ];
+  // binary search
+  function bisearch(ucs: number, data: number[][]): boolean {
+    let min = 0;
+    let max = data.length - 1;
+    let mid;
+    if (ucs < data[0][0] || ucs > data[max][1]) {
+      return false;
+    }
+    while (max >= min) {
+      mid = (min + max) >> 1;
+      if (ucs > data[mid][1]) {
+        min = mid + 1;
+      } else if (ucs < data[mid][0]) {
+        max = mid - 1;
+      } else {
+        return true;
+      }
+    }
+    return false;
+  }
+  function wcwidthHigh(ucs: number): 0 | 1 | 2 {
+    if (bisearch(ucs, COMBINING_HIGH)) {
+      return 0;
+    }
+    if ((ucs >= 0x20000 && ucs <= 0x2fffd) || (ucs >= 0x30000 && ucs <= 0x3fffd)) {
+      return 2;
+    }
+    return 1;
+  }
+  const control = opts.control | 0;
+
+  // create lookup table for BMP plane
+  const table = new Uint8Array(65536);
+  fill(table, 1);
+  table[0] = opts.nul;
+  // control chars
+  fill(table, opts.control, 1, 32);
+  fill(table, opts.control, 0x7f, 0xa0);
+
+  // apply wide char rules first
+  // wide chars
+  fill(table, 2, 0x1100, 0x1160);
+  table[0x2329] = 2;
+  table[0x232a] = 2;
+  fill(table, 2, 0x2e80, 0xa4d0);
+  table[0x303f] = 1;  // wrongly in last line
+
+  fill(table, 2, 0xac00, 0xd7a4);
+  fill(table, 2, 0xf900, 0xfb00);
+  fill(table, 2, 0xfe10, 0xfe1a);
+  fill(table, 2, 0xfe30, 0xfe70);
+  fill(table, 2, 0xff00, 0xff61);
+  fill(table, 2, 0xffe0, 0xffe7);
+
+  // apply combining last to ensure we overwrite
+  // wrongly wide set chars:
+  //    the original algo evals combining first and falls
+  //    through to wide check so we simply do here the opposite
+  // combining 0
+  for (let r = 0; r < COMBINING_BMP.length; ++r) {
+    fill(table, 0, COMBINING_BMP[r][0], COMBINING_BMP[r][1] + 1);
+  }
+
+  return function (num: number): number {
+    if (num < 32) {
+      return control | 0;
+    }
+    if (num < 127) {
+      return 1;
+    }
+    if (num < 65536) {
+      return table[num];
+    }
+    // do a full search for high codepoints
+    return wcwidthHigh(num);
+  };
+})({nul: 0, control: 0});  // configurable options
+
+/**
+ * Get the terminal cell width for a string.
+ */
+export function getStringCellWidth(s: string): number {
+  let result = 0;
+  const length = s.length;
+  for (let i = 0; i < length; ++i) {
+    let code = s.charCodeAt(i);
+    // surrogate pair first
+    if (0xD800 <= code && code <= 0xDBFF) {
+      if (++i >= length) {
+        // this should not happen with strings retrieved from
+        // Buffer.translateToString as it converts from UTF-32
+        // and therefore always should contain the second part
+        // for any other string we still have to handle it somehow:
+        // simply treat the lonely surrogate first as a single char (UCS-2 behavior)
+        return result + wcwidth(code);
+      }
+      const second = s.charCodeAt(i);
+      // convert surrogate pair to high codepoint only for valid second part (UTF-16)
+      // otherwise treat them independently (UCS-2 behavior)
+      if (0xDC00 <= second && second <= 0xDFFF) {
+        code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+      } else {
+        result += wcwidth(second);
+      }
+    }
+    result += wcwidth(code);
+  }
+  return result;
+}
diff --git a/node_modules/xterm/src/common/CircularList.ts b/node_modules/xterm/src/common/CircularList.ts
new file mode 100644 (file)
index 0000000..d4ad3fc
--- /dev/null
@@ -0,0 +1,235 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICircularList } from 'common/Types';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+
+export interface IInsertEvent {
+  index: number;
+  amount: number;
+}
+
+export interface IDeleteEvent {
+  index: number;
+  amount: number;
+}
+
+/**
+ * Represents a circular list; a list with a maximum size that wraps around when push is called,
+ * overriding values at the start of the list.
+ */
+export class CircularList<T> implements ICircularList<T> {
+  protected _array: (T | undefined)[];
+  private _startIndex: number;
+  private _length: number;
+
+  public onDeleteEmitter = new EventEmitter<IDeleteEvent>();
+  public get onDelete(): IEvent<IDeleteEvent> { return this.onDeleteEmitter.event; }
+  public onInsertEmitter = new EventEmitter<IInsertEvent>();
+  public get onInsert(): IEvent<IInsertEvent> { return this.onInsertEmitter.event; }
+  public onTrimEmitter = new EventEmitter<number>();
+  public get onTrim(): IEvent<number> { return this.onTrimEmitter.event; }
+
+  constructor(
+    private _maxLength: number
+  ) {
+    this._array = new Array<T>(this._maxLength);
+    this._startIndex = 0;
+    this._length = 0;
+  }
+
+  public get maxLength(): number {
+    return this._maxLength;
+  }
+
+  public set maxLength(newMaxLength: number) {
+    // There was no change in maxLength, return early.
+    if (this._maxLength === newMaxLength) {
+      return;
+    }
+
+    // Reconstruct array, starting at index 0. Only transfer values from the
+    // indexes 0 to length.
+    const newArray = new Array<T | undefined>(newMaxLength);
+    for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {
+      newArray[i] = this._array[this._getCyclicIndex(i)];
+    }
+    this._array = newArray;
+    this._maxLength = newMaxLength;
+    this._startIndex = 0;
+  }
+
+  public get length(): number {
+    return this._length;
+  }
+
+  public set length(newLength: number) {
+    if (newLength > this._length) {
+      for (let i = this._length; i < newLength; i++) {
+        this._array[i] = undefined;
+      }
+    }
+    this._length = newLength;
+  }
+
+  /**
+   * Gets the value at an index.
+   *
+   * Note that for performance reasons there is no bounds checking here, the index reference is
+   * circular so this should always return a value and never throw.
+   * @param index The index of the value to get.
+   * @return The value corresponding to the index.
+   */
+  public get(index: number): T | undefined {
+    return this._array[this._getCyclicIndex(index)];
+  }
+
+  /**
+   * Sets the value at an index.
+   *
+   * Note that for performance reasons there is no bounds checking here, the index reference is
+   * circular so this should always return a value and never throw.
+   * @param index The index to set.
+   * @param value The value to set.
+   */
+  public set(index: number, value: T | undefined): void {
+    this._array[this._getCyclicIndex(index)] = value;
+  }
+
+  /**
+   * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0
+   * if the maximum length is reached.
+   * @param value The value to push onto the list.
+   */
+  public push(value: T): void {
+    this._array[this._getCyclicIndex(this._length)] = value;
+    if (this._length === this._maxLength) {
+      this._startIndex = ++this._startIndex % this._maxLength;
+      this.onTrimEmitter.fire(1);
+    } else {
+      this._length++;
+    }
+  }
+
+  /**
+   * Advance ringbuffer index and return current element for recycling.
+   * Note: The buffer must be full for this method to work.
+   * @throws When the buffer is not full.
+   */
+  public recycle(): T {
+    if (this._length !== this._maxLength) {
+      throw new Error('Can only recycle when the buffer is full');
+    }
+    this._startIndex = ++this._startIndex % this._maxLength;
+    this.onTrimEmitter.fire(1);
+    return this._array[this._getCyclicIndex(this._length - 1)]!;
+  }
+
+  /**
+   * Ringbuffer is at max length.
+   */
+  public get isFull(): boolean {
+    return this._length === this._maxLength;
+  }
+
+  /**
+   * Removes and returns the last value on the list.
+   * @return The popped value.
+   */
+  public pop(): T | undefined {
+    return this._array[this._getCyclicIndex(this._length-- - 1)];
+  }
+
+  /**
+   * Deletes and/or inserts items at a particular index (in that order). Unlike
+   * Array.prototype.splice, this operation does not return the deleted items as a new array in
+   * order to save creating a new array. Note that this operation may shift all values in the list
+   * in the worst case.
+   * @param start The index to delete and/or insert.
+   * @param deleteCount The number of elements to delete.
+   * @param items The items to insert.
+   */
+  public splice(start: number, deleteCount: number, ...items: T[]): void {
+    // Delete items
+    if (deleteCount) {
+      for (let i = start; i < this._length - deleteCount; i++) {
+        this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];
+      }
+      this._length -= deleteCount;
+    }
+
+    // Add items
+    for (let i = this._length - 1; i >= start; i--) {
+      this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];
+    }
+    for (let i = 0; i < items.length; i++) {
+      this._array[this._getCyclicIndex(start + i)] = items[i];
+    }
+
+    // Adjust length as needed
+    if (this._length + items.length > this._maxLength) {
+      const countToTrim = (this._length + items.length) - this._maxLength;
+      this._startIndex += countToTrim;
+      this._length = this._maxLength;
+      this.onTrimEmitter.fire(countToTrim);
+    } else {
+      this._length += items.length;
+    }
+  }
+
+  /**
+   * Trims a number of items from the start of the list.
+   * @param count The number of items to remove.
+   */
+  public trimStart(count: number): void {
+    if (count > this._length) {
+      count = this._length;
+    }
+    this._startIndex += count;
+    this._length -= count;
+    this.onTrimEmitter.fire(count);
+  }
+
+  public shiftElements(start: number, count: number, offset: number): void {
+    if (count <= 0) {
+      return;
+    }
+    if (start < 0 || start >= this._length) {
+      throw new Error('start argument out of range');
+    }
+    if (start + offset < 0) {
+      throw new Error('Cannot shift elements in list beyond index 0');
+    }
+
+    if (offset > 0) {
+      for (let i = count - 1; i >= 0; i--) {
+        this.set(start + i + offset, this.get(start + i));
+      }
+      const expandListBy = (start + count + offset) - this._length;
+      if (expandListBy > 0) {
+        this._length += expandListBy;
+        while (this._length > this._maxLength) {
+          this._length--;
+          this._startIndex++;
+          this.onTrimEmitter.fire(1);
+        }
+      }
+    } else {
+      for (let i = 0; i < count; i++) {
+        this.set(start + i + offset, this.get(start + i));
+      }
+    }
+  }
+
+  /**
+   * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the
+   * backing array to get the element associated with the regular index.
+   * @param index The regular index.
+   * @returns The cyclic index.
+   */
+  private _getCyclicIndex(index: number): number {
+    return (this._startIndex + index) % this._maxLength;
+  }
+}
diff --git a/node_modules/xterm/src/common/Clone.ts b/node_modules/xterm/src/common/Clone.ts
new file mode 100644 (file)
index 0000000..51c5aba
--- /dev/null
@@ -0,0 +1,23 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/*
+ * A simple utility for cloning values
+ */
+export function clone<T>(val: T, depth: number = 5): T {
+  if (typeof val !== 'object') {
+    return val;
+  }
+
+  // If we're cloning an array, use an array as the base, otherwise use an object
+  const clonedObject: any = Array.isArray(val) ? [] : {};
+
+  for (const key in val) {
+    // Recursively clone eack item unless we're at the maximum depth
+    clonedObject[key] = depth <= 1 ? val[key] : (val[key] ? clone(val[key], depth - 1) : val[key]);
+  }
+
+  return clonedObject as T;
+}
diff --git a/node_modules/xterm/src/common/EventEmitter.ts b/node_modules/xterm/src/common/EventEmitter.ts
new file mode 100644 (file)
index 0000000..34ac190
--- /dev/null
@@ -0,0 +1,54 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+interface IListener<T> {
+  (e: T): void;
+}
+
+export interface IEvent<T> {
+  (listener: (e: T) => any): IDisposable;
+}
+
+export interface IEventEmitter<T> {
+  event: IEvent<T>;
+  fire(data: T): void;
+}
+
+export class EventEmitter<T> implements IEventEmitter<T> {
+  private _listeners: IListener<T>[] = [];
+  private _event?: IEvent<T>;
+
+  public get event(): IEvent<T> {
+    if (!this._event) {
+      this._event = (listener: (e: T) => any) => {
+        this._listeners.push(listener);
+        const disposable = {
+          dispose: () => {
+            for (let i = 0; i < this._listeners.length; i++) {
+              if (this._listeners[i] === listener) {
+                this._listeners.splice(i, 1);
+                return;
+              }
+            }
+          }
+        };
+        return disposable;
+      };
+    }
+    return this._event;
+  }
+
+  public fire(data: T): void {
+    const queue: IListener<T>[] = [];
+    for (let i = 0; i < this._listeners.length; i++) {
+      queue.push(this._listeners[i]);
+    }
+    for (let i = 0; i < queue.length; i++) {
+      queue[i].call(undefined, data);
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/Lifecycle.ts b/node_modules/xterm/src/common/Lifecycle.ts
new file mode 100644 (file)
index 0000000..ad1afa1
--- /dev/null
@@ -0,0 +1,47 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+/**
+ * A base class that can be extended to provide convenience methods for managing the lifecycle of an
+ * object and its components.
+ */
+export abstract class Disposable implements IDisposable {
+  protected _disposables: IDisposable[] = [];
+  protected _isDisposed: boolean = false;
+
+  constructor() {
+  }
+
+  /**
+   * Disposes the object, triggering the `dispose` method on all registered IDisposables.
+   */
+  public dispose(): void {
+    this._isDisposed = true;
+    this._disposables.forEach(d => d.dispose());
+    this._disposables.length = 0;
+  }
+
+  /**
+   * Registers a disposable object.
+   * @param d The disposable to register.
+   */
+  public register<T extends IDisposable>(d: T): void {
+    this._disposables.push(d);
+  }
+
+  /**
+   * Unregisters a disposable object if it has been registered, if not do
+   * nothing.
+   * @param d The disposable to unregister.
+   */
+  public unregister<T extends IDisposable>(d: T): void {
+    const index = this._disposables.indexOf(d);
+    if (index !== -1) {
+      this._disposables.splice(index, 1);
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/Platform.ts b/node_modules/xterm/src/common/Platform.ts
new file mode 100644 (file)
index 0000000..aae06c7
--- /dev/null
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+interface INavigator {
+  userAgent: string;
+  language: string;
+  platform: string;
+}
+
+// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but
+// we want this module to live in common.
+declare const navigator: INavigator;
+
+const isNode = (typeof navigator === 'undefined') ? true : false;
+const userAgent = (isNode) ? 'node' : navigator.userAgent;
+const platform = (isNode) ? 'node' : navigator.platform;
+
+export const isFirefox = !!~userAgent.indexOf('Firefox');
+export const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent);
+
+// Find the users platform. We use this to interpret the meta key
+// and ISO third level shifts.
+// http://stackoverflow.com/q/19877924/577598
+export const isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform);
+export const isIpad = platform === 'iPad';
+export const isIphone = platform === 'iPhone';
+export const isWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform);
+export const isLinux = platform.indexOf('Linux') >= 0;
+
+/**
+ * Return if the given array contains the given element
+ * @param arr The array to search for the given element.
+ * @param el The element to look for into the array
+ */
+function contains(arr: any[], el: any): boolean {
+  return arr.indexOf(el) >= 0;
+}
diff --git a/node_modules/xterm/src/common/TypedArrayUtils.ts b/node_modules/xterm/src/common/TypedArrayUtils.ts
new file mode 100644 (file)
index 0000000..5469983
--- /dev/null
@@ -0,0 +1,52 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export type TypedArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray
+  | Int8Array | Int16Array | Int32Array
+  | Float32Array | Float64Array;
+
+
+/**
+ * polyfill for TypedArray.fill
+ * This is needed to support .fill in all safari versions and IE 11.
+ */
+export function fill<T extends TypedArray>(array: T, value: number, start?: number, end?: number): T {
+  // all modern engines that support .fill
+  if (array.fill) {
+    return array.fill(value, start, end) as T;
+  }
+  return fillFallback(array, value, start, end);
+}
+
+export function fillFallback<T extends TypedArray>(array: T, value: number, start: number = 0, end: number = array.length): T {
+  // safari and IE 11
+  // since IE 11 does not support Array.prototype.fill either
+  // we cannot use the suggested polyfill from MDN
+  // instead we simply fall back to looping
+  if (start >= array.length) {
+    return array;
+  }
+  start = (array.length + start) % array.length;
+  if (end >= array.length) {
+    end = array.length;
+  } else {
+    end = (array.length + end) % array.length;
+  }
+  for (let i = start; i < end; ++i) {
+    array[i] = value;
+  }
+  return array;
+}
+
+/**
+ * Concat two typed arrays `a` and `b`.
+ * Returns a new typed array.
+ */
+export function concat<T extends TypedArray>(a: T, b: T): T {
+  const result = new (a.constructor as any)(a.length + b.length);
+  result.set(a);
+  result.set(b, a.length);
+  return result;
+}
diff --git a/node_modules/xterm/src/common/Types.d.ts b/node_modules/xterm/src/common/Types.d.ts
new file mode 100644 (file)
index 0000000..2f74203
--- /dev/null
@@ -0,0 +1,253 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent, IEventEmitter } from 'common/EventEmitter';
+import { IDeleteEvent, IInsertEvent } from 'common/CircularList';
+
+export interface IDisposable {
+  dispose(): void;
+}
+
+export type XtermListener = (...args: any[]) => void;
+
+/**
+ * A keyboard event interface which does not depend on the DOM, KeyboardEvent implicitly extends
+ * this event.
+ */
+export interface IKeyboardEvent {
+  altKey: boolean;
+  ctrlKey: boolean;
+  shiftKey: boolean;
+  metaKey: boolean;
+  keyCode: number;
+  key: string;
+  type: string;
+}
+
+export interface ICircularList<T> {
+  length: number;
+  maxLength: number;
+  isFull: boolean;
+
+  onDeleteEmitter: IEventEmitter<IDeleteEvent>;
+  onDelete: IEvent<IDeleteEvent>;
+  onInsertEmitter: IEventEmitter<IInsertEvent>;
+  onInsert: IEvent<IInsertEvent>;
+  onTrimEmitter: IEventEmitter<number>;
+  onTrim: IEvent<number>;
+
+  get(index: number): T | undefined;
+  set(index: number, value: T): void;
+  push(value: T): void;
+  recycle(): T | undefined;
+  pop(): T | undefined;
+  splice(start: number, deleteCount: number, ...items: T[]): void;
+  trimStart(count: number): void;
+  shiftElements(start: number, count: number, offset: number): void;
+}
+
+export const enum KeyboardResultType {
+  SEND_KEY,
+  SELECT_ALL,
+  PAGE_UP,
+  PAGE_DOWN
+}
+
+export interface IKeyboardResult {
+  type: KeyboardResultType;
+  cancel: boolean;
+  key: string | undefined;
+}
+
+export interface ICharset {
+  [key: string]: string;
+}
+
+export type CharData = [number, string, number, number];
+export type IColorRGB = [number, number, number];
+
+/** Attribute data */
+export interface IAttributeData {
+  fg: number;
+  bg: number;
+
+  clone(): IAttributeData;
+
+  // flags
+  isInverse(): number;
+  isBold(): number;
+  isUnderline(): number;
+  isBlink(): number;
+  isInvisible(): number;
+  isItalic(): number;
+  isDim(): number;
+
+  // color modes
+  getFgColorMode(): number;
+  getBgColorMode(): number;
+  isFgRGB(): boolean;
+  isBgRGB(): boolean;
+  isFgPalette(): boolean;
+  isBgPalette(): boolean;
+  isFgDefault(): boolean;
+  isBgDefault(): boolean;
+
+  // colors
+  getFgColor(): number;
+  getBgColor(): number;
+}
+
+/** Cell data */
+export interface ICellData extends IAttributeData {
+  content: number;
+  combinedData: string;
+  isCombined(): number;
+  getWidth(): number;
+  getChars(): string;
+  getCode(): number;
+  setFromCharData(value: CharData): void;
+  getAsCharData(): CharData;
+}
+
+/**
+ * Interface for a line in the terminal buffer.
+ */
+export interface IBufferLine {
+  length: number;
+  isWrapped: boolean;
+  get(index: number): CharData;
+  set(index: number, value: CharData): void;
+  loadCell(index: number, cell: ICellData): ICellData;
+  setCell(index: number, cell: ICellData): void;
+  setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number): void;
+  addCodepointToCell(index: number, codePoint: number): void;
+  insertCells(pos: number, n: number, ch: ICellData): void;
+  deleteCells(pos: number, n: number, fill: ICellData): void;
+  replaceCells(start: number, end: number, fill: ICellData): void;
+  resize(cols: number, fill: ICellData): void;
+  fill(fillCellData: ICellData): void;
+  copyFrom(line: IBufferLine): void;
+  clone(): IBufferLine;
+  getTrimmedLength(): number;
+  translateToString(trimRight?: boolean, startCol?: number, endCol?: number): string;
+
+  /* direct access to cell attrs */
+  getWidth(index: number): number;
+  hasWidth(index: number): number;
+  getFg(index: number): number;
+  getBg(index: number): number;
+  hasContent(index: number): number;
+  getCodePoint(index: number): number;
+  isCombined(index: number): number;
+  getString(index: number): string;
+}
+
+export interface IMarker extends IDisposable {
+  readonly id: number;
+  readonly isDisposed: boolean;
+  readonly line: number;
+}
+
+export interface IDecPrivateModes {
+  applicationCursorKeys: boolean;
+}
+
+export interface IRowRange {
+  start: number;
+  end: number;
+}
+
+/**
+ * Interface for mouse events in the core.
+ */
+export const enum CoreMouseButton {
+  LEFT = 0,
+  MIDDLE = 1,
+  RIGHT = 2,
+  NONE = 3,
+  WHEEL = 4,
+  // additional buttons 1..8
+  // untested!
+  AUX1 = 8,
+  AUX2 = 9,
+  AUX3 = 10,
+  AUX4 = 11,
+  AUX5 = 12,
+  AUX6 = 13,
+  AUX7 = 14,
+  AUX8 = 15
+}
+
+export const enum CoreMouseAction {
+  UP = 0,     // buttons, wheel
+  DOWN = 1,   // buttons, wheel
+  LEFT = 2,   // wheel only
+  RIGHT = 3,  // wheel only
+  MOVE = 32   // buttons only
+}
+
+export interface ICoreMouseEvent {
+  /** column (zero based). */
+  col: number;
+  /** row (zero based). */
+  row: number;
+  /**
+   * Button the action occured. Due to restrictions of the tracking protocols
+   * it is not possible to report multiple buttons at once.
+   * Wheel is treated as a button.
+   * There are invalid combinations of buttons and actions possible
+   * (like move + wheel), those are silently ignored by the CoreMouseService.
+   */
+  button: CoreMouseButton;
+  action: CoreMouseAction;
+  /**
+   * Modifier states.
+   * Protocols will add/ignore those based on specific restrictions.
+   */
+  ctrl?: boolean;
+  alt?: boolean;
+  shift?: boolean;
+}
+
+/**
+ * CoreMouseEventType
+ * To be reported to the browser component which events a mouse
+ * protocol wants to be catched and forwarded as an ICoreMouseEvent
+ * to CoreMouseService.
+ */
+export const enum CoreMouseEventType {
+  NONE = 0,
+  /** any mousedown event */
+  DOWN = 1,
+  /** any mouseup event */
+  UP = 2,
+  /** any mousemove event while a button is held */
+  DRAG = 4,
+  /** any mousemove event without a button */
+  MOVE = 8,
+  /** any wheel event */
+  WHEEL = 16
+}
+
+/**
+ * Mouse protocol interface.
+ * A mouse protocol can be registered and activated at the CoreMouseService.
+ * `events` should contain a list of needed events as a hint for the browser component
+ * to install/remove the appropriate event handlers.
+ * `restrict` applies further protocol specific restrictions like not allowed
+ * modifiers or filtering invalid event types.
+ */
+export interface ICoreMouseProtocol {
+  events: CoreMouseEventType;
+  restrict: (e: ICoreMouseEvent) => boolean;
+}
+
+/**
+ * CoreMouseEncoding
+ * The tracking encoding can be registered and activated at the CoreMouseService.
+ * If a ICoreMouseEvent passes all procotol restrictions it will be encoded
+ * with the active encoding and sent out.
+ */
+export type CoreMouseEncoding = (event: ICoreMouseEvent) => string;
diff --git a/node_modules/xterm/src/common/buffer/AttributeData.ts b/node_modules/xterm/src/common/buffer/AttributeData.ts
new file mode 100644 (file)
index 0000000..0e7e270
--- /dev/null
@@ -0,0 +1,68 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IAttributeData, IColorRGB } from 'common/Types';
+import { Attributes, FgFlags, BgFlags } from 'common/buffer/Constants';
+
+export class AttributeData implements IAttributeData {
+  static toColorRGB(value: number): IColorRGB {
+    return [
+      value >>> Attributes.RED_SHIFT & 255,
+      value >>> Attributes.GREEN_SHIFT & 255,
+      value & 255
+    ];
+  }
+  static fromColorRGB(value: IColorRGB): number {
+    return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255;
+  }
+
+  public clone(): IAttributeData {
+    const newObj = new AttributeData();
+    newObj.fg = this.fg;
+    newObj.bg = this.bg;
+    return newObj;
+  }
+
+  // data
+  public fg: number = 0;
+  public bg: number = 0;
+
+  // flags
+  public isInverse(): number   { return this.fg & FgFlags.INVERSE; }
+  public isBold(): number      { return this.fg & FgFlags.BOLD; }
+  public isUnderline(): number { return this.fg & FgFlags.UNDERLINE; }
+  public isBlink(): number     { return this.fg & FgFlags.BLINK; }
+  public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; }
+  public isItalic(): number    { return this.bg & BgFlags.ITALIC; }
+  public isDim(): number       { return this.bg & BgFlags.DIM; }
+
+  // color modes
+  public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; }
+  public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; }
+  public isFgRGB(): boolean       { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; }
+  public isBgRGB(): boolean       { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; }
+  public isFgPalette(): boolean   { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; }
+  public isBgPalette(): boolean   { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; }
+  public isFgDefault(): boolean   { return (this.fg & Attributes.CM_MASK) === 0; }
+  public isBgDefault(): boolean   { return (this.bg & Attributes.CM_MASK) === 0; }
+
+  // colors
+  public getFgColor(): number {
+    switch (this.fg & Attributes.CM_MASK) {
+      case Attributes.CM_P16:
+      case Attributes.CM_P256:  return this.fg & Attributes.PCOLOR_MASK;
+      case Attributes.CM_RGB:   return this.fg & Attributes.RGB_MASK;
+      default:                  return -1;  // CM_DEFAULT defaults to -1
+    }
+  }
+  public getBgColor(): number {
+    switch (this.bg & Attributes.CM_MASK) {
+      case Attributes.CM_P16:
+      case Attributes.CM_P256:  return this.bg & Attributes.PCOLOR_MASK;
+      case Attributes.CM_RGB:   return this.bg & Attributes.RGB_MASK;
+      default:                  return -1;  // CM_DEFAULT defaults to -1
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/Buffer.ts b/node_modules/xterm/src/common/buffer/Buffer.ts
new file mode 100644 (file)
index 0000000..152bab7
--- /dev/null
@@ -0,0 +1,671 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { CircularList, IInsertEvent } from 'common/CircularList';
+import { IBuffer, BufferIndex, IBufferStringIterator, IBufferStringIteratorResult } from 'common/buffer/Types';
+import { IBufferLine, ICellData, IAttributeData, ICharset } from 'common/Types';
+import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
+import { CellData } from 'common/buffer/CellData';
+import { NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_CHAR_INDEX } from 'common/buffer/Constants';
+import { reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths, getWrappedLineTrimmedLength } from 'common/buffer/BufferReflow';
+import { Marker } from 'common/buffer/Marker';
+import { IOptionsService, IBufferService } from 'common/services/Services';
+import { DEFAULT_CHARSET } from 'common/data/Charsets';
+
+export const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1
+
+/**
+ * This class represents a terminal buffer (an internal state of the terminal), where the
+ * following information is stored (in high-level):
+ *   - text content of this particular buffer
+ *   - cursor position
+ *   - scroll position
+ */
+export class Buffer implements IBuffer {
+  public lines: CircularList<IBufferLine>;
+  public ydisp: number = 0;
+  public ybase: number = 0;
+  public y: number = 0;
+  public x: number = 0;
+  public scrollBottom: number;
+  public scrollTop: number;
+  // TODO: Type me
+  public tabs: any;
+  public savedY: number = 0;
+  public savedX: number = 0;
+  public savedCurAttrData = DEFAULT_ATTR_DATA.clone();
+  public savedCharset: ICharset | null = DEFAULT_CHARSET;
+  public markers: Marker[] = [];
+  private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);
+  private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]);
+  private _cols: number;
+  private _rows: number;
+
+  constructor(
+    private _hasScrollback: boolean,
+    private _optionsService: IOptionsService,
+    private _bufferService: IBufferService
+  ) {
+    this._cols = this._bufferService.cols;
+    this._rows = this._bufferService.rows;
+    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));
+    this.scrollTop = 0;
+    this.scrollBottom = this._rows - 1;
+    this.setupTabStops();
+  }
+
+  public getNullCell(attr?: IAttributeData): ICellData {
+    if (attr) {
+      this._nullCell.fg = attr.fg;
+      this._nullCell.bg = attr.bg;
+    } else {
+      this._nullCell.fg = 0;
+      this._nullCell.bg = 0;
+    }
+    return this._nullCell;
+  }
+
+  public getWhitespaceCell(attr?: IAttributeData): ICellData {
+    if (attr) {
+      this._whitespaceCell.fg = attr.fg;
+      this._whitespaceCell.bg = attr.bg;
+    } else {
+      this._whitespaceCell.fg = 0;
+      this._whitespaceCell.bg = 0;
+    }
+    return this._whitespaceCell;
+  }
+
+  public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine {
+    return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped);
+  }
+
+  public get hasScrollback(): boolean {
+    return this._hasScrollback && this.lines.maxLength > this._rows;
+  }
+
+  public get isCursorInViewport(): boolean {
+    const absoluteY = this.ybase + this.y;
+    const relativeY = absoluteY - this.ydisp;
+    return (relativeY >= 0 && relativeY < this._rows);
+  }
+
+  /**
+   * Gets the correct buffer length based on the rows provided, the terminal's
+   * scrollback and whether this buffer is flagged to have scrollback or not.
+   * @param rows The terminal rows to use in the calculation.
+   */
+  private _getCorrectBufferLength(rows: number): number {
+    if (!this._hasScrollback) {
+      return rows;
+    }
+
+    const correctBufferLength = rows + this._optionsService.options.scrollback;
+
+    return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength;
+  }
+
+  /**
+   * Fills the buffer's viewport with blank lines.
+   */
+  public fillViewportRows(fillAttr?: IAttributeData): void {
+    if (this.lines.length === 0) {
+      if (fillAttr === undefined) {
+        fillAttr = DEFAULT_ATTR_DATA;
+      }
+      let i = this._rows;
+      while (i--) {
+        this.lines.push(this.getBlankLine(fillAttr));
+      }
+    }
+  }
+
+  /**
+   * Clears the buffer to it's initial state, discarding all previous data.
+   */
+  public clear(): void {
+    this.ydisp = 0;
+    this.ybase = 0;
+    this.y = 0;
+    this.x = 0;
+    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));
+    this.scrollTop = 0;
+    this.scrollBottom = this._rows - 1;
+    this.setupTabStops();
+  }
+
+  /**
+   * Resizes the buffer, adjusting its data accordingly.
+   * @param newCols The new number of columns.
+   * @param newRows The new number of rows.
+   */
+  public resize(newCols: number, newRows: number): void {
+    // store reference to null cell with default attrs
+    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);
+
+    // Increase max length if needed before adjustments to allow space to fill
+    // as required.
+    const newMaxLength = this._getCorrectBufferLength(newRows);
+    if (newMaxLength > this.lines.maxLength) {
+      this.lines.maxLength = newMaxLength;
+    }
+
+    // The following adjustments should only happen if the buffer has been
+    // initialized/filled.
+    if (this.lines.length > 0) {
+      // Deal with columns increasing (reducing needs to happen after reflow)
+      if (this._cols < newCols) {
+        for (let i = 0; i < this.lines.length; i++) {
+          this.lines.get(i)!.resize(newCols, nullCell);
+        }
+      }
+
+      // Resize rows in both directions as needed
+      let addToY = 0;
+      if (this._rows < newRows) {
+        for (let y = this._rows; y < newRows; y++) {
+          if (this.lines.length < newRows + this.ybase) {
+            if (this._optionsService.options.windowsMode) {
+              // Just add the new missing rows on Windows as conpty reprints the screen with it's
+              // view of the world. Once a line enters scrollback for conpty it remains there
+              this.lines.push(new BufferLine(newCols, nullCell));
+            } else {
+              if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
+                // There is room above the buffer and there are no empty elements below the line,
+                // scroll up
+                this.ybase--;
+                addToY++;
+                if (this.ydisp > 0) {
+                  // Viewport is at the top of the buffer, must increase downwards
+                  this.ydisp--;
+                }
+              } else {
+                // Add a blank line if there is no buffer left at the top to scroll to, or if there
+                // are blank lines after the cursor
+                this.lines.push(new BufferLine(newCols, nullCell));
+              }
+            }
+          }
+        }
+      } else { // (this._rows >= newRows)
+        for (let y = this._rows; y > newRows; y--) {
+          if (this.lines.length > newRows + this.ybase) {
+            if (this.lines.length > this.ybase + this.y + 1) {
+              // The line is a blank line below the cursor, remove it
+              this.lines.pop();
+            } else {
+              // The line is the cursor, scroll down
+              this.ybase++;
+              this.ydisp++;
+            }
+          }
+        }
+      }
+
+      // Reduce max length if needed after adjustments, this is done after as it
+      // would otherwise cut data from the bottom of the buffer.
+      if (newMaxLength < this.lines.maxLength) {
+        // Trim from the top of the buffer and adjust ybase and ydisp.
+        const amountToTrim = this.lines.length - newMaxLength;
+        if (amountToTrim > 0) {
+          this.lines.trimStart(amountToTrim);
+          this.ybase = Math.max(this.ybase - amountToTrim, 0);
+          this.ydisp = Math.max(this.ydisp - amountToTrim, 0);
+          this.savedY = Math.max(this.savedY - amountToTrim, 0);
+        }
+        this.lines.maxLength = newMaxLength;
+      }
+
+      // Make sure that the cursor stays on screen
+      this.x = Math.min(this.x, newCols - 1);
+      this.y = Math.min(this.y, newRows - 1);
+      if (addToY) {
+        this.y += addToY;
+      }
+      this.savedX = Math.min(this.savedX, newCols - 1);
+
+      this.scrollTop = 0;
+    }
+
+    this.scrollBottom = newRows - 1;
+
+    if (this._isReflowEnabled) {
+      this._reflow(newCols, newRows);
+
+      // Trim the end of the line off if cols shrunk
+      if (this._cols > newCols) {
+        for (let i = 0; i < this.lines.length; i++) {
+          this.lines.get(i)!.resize(newCols, nullCell);
+        }
+      }
+    }
+
+    this._cols = newCols;
+    this._rows = newRows;
+  }
+
+  private get _isReflowEnabled(): boolean {
+    return this._hasScrollback && !this._optionsService.options.windowsMode;
+  }
+
+  private _reflow(newCols: number, newRows: number): void {
+    if (this._cols === newCols) {
+      return;
+    }
+
+    // Iterate through rows, ignore the last one as it cannot be wrapped
+    if (newCols > this._cols) {
+      this._reflowLarger(newCols, newRows);
+    } else {
+      this._reflowSmaller(newCols, newRows);
+    }
+  }
+
+  private _reflowLarger(newCols: number, newRows: number): void {
+    const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA));
+    if (toRemove.length > 0) {
+      const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove);
+      reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout);
+      this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved);
+    }
+  }
+
+  private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void {
+    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);
+    // Adjust viewport based on number of items removed
+    let viewportAdjustments = countRemoved;
+    while (viewportAdjustments-- > 0) {
+      if (this.ybase === 0) {
+        if (this.y > 0) {
+          this.y--;
+        }
+        if (this.lines.length < newRows) {
+          // Add an extra row at the bottom of the viewport
+          this.lines.push(new BufferLine(newCols, nullCell));
+        }
+      } else {
+        if (this.ydisp === this.ybase) {
+          this.ydisp--;
+        }
+        this.ybase--;
+      }
+    }
+    this.savedY = Math.max(this.savedY - countRemoved, 0);
+  }
+
+  private _reflowSmaller(newCols: number, newRows: number): void {
+    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);
+    // Gather all BufferLines that need to be inserted into the Buffer here so that they can be
+    // batched up and only committed once
+    const toInsert = [];
+    let countToInsert = 0;
+    // Go backwards as many lines may be trimmed and this will avoid considering them
+    for (let y = this.lines.length - 1; y >= 0; y--) {
+      // Check whether this line is a problem
+      let nextLine = this.lines.get(y) as BufferLine;
+      if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) {
+        continue;
+      }
+
+      // Gather wrapped lines and adjust y to be the starting line
+      const wrappedLines: BufferLine[] = [nextLine];
+      while (nextLine.isWrapped && y > 0) {
+        nextLine = this.lines.get(--y) as BufferLine;
+        wrappedLines.unshift(nextLine);
+      }
+
+      // If these lines contain the cursor don't touch them, the program will handle fixing up
+      // wrapped lines with the cursor
+      const absoluteY = this.ybase + this.y;
+      if (absoluteY >= y && absoluteY < y + wrappedLines.length) {
+        continue;
+      }
+
+      const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength();
+      const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols);
+      const linesToAdd = destLineLengths.length - wrappedLines.length;
+      let trimmedLines: number;
+      if (this.ybase === 0 && this.y !== this.lines.length - 1) {
+        // If the top section of the buffer is not yet filled
+        trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd);
+      } else {
+        trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd);
+      }
+
+      // Add the new lines
+      const newLines: BufferLine[] = [];
+      for (let i = 0; i < linesToAdd; i++) {
+        const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine;
+        newLines.push(newLine);
+      }
+      if (newLines.length > 0) {
+        toInsert.push({
+          // countToInsert here gets the actual index, taking into account other inserted items.
+          // using this we can iterate through the list forwards
+          start: y + wrappedLines.length + countToInsert,
+          newLines
+        });
+        countToInsert += newLines.length;
+      }
+      wrappedLines.push(...newLines);
+
+      // Copy buffer data to new locations, this needs to happen backwards to do in-place
+      let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols);
+      let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols;
+      if (destCol === 0) {
+        destLineIndex--;
+        destCol = destLineLengths[destLineIndex];
+      }
+      let srcLineIndex = wrappedLines.length - linesToAdd - 1;
+      let srcCol = lastLineLength;
+      while (srcLineIndex >= 0) {
+        const cellsToCopy = Math.min(srcCol, destCol);
+        wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true);
+        destCol -= cellsToCopy;
+        if (destCol === 0) {
+          destLineIndex--;
+          destCol = destLineLengths[destLineIndex];
+        }
+        srcCol -= cellsToCopy;
+        if (srcCol === 0) {
+          srcLineIndex--;
+          const wrappedLinesIndex = Math.max(srcLineIndex, 0);
+          srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols);
+        }
+      }
+
+      // Null out the end of the line ends if a wide character wrapped to the following line
+      for (let i = 0; i < wrappedLines.length; i++) {
+        if (destLineLengths[i] < newCols) {
+          wrappedLines[i].setCell(destLineLengths[i], nullCell);
+        }
+      }
+
+      // Adjust viewport as needed
+      let viewportAdjustments = linesToAdd - trimmedLines;
+      while (viewportAdjustments-- > 0) {
+        if (this.ybase === 0) {
+          if (this.y < newRows - 1) {
+            this.y++;
+            this.lines.pop();
+          } else {
+            this.ybase++;
+            this.ydisp++;
+          }
+        } else {
+          // Ensure ybase does not exceed its maximum value
+          if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) {
+            if (this.ybase === this.ydisp) {
+              this.ydisp++;
+            }
+            this.ybase++;
+          }
+        }
+      }
+      this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1);
+    }
+
+    // Rearrange lines in the buffer if there are any insertions, this is done at the end rather
+    // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many
+    // costly calls to CircularList.splice.
+    if (toInsert.length > 0) {
+      // Record buffer insert events and then play them back backwards so that the indexes are
+      // correct
+      const insertEvents: IInsertEvent[] = [];
+
+      // Record original lines so they don't get overridden when we rearrange the list
+      const originalLines: BufferLine[] = [];
+      for (let i = 0; i < this.lines.length; i++) {
+        originalLines.push(this.lines.get(i) as BufferLine);
+      }
+      const originalLinesLength = this.lines.length;
+
+      let originalLineIndex = originalLinesLength - 1;
+      let nextToInsertIndex = 0;
+      let nextToInsert = toInsert[nextToInsertIndex];
+      this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert);
+      let countInsertedSoFar = 0;
+      for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) {
+        if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) {
+          // Insert extra lines here, adjusting i as needed
+          for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) {
+            this.lines.set(i--, nextToInsert.newLines[nextI]);
+          }
+          i++;
+
+          // Create insert events for later
+          insertEvents.push({
+            index: originalLineIndex + 1,
+            amount: nextToInsert.newLines.length
+          });
+
+          countInsertedSoFar += nextToInsert.newLines.length;
+          nextToInsert = toInsert[++nextToInsertIndex];
+        } else {
+          this.lines.set(i, originalLines[originalLineIndex--]);
+        }
+      }
+
+      // Update markers
+      let insertCountEmitted = 0;
+      for (let i = insertEvents.length - 1; i >= 0; i--) {
+        insertEvents[i].index += insertCountEmitted;
+        this.lines.onInsertEmitter.fire(insertEvents[i]);
+        insertCountEmitted += insertEvents[i].amount;
+      }
+      const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength);
+      if (amountToTrim > 0) {
+        this.lines.onTrimEmitter.fire(amountToTrim);
+      }
+    }
+  }
+
+  // private _reflowSmallerGetLinesNeeded()
+
+  /**
+   * Translates a string index back to a BufferIndex.
+   * To get the correct buffer position the string must start at `startCol` 0
+   * (default in translateBufferLineToString).
+   * The method also works on wrapped line strings given rows were not trimmed.
+   * The method operates on the CharData string length, there are no
+   * additional content or boundary checks. Therefore the string and the buffer
+   * should not be altered in between.
+   * TODO: respect trim flag after fixing #1685
+   * @param lineIndex line index the string was retrieved from
+   * @param stringIndex index within the string
+   * @param startCol column offset the string was retrieved from
+   */
+  public stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight: boolean = false): BufferIndex {
+    while (stringIndex) {
+      const line = this.lines.get(lineIndex);
+      if (!line) {
+        return [-1, -1];
+      }
+      const length = (trimRight) ? line.getTrimmedLength() : line.length;
+      for (let i = 0; i < length; ++i) {
+        if (line.get(i)[CHAR_DATA_WIDTH_INDEX]) {
+          // empty cells report a string length of 0, but get replaced
+          // with a whitespace in translateToString, thus replace with 1
+          stringIndex -= line.get(i)[CHAR_DATA_CHAR_INDEX].length || 1;
+        }
+        if (stringIndex < 0) {
+          return [lineIndex, i];
+        }
+      }
+      lineIndex++;
+    }
+    return [lineIndex, 0];
+  }
+
+  /**
+   * Translates a buffer line to a string, with optional start and end columns.
+   * Wide characters will count as two columns in the resulting string. This
+   * function is useful for getting the actual text underneath the raw selection
+   * position.
+   * @param line The line being translated.
+   * @param trimRight Whether to trim whitespace to the right.
+   * @param startCol The column to start at.
+   * @param endCol The column to end at.
+   */
+  public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string {
+    const line = this.lines.get(lineIndex);
+    if (!line) {
+      return '';
+    }
+    return line.translateToString(trimRight, startCol, endCol);
+  }
+
+  public getWrappedRangeForLine(y: number): { first: number, last: number } {
+    let first = y;
+    let last = y;
+    // Scan upwards for wrapped lines
+    while (first > 0 && this.lines.get(first)!.isWrapped) {
+      first--;
+    }
+    // Scan downwards for wrapped lines
+    while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) {
+      last++;
+    }
+    return { first, last };
+  }
+
+  /**
+   * Setup the tab stops.
+   * @param i The index to start setting up tab stops from.
+   */
+  public setupTabStops(i?: number): void {
+    if (i !== null && i !== undefined) {
+      if (!this.tabs[i]) {
+        i = this.prevStop(i);
+      }
+    } else {
+      this.tabs = {};
+      i = 0;
+    }
+
+    for (; i < this._cols; i += this._optionsService.options.tabStopWidth) {
+      this.tabs[i] = true;
+    }
+  }
+
+  /**
+   * Move the cursor to the previous tab stop from the given position (default is current).
+   * @param x The position to move the cursor to the previous tab stop.
+   */
+  public prevStop(x?: number): number {
+    if (x === null || x === undefined) {
+      x = this.x;
+    }
+    while (!this.tabs[--x] && x > 0);
+    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;
+  }
+
+  /**
+   * Move the cursor one tab stop forward from the given position (default is current).
+   * @param x The position to move the cursor one tab stop forward.
+   */
+  public nextStop(x?: number): number {
+    if (x === null || x === undefined) {
+      x = this.x;
+    }
+    while (!this.tabs[++x] && x < this._cols);
+    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;
+  }
+
+  public addMarker(y: number): Marker {
+    const marker = new Marker(y);
+    this.markers.push(marker);
+    marker.register(this.lines.onTrim(amount => {
+      marker.line -= amount;
+      // The marker should be disposed when the line is trimmed from the buffer
+      if (marker.line < 0) {
+        marker.dispose();
+      }
+    }));
+    marker.register(this.lines.onInsert(event => {
+      if (marker.line >= event.index) {
+        marker.line += event.amount;
+      }
+    }));
+    marker.register(this.lines.onDelete(event => {
+      // Delete the marker if it's within the range
+      if (marker.line >= event.index && marker.line < event.index + event.amount) {
+        marker.dispose();
+      }
+
+      // Shift the marker if it's after the deleted range
+      if (marker.line > event.index) {
+        marker.line -= event.amount;
+      }
+    }));
+    marker.register(marker.onDispose(() => this._removeMarker(marker)));
+    return marker;
+  }
+
+  private _removeMarker(marker: Marker): void {
+    this.markers.splice(this.markers.indexOf(marker), 1);
+  }
+
+  public iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator {
+    return new BufferStringIterator(this, trimRight, startIndex, endIndex, startOverscan, endOverscan);
+  }
+}
+
+/**
+ * Iterator to get unwrapped content strings from the buffer.
+ * The iterator returns at least the string data between the borders
+ * `startIndex` and `endIndex` (exclusive) and will expand the lines
+ * by `startOverscan` to the top and by `endOverscan` to the bottom,
+ * if no new line was found in between.
+ * It will never read/return string data beyond `startIndex - startOverscan`
+ * or `endIndex + endOverscan`. Therefore the first and last line might be truncated.
+ * It is possible to always get the full string for the first and last line as well
+ * by setting the overscan values to the actual buffer length. This not recommended
+ * since it might return the whole buffer within a single string in a worst case scenario.
+ */
+export class BufferStringIterator implements IBufferStringIterator {
+  private _current: number;
+
+  constructor (
+    private _buffer: IBuffer,
+    private _trimRight: boolean,
+    private _startIndex: number = 0,
+    private _endIndex: number = _buffer.lines.length,
+    private _startOverscan: number = 0,
+    private _endOverscan: number = 0
+  ) {
+    if (this._startIndex < 0) {
+      this._startIndex = 0;
+    }
+    if (this._endIndex > this._buffer.lines.length) {
+      this._endIndex = this._buffer.lines.length;
+    }
+    this._current = this._startIndex;
+  }
+
+  public hasNext(): boolean {
+    return this._current < this._endIndex;
+  }
+
+  public next(): IBufferStringIteratorResult {
+    const range = this._buffer.getWrappedRangeForLine(this._current);
+    // limit search window to overscan value at both borders
+    if (range.first < this._startIndex - this._startOverscan) {
+      range.first = this._startIndex - this._startOverscan;
+    }
+    if (range.last > this._endIndex + this._endOverscan) {
+      range.last = this._endIndex + this._endOverscan;
+    }
+    // limit to current buffer length
+    range.first = Math.max(range.first, 0);
+    range.last = Math.min(range.last, this._buffer.lines.length);
+    let result = '';
+    for (let i = range.first; i <= range.last; ++i) {
+      result += this._buffer.translateBufferLineToString(i, this._trimRight);
+    }
+    this._current = range.last + 1;
+    return {range: range, content: result};
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/BufferLine.ts b/node_modules/xterm/src/common/buffer/BufferLine.ts
new file mode 100644 (file)
index 0000000..1e95e00
--- /dev/null
@@ -0,0 +1,393 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { CharData, IBufferLine, ICellData } from 'common/Types';
+import { stringFromCodePoint } from 'common/input/TextDecoder';
+import { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { AttributeData } from 'common/buffer/AttributeData';
+
+/**
+ * buffer memory layout:
+ *
+ *   |             uint32_t             |        uint32_t         |        uint32_t         |
+ *   |             `content`            |          `FG`           |          `BG`           |
+ *   | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) |
+ */
+
+
+/** typed array slots taken by one cell */
+const CELL_SIZE = 3;
+
+/**
+ * Cell member indices.
+ *
+ * Direct access:
+ *    `content = data[column * CELL_SIZE + Cell.CONTENT];`
+ *    `fg = data[column * CELL_SIZE + Cell.FG];`
+ *    `bg = data[column * CELL_SIZE + Cell.BG];`
+ */
+const enum Cell {
+  CONTENT = 0,
+  FG = 1, // currently simply holds all known attrs
+  BG = 2  // currently unused
+}
+
+export const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData());
+
+/**
+ * Typed array based bufferline implementation.
+ *
+ * There are 2 ways to insert data into the cell buffer:
+ * - `setCellFromCodepoint` + `addCodepointToCell`
+ *   Use these for data that is already UTF32.
+ *   Used during normal input in `InputHandler` for faster buffer access.
+ * - `setCell`
+ *   This method takes a CellData object and stores the data in the buffer.
+ *   Use `CellData.fromCharData` to create the CellData object (e.g. from JS string).
+ *
+ * To retrieve data from the buffer use either one of the primitive methods
+ * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop
+ * memory allocs / GC pressure can be greatly reduced by reusing the CellData object.
+ */
+export class BufferLine implements IBufferLine {
+  protected _data: Uint32Array;
+  protected _combined: {[index: number]: string} = {};
+  public length: number;
+
+  constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) {
+    this._data = new Uint32Array(cols * CELL_SIZE);
+    const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);
+    for (let i = 0; i < cols; ++i) {
+      this.setCell(i, cell);
+    }
+    this.length = cols;
+  }
+
+  /**
+   * Get cell data CharData.
+   * @deprecated
+   */
+  public get(index: number): CharData {
+    const content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    const cp = content & Content.CODEPOINT_MASK;
+    return [
+      this._data[index * CELL_SIZE + Cell.FG],
+      (content & Content.IS_COMBINED_MASK)
+        ? this._combined[index]
+        : (cp) ? stringFromCodePoint(cp) : '',
+      content >> Content.WIDTH_SHIFT,
+      (content & Content.IS_COMBINED_MASK)
+        ? this._combined[index].charCodeAt(this._combined[index].length - 1)
+        : cp
+    ];
+  }
+
+  /**
+   * Set cell data from CharData.
+   * @deprecated
+   */
+  public set(index: number, value: CharData): void {
+    this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX];
+    if (value[CHAR_DATA_CHAR_INDEX].length > 1) {
+      this._combined[index] = value[1];
+      this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    } else {
+      this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    }
+  }
+
+  /**
+   * primitive getters
+   * use these when only one value is needed, otherwise use `loadCell`
+   */
+  public getWidth(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT;
+  }
+
+  /** Test whether content has width. */
+  public hasWidth(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK;
+  }
+
+  /** Get FG cell component. */
+  public getFg(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.FG];
+  }
+
+  /** Get BG cell component. */
+  public getBg(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.BG];
+  }
+
+  /**
+   * Test whether contains any chars.
+   * Basically an empty has no content, but other cells might differ in FG/BG
+   * from real empty cells.
+   * */
+  public hasContent(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK;
+  }
+
+  /**
+   * Get codepoint of the cell.
+   * To be in line with `code` in CharData this either returns
+   * a single UTF32 codepoint or the last codepoint of a combined string.
+   */
+  public getCodePoint(index: number): number {
+    const content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    if (content & Content.IS_COMBINED_MASK) {
+      return this._combined[index].charCodeAt(this._combined[index].length - 1);
+    }
+    return content & Content.CODEPOINT_MASK;
+  }
+
+  /** Test whether the cell contains a combined string. */
+  public isCombined(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK;
+  }
+
+  /** Returns the string content of the cell. */
+  public getString(index: number): string {
+    const content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    if (content & Content.IS_COMBINED_MASK) {
+      return this._combined[index];
+    }
+    if (content & Content.CODEPOINT_MASK) {
+      return stringFromCodePoint(content & Content.CODEPOINT_MASK);
+    }
+    // return empty string for empty cells
+    return '';
+  }
+
+  /**
+   * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly
+   * to GC as it significantly reduced the amount of new objects/references needed.
+   */
+  public loadCell(index: number, cell: ICellData): ICellData {
+    const startIndex = index * CELL_SIZE;
+    cell.content = this._data[startIndex + Cell.CONTENT];
+    cell.fg = this._data[startIndex + Cell.FG];
+    cell.bg = this._data[startIndex + Cell.BG];
+    if (cell.content & Content.IS_COMBINED_MASK) {
+      cell.combinedData = this._combined[index];
+    }
+    return cell;
+  }
+
+  /**
+   * Set data at `index` to `cell`.
+   */
+  public setCell(index: number, cell: ICellData): void {
+    if (cell.content & Content.IS_COMBINED_MASK) {
+      this._combined[index] = cell.combinedData;
+    }
+    this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content;
+    this._data[index * CELL_SIZE + Cell.FG] = cell.fg;
+    this._data[index * CELL_SIZE + Cell.BG] = cell.bg;
+  }
+
+  /**
+   * Set cell data from input handler.
+   * Since the input handler see the incoming chars as UTF32 codepoints,
+   * it gets an optimized access method.
+   */
+  public setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number): void {
+    this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT);
+    this._data[index * CELL_SIZE + Cell.FG] = fg;
+    this._data[index * CELL_SIZE + Cell.BG] = bg;
+  }
+
+  /**
+   * Add a codepoint to a cell from input handler.
+   * During input stage combining chars with a width of 0 follow and stack
+   * onto a leading char. Since we already set the attrs
+   * by the previous `setDataFromCodePoint` call, we can omit it here.
+   */
+  public addCodepointToCell(index: number, codePoint: number): void {
+    let content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    if (content & Content.IS_COMBINED_MASK) {
+      // we already have a combined string, simply add
+      this._combined[index] += stringFromCodePoint(codePoint);
+    } else {
+      if (content & Content.CODEPOINT_MASK) {
+        // normal case for combining chars:
+        //  - move current leading char + new one into combined string
+        //  - set combined flag
+        this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint);
+        content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0
+        content |= Content.IS_COMBINED_MASK;
+      } else {
+        // should not happen - we actually have no data in the cell yet
+        // simply set the data in the cell buffer with a width of 1
+        content = codePoint | (1 << Content.WIDTH_SHIFT);
+      }
+      this._data[index * CELL_SIZE + Cell.CONTENT] = content;
+    }
+  }
+
+  public insertCells(pos: number, n: number, fillCellData: ICellData): void {
+    pos %= this.length;
+    if (n < this.length - pos) {
+      const cell = new CellData();
+      for (let i = this.length - pos - n - 1; i >= 0; --i) {
+        this.setCell(pos + n + i, this.loadCell(pos + i, cell));
+      }
+      for (let i = 0; i < n; ++i) {
+        this.setCell(pos + i, fillCellData);
+      }
+    } else {
+      for (let i = pos; i < this.length; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    }
+  }
+
+  public deleteCells(pos: number, n: number, fillCellData: ICellData): void {
+    pos %= this.length;
+    if (n < this.length - pos) {
+      const cell = new CellData();
+      for (let i = 0; i < this.length - pos - n; ++i) {
+        this.setCell(pos + i, this.loadCell(pos + n + i, cell));
+      }
+      for (let i = this.length - n; i < this.length; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    } else {
+      for (let i = pos; i < this.length; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    }
+  }
+
+  public replaceCells(start: number, end: number, fillCellData: ICellData): void {
+    while (start < end  && start < this.length) {
+      this.setCell(start++, fillCellData);
+    }
+  }
+
+  public resize(cols: number, fillCellData: ICellData): void {
+    if (cols === this.length) {
+      return;
+    }
+    if (cols > this.length) {
+      const data = new Uint32Array(cols * CELL_SIZE);
+      if (this.length) {
+        if (cols * CELL_SIZE < this._data.length) {
+          data.set(this._data.subarray(0, cols * CELL_SIZE));
+        } else {
+          data.set(this._data);
+        }
+      }
+      this._data = data;
+      for (let i = this.length; i < cols; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    } else {
+      if (cols) {
+        const data = new Uint32Array(cols * CELL_SIZE);
+        data.set(this._data.subarray(0, cols * CELL_SIZE));
+        this._data = data;
+        // Remove any cut off combined data
+        const keys = Object.keys(this._combined);
+        for (let i = 0; i < keys.length; i++) {
+          const key = parseInt(keys[i], 10);
+          if (key >= cols) {
+            delete this._combined[key];
+          }
+        }
+      } else {
+        this._data = new Uint32Array(0);
+        this._combined = {};
+      }
+    }
+    this.length = cols;
+  }
+
+  /** fill a line with fillCharData */
+  public fill(fillCellData: ICellData): void {
+    this._combined = {};
+    for (let i = 0; i < this.length; ++i) {
+      this.setCell(i, fillCellData);
+    }
+  }
+
+  /** alter to a full copy of line  */
+  public copyFrom(line: BufferLine): void {
+    if (this.length !== line.length) {
+      this._data = new Uint32Array(line._data);
+    } else {
+      // use high speed copy if lengths are equal
+      this._data.set(line._data);
+    }
+    this.length = line.length;
+    this._combined = {};
+    for (const el in line._combined) {
+      this._combined[el] = line._combined[el];
+    }
+    this.isWrapped = line.isWrapped;
+  }
+
+  /** create a new clone */
+  public clone(): IBufferLine {
+    const newLine = new BufferLine(0);
+    newLine._data = new Uint32Array(this._data);
+    newLine.length = this.length;
+    for (const el in this._combined) {
+      newLine._combined[el] = this._combined[el];
+    }
+    newLine.isWrapped = this.isWrapped;
+    return newLine;
+  }
+
+  public getTrimmedLength(): number {
+    for (let i = this.length - 1; i >= 0; --i) {
+      if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) {
+        return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);
+      }
+    }
+    return 0;
+  }
+
+  public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void {
+    const srcData = src._data;
+    if (applyInReverse) {
+      for (let cell = length - 1; cell >= 0; cell--) {
+        for (let i = 0; i < CELL_SIZE; i++) {
+          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];
+        }
+      }
+    } else {
+      for (let cell = 0; cell < length; cell++) {
+        for (let i = 0; i < CELL_SIZE; i++) {
+          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];
+        }
+      }
+    }
+
+    // Move any combined data over as needed
+    const srcCombinedKeys = Object.keys(src._combined);
+    for (let i = 0; i < srcCombinedKeys.length; i++) {
+      const key = parseInt(srcCombinedKeys[i], 10);
+      if (key >= srcCol) {
+        this._combined[key - srcCol + destCol] = src._combined[key];
+      }
+    }
+  }
+
+  public translateToString(trimRight: boolean = false, startCol: number = 0, endCol: number = this.length): string {
+    if (trimRight) {
+      endCol = Math.min(endCol, this.getTrimmedLength());
+    }
+    let result = '';
+    while (startCol < endCol) {
+      const content = this._data[startCol * CELL_SIZE + Cell.CONTENT];
+      const cp = content & Content.CODEPOINT_MASK;
+      result += (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR;
+      startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by 1
+    }
+    return result;
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/BufferReflow.ts b/node_modules/xterm/src/common/buffer/BufferReflow.ts
new file mode 100644 (file)
index 0000000..ece9a96
--- /dev/null
@@ -0,0 +1,220 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { BufferLine } from 'common/buffer/BufferLine';
+import { CircularList } from 'common/CircularList';
+import { IBufferLine, ICellData } from 'common/Types';
+
+export interface INewLayoutResult {
+  layout: number[];
+  countRemoved: number;
+}
+
+/**
+ * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed
+ * when a wrapped line unwraps.
+ * @param lines The buffer lines.
+ * @param newCols The columns after resize.
+ */
+export function reflowLargerGetLinesToRemove(lines: CircularList<IBufferLine>, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData): number[] {
+  // Gather all BufferLines that need to be removed from the Buffer here so that they can be
+  // batched up and only committed once
+  const toRemove: number[] = [];
+
+  for (let y = 0; y < lines.length - 1; y++) {
+    // Check if this row is wrapped
+    let i = y;
+    let nextLine = lines.get(++i) as BufferLine;
+    if (!nextLine.isWrapped) {
+      continue;
+    }
+
+    // Check how many lines it's wrapped for
+    const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine];
+    while (i < lines.length && nextLine.isWrapped) {
+      wrappedLines.push(nextLine);
+      nextLine = lines.get(++i) as BufferLine;
+    }
+
+    // If these lines contain the cursor don't touch them, the program will handle fixing up wrapped
+    // lines with the cursor
+    if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {
+      y += wrappedLines.length - 1;
+      continue;
+    }
+
+    // Copy buffer data to new locations
+    let destLineIndex = 0;
+    let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols);
+    let srcLineIndex = 1;
+    let srcCol = 0;
+    while (srcLineIndex < wrappedLines.length) {
+      const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols);
+      const srcRemainingCells = srcTrimmedTineLength - srcCol;
+      const destRemainingCells = newCols - destCol;
+      const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells);
+
+      wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false);
+
+      destCol += cellsToCopy;
+      if (destCol === newCols) {
+        destLineIndex++;
+        destCol = 0;
+      }
+      srcCol += cellsToCopy;
+      if (srcCol === srcTrimmedTineLength) {
+        srcLineIndex++;
+        srcCol = 0;
+      }
+
+      // Make sure the last cell isn't wide, if it is copy it to the current dest
+      if (destCol === 0 && destLineIndex !== 0) {
+        if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) {
+          wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false);
+          // Null out the end of the last row
+          wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell);
+        }
+      }
+    }
+
+    // Clear out remaining cells or fragments could remain;
+    wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell);
+
+    // Work backwards and remove any rows at the end that only contain null cells
+    let countToRemove = 0;
+    for (let i = wrappedLines.length - 1; i > 0; i--) {
+      if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) {
+        countToRemove++;
+      } else {
+        break;
+      }
+    }
+
+    if (countToRemove > 0) {
+      toRemove.push(y + wrappedLines.length - countToRemove); // index
+      toRemove.push(countToRemove);
+    }
+
+    y += wrappedLines.length - 1;
+  }
+  return toRemove;
+}
+
+/**
+ * Creates and return the new layout for lines given an array of indexes to be removed.
+ * @param lines The buffer lines.
+ * @param toRemove The indexes to remove.
+ */
+export function reflowLargerCreateNewLayout(lines: CircularList<IBufferLine>, toRemove: number[]): INewLayoutResult {
+  const layout: number[] = [];
+  // First iterate through the list and get the actual indexes to use for rows
+  let nextToRemoveIndex = 0;
+  let nextToRemoveStart = toRemove[nextToRemoveIndex];
+  let countRemovedSoFar = 0;
+  for (let i = 0; i < lines.length; i++) {
+    if (nextToRemoveStart === i) {
+      const countToRemove = toRemove[++nextToRemoveIndex];
+
+      // Tell markers that there was a deletion
+      lines.onDeleteEmitter.fire({
+        index: i - countRemovedSoFar,
+        amount: countToRemove
+      });
+
+      i += countToRemove - 1;
+      countRemovedSoFar += countToRemove;
+      nextToRemoveStart = toRemove[++nextToRemoveIndex];
+    } else {
+      layout.push(i);
+    }
+  }
+  return {
+    layout,
+    countRemoved: countRemovedSoFar
+  };
+}
+
+/**
+ * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's
+ * done all at once in a single iteration through the list since splice is very expensive.
+ * @param lines The buffer lines.
+ * @param newLayout The new layout to apply.
+ */
+export function reflowLargerApplyNewLayout(lines: CircularList<IBufferLine>, newLayout: number[]): void {
+  // Record original lines so they don't get overridden when we rearrange the list
+  const newLayoutLines: BufferLine[] = [];
+  for (let i = 0; i < newLayout.length; i++) {
+    newLayoutLines.push(lines.get(newLayout[i]) as BufferLine);
+  }
+
+  // Rearrange the list
+  for (let i = 0; i < newLayoutLines.length; i++) {
+    lines.set(i, newLayoutLines[i]);
+  }
+  lines.length = newLayout.length;
+}
+
+/**
+ * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-
+ * compute the wrapping points since wide characters may need to be wrapped onto the following line.
+ * This function will return an array of numbers of where each line wraps to, the resulting array
+ * will only contain the values `newCols` (when the line does not end with a wide character) and
+ * `newCols - 1` (when the line does end with a wide character), except for the last value which
+ * will contain the remaining items to fill the line.
+ *
+ * Calling this with a `newCols` value of `1` will lock up.
+ *
+ * @param wrappedLines The wrapped lines to evaluate.
+ * @param oldCols The columns before resize.
+ * @param newCols The columns after resize.
+ */
+export function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] {
+  const newLineLengths: number[] = [];
+  const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c);
+
+  // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and
+  // linesNeeded
+  let srcCol = 0;
+  let srcLine = 0;
+  let cellsAvailable = 0;
+  while (cellsAvailable < cellsNeeded) {
+    if (cellsNeeded - cellsAvailable < newCols) {
+      // Add the final line and exit the loop
+      newLineLengths.push(cellsNeeded - cellsAvailable);
+      break;
+    }
+    srcCol += newCols;
+    const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols);
+    if (srcCol > oldTrimmedLength) {
+      srcCol -= oldTrimmedLength;
+      srcLine++;
+    }
+    const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2;
+    if (endsWithWide) {
+      srcCol--;
+    }
+    const lineLength = endsWithWide ? newCols - 1 : newCols;
+    newLineLengths.push(lineLength);
+    cellsAvailable += lineLength;
+  }
+
+  return newLineLengths;
+}
+
+export function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number {
+  // If this is the last row in the wrapped line, get the actual trimmed length
+  if (i === lines.length - 1) {
+    return lines[i].getTrimmedLength();
+  }
+  // Detect whether the following line starts with a wide character and the end of the current line
+  // is null, if so then we can be pretty sure the null character should be excluded from the line
+  // length]
+  const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1;
+  const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2;
+  if (endsInNull && followingLineStartsWithWide) {
+    return cols - 1;
+  }
+  return cols;
+}
diff --git a/node_modules/xterm/src/common/buffer/BufferSet.ts b/node_modules/xterm/src/common/buffer/BufferSet.ts
new file mode 100644 (file)
index 0000000..50e6e50
--- /dev/null
@@ -0,0 +1,122 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBuffer, IBufferSet } from 'common/buffer/Types';
+import { IAttributeData } from 'common/Types';
+import { Buffer } from 'common/buffer/Buffer';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { IOptionsService, IBufferService } from 'common/services/Services';
+
+/**
+ * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and
+ * provides also utilities for working with them.
+ */
+export class BufferSet implements IBufferSet {
+  private _normal: Buffer;
+  private _alt: Buffer;
+  private _activeBuffer: Buffer;
+
+
+  private _onBufferActivate = new EventEmitter<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}>();
+  public get onBufferActivate(): IEvent<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}> { return this._onBufferActivate.event; }
+
+  /**
+   * Create a new BufferSet for the given terminal.
+   * @param _terminal - The terminal the BufferSet will belong to
+   */
+  constructor(
+    readonly optionsService: IOptionsService,
+    readonly bufferService: IBufferService
+  ) {
+    this._normal = new Buffer(true, optionsService, bufferService);
+    this._normal.fillViewportRows();
+
+    // The alt buffer should never have scrollback.
+    // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer
+    this._alt = new Buffer(false, optionsService, bufferService);
+    this._activeBuffer = this._normal;
+
+    this.setupTabStops();
+  }
+
+  /**
+   * Returns the alt Buffer of the BufferSet
+   */
+  public get alt(): Buffer {
+    return this._alt;
+  }
+
+  /**
+   * Returns the normal Buffer of the BufferSet
+   */
+  public get active(): Buffer {
+    return this._activeBuffer;
+  }
+
+  /**
+   * Returns the currently active Buffer of the BufferSet
+   */
+  public get normal(): Buffer {
+    return this._normal;
+  }
+
+  /**
+   * Sets the normal Buffer of the BufferSet as its currently active Buffer
+   */
+  public activateNormalBuffer(): void {
+    if (this._activeBuffer === this._normal) {
+      return;
+    }
+    this._normal.x = this._alt.x;
+    this._normal.y = this._alt.y;
+    // The alt buffer should always be cleared when we switch to the normal
+    // buffer. This frees up memory since the alt buffer should always be new
+    // when activated.
+    this._alt.clear();
+    this._activeBuffer = this._normal;
+    this._onBufferActivate.fire({
+      activeBuffer: this._normal,
+      inactiveBuffer: this._alt
+    });
+  }
+
+  /**
+   * Sets the alt Buffer of the BufferSet as its currently active Buffer
+   */
+  public activateAltBuffer(fillAttr?: IAttributeData): void {
+    if (this._activeBuffer === this._alt) {
+      return;
+    }
+    // Since the alt buffer is always cleared when the normal buffer is
+    // activated, we want to fill it when switching to it.
+    this._alt.fillViewportRows(fillAttr);
+    this._alt.x = this._normal.x;
+    this._alt.y = this._normal.y;
+    this._activeBuffer = this._alt;
+    this._onBufferActivate.fire({
+      activeBuffer: this._alt,
+      inactiveBuffer: this._normal
+    });
+  }
+
+  /**
+   * Resizes both normal and alt buffers, adjusting their data accordingly.
+   * @param newCols The new number of columns.
+   * @param newRows The new number of rows.
+   */
+  public resize(newCols: number, newRows: number): void {
+    this._normal.resize(newCols, newRows);
+    this._alt.resize(newCols, newRows);
+  }
+
+  /**
+   * Setup the tab stops.
+   * @param i The index to start setting up tab stops from.
+   */
+  public setupTabStops(i?: number): void {
+    this._normal.setupTabStops(i);
+    this._alt.setupTabStops(i);
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/CellData.ts b/node_modules/xterm/src/common/buffer/CellData.ts
new file mode 100644 (file)
index 0000000..21ad2ee
--- /dev/null
@@ -0,0 +1,93 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { CharData, ICellData } from 'common/Types';
+import { stringFromCodePoint } from 'common/input/TextDecoder';
+import { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants';
+import { AttributeData } from 'common/buffer/AttributeData';
+
+/**
+ * CellData - represents a single Cell in the terminal buffer.
+ */
+export class CellData extends AttributeData implements ICellData {
+  /** Helper to create CellData from CharData. */
+  public static fromCharData(value: CharData): CellData {
+    const obj = new CellData();
+    obj.setFromCharData(value);
+    return obj;
+  }
+  /** Primitives from terminal buffer. */
+  public content: number = 0;
+  public fg: number = 0;
+  public bg: number = 0;
+  public combinedData: string = '';
+  /** Whether cell contains a combined string. */
+  public isCombined(): number {
+    return this.content & Content.IS_COMBINED_MASK;
+  }
+  /** Width of the cell. */
+  public getWidth(): number {
+    return this.content >> Content.WIDTH_SHIFT;
+  }
+  /** JS string of the content. */
+  public getChars(): string {
+    if (this.content & Content.IS_COMBINED_MASK) {
+      return this.combinedData;
+    }
+    if (this.content & Content.CODEPOINT_MASK) {
+      return stringFromCodePoint(this.content & Content.CODEPOINT_MASK);
+    }
+    return '';
+  }
+  /**
+   * Codepoint of cell
+   * Note this returns the UTF32 codepoint of single chars,
+   * if content is a combined string it returns the codepoint
+   * of the last char in string to be in line with code in CharData.
+   * */
+  public getCode(): number {
+    return (this.isCombined())
+      ? this.combinedData.charCodeAt(this.combinedData.length - 1)
+      : this.content & Content.CODEPOINT_MASK;
+  }
+  /** Set data from CharData */
+  public setFromCharData(value: CharData): void {
+    this.fg = value[CHAR_DATA_ATTR_INDEX];
+    this.bg = 0;
+    let combined = false;
+    // surrogates and combined strings need special treatment
+    if (value[CHAR_DATA_CHAR_INDEX].length > 2) {
+      combined = true;
+    }
+    else if (value[CHAR_DATA_CHAR_INDEX].length === 2) {
+      const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0);
+      // if the 2-char string is a surrogate create single codepoint
+      // everything else is combined
+      if (0xD800 <= code && code <= 0xDBFF) {
+        const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1);
+        if (0xDC00 <= second && second <= 0xDFFF) {
+          this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+        }
+        else {
+          combined = true;
+        }
+      }
+      else {
+        combined = true;
+      }
+    }
+    else {
+      this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    }
+    if (combined) {
+      this.combinedData = value[CHAR_DATA_CHAR_INDEX];
+      this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    }
+  }
+  /** Get data as CharData. */
+  public getAsCharData(): CharData {
+    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/Constants.ts b/node_modules/xterm/src/common/buffer/Constants.ts
new file mode 100644 (file)
index 0000000..276a5c5
--- /dev/null
@@ -0,0 +1,128 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export const DEFAULT_COLOR = 256;
+export const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0);
+
+export const CHAR_DATA_ATTR_INDEX = 0;
+export const CHAR_DATA_CHAR_INDEX = 1;
+export const CHAR_DATA_WIDTH_INDEX = 2;
+export const CHAR_DATA_CODE_INDEX = 3;
+
+/**
+ * Null cell - a real empty cell (containing nothing).
+ * Note that code should always be 0 for a null cell as
+ * several test condition of the buffer line rely on this.
+ */
+export const NULL_CELL_CHAR = '';
+export const NULL_CELL_WIDTH = 1;
+export const NULL_CELL_CODE = 0;
+
+/**
+ * Whitespace cell.
+ * This is meant as a replacement for empty cells when needed
+ * during rendering lines to preserve correct aligment.
+ */
+export const WHITESPACE_CELL_CHAR = ' ';
+export const WHITESPACE_CELL_WIDTH = 1;
+export const WHITESPACE_CELL_CODE = 32;
+
+/**
+ * Bitmasks for accessing data in `content`.
+ */
+export const enum Content {
+  /**
+   * bit 1..21    codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken)
+   *              read:   `codepoint = content & Content.codepointMask;`
+   *              write:  `content |= codepoint & Content.codepointMask;`
+   *                      shortcut if precondition `codepoint <= 0x10FFFF` is met:
+   *                      `content |= codepoint;`
+   */
+  CODEPOINT_MASK = 0x1FFFFF,
+
+  /**
+   * bit 22       flag indication whether a cell contains combined content
+   *              read:   `isCombined = content & Content.isCombined;`
+   *              set:    `content |= Content.isCombined;`
+   *              clear:  `content &= ~Content.isCombined;`
+   */
+  IS_COMBINED_MASK = 0x200000,  // 1 << 21
+
+  /**
+   * bit 1..22    mask to check whether a cell contains any string data
+   *              we need to check for codepoint and isCombined bits to see
+   *              whether a cell contains anything
+   *              read:   `isEmpty = !(content & Content.hasContent)`
+   */
+  HAS_CONTENT_MASK = 0x3FFFFF,
+
+  /**
+   * bit 23..24   wcwidth value of cell, takes 2 bits (ranges from 0..2)
+   *              read:   `width = (content & Content.widthMask) >> Content.widthShift;`
+   *                      `hasWidth = content & Content.widthMask;`
+   *                      as long as wcwidth is highest value in `content`:
+   *                      `width = content >> Content.widthShift;`
+   *              write:  `content |= (width << Content.widthShift) & Content.widthMask;`
+   *                      shortcut if precondition `0 <= width <= 3` is met:
+   *                      `content |= width << Content.widthShift;`
+   */
+  WIDTH_MASK = 0xC00000,   // 3 << 22
+  WIDTH_SHIFT = 22
+}
+
+export const enum Attributes {
+  /**
+   * bit 1..8     blue in RGB, color in P256 and P16
+   */
+  BLUE_MASK = 0xFF,
+  BLUE_SHIFT = 0,
+  PCOLOR_MASK = 0xFF,
+  PCOLOR_SHIFT = 0,
+
+  /**
+   * bit 9..16    green in RGB
+   */
+  GREEN_MASK = 0xFF00,
+  GREEN_SHIFT = 8,
+
+  /**
+   * bit 17..24   red in RGB
+   */
+  RED_MASK = 0xFF0000,
+  RED_SHIFT = 16,
+
+  /**
+   * bit 25..26   color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3)
+   */
+  CM_MASK = 0x3000000,
+  CM_DEFAULT = 0,
+  CM_P16 = 0x1000000,
+  CM_P256 = 0x2000000,
+  CM_RGB = 0x3000000,
+
+  /**
+   * bit 1..24  RGB room
+   */
+  RGB_MASK = 0xFFFFFF
+}
+
+export const enum FgFlags {
+  /**
+   * bit 27..31 (32th bit unused)
+   */
+  INVERSE = 0x4000000,
+  BOLD = 0x8000000,
+  UNDERLINE = 0x10000000,
+  BLINK = 0x20000000,
+  INVISIBLE = 0x40000000
+}
+
+export const enum BgFlags {
+  /**
+   * bit 27..32 (upper 4 unused)
+   */
+  ITALIC = 0x4000000,
+  DIM = 0x8000000
+}
diff --git a/node_modules/xterm/src/common/buffer/Marker.ts b/node_modules/xterm/src/common/buffer/Marker.ts
new file mode 100644 (file)
index 0000000..9a4256d
--- /dev/null
@@ -0,0 +1,36 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { Disposable } from 'common/Lifecycle';
+import { IMarker } from 'common/Types';
+
+export class Marker extends Disposable implements IMarker {
+  private static _nextId = 1;
+
+  private _id: number = Marker._nextId++;
+  public isDisposed: boolean = false;
+
+  public get id(): number { return this._id; }
+
+  private _onDispose = new EventEmitter<void>();
+  public get onDispose(): IEvent<void> { return this._onDispose.event; }
+
+  constructor(
+    public line: number
+  ) {
+    super();
+  }
+
+  public dispose(): void {
+    if (this.isDisposed) {
+      return;
+    }
+    this.isDisposed = true;
+    this.line = -1;
+    // Emit before super.dispose such that dispose listeners get a change to react
+    this._onDispose.fire();
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/Types.d.ts b/node_modules/xterm/src/common/buffer/Types.d.ts
new file mode 100644 (file)
index 0000000..e229d69
--- /dev/null
@@ -0,0 +1,61 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IAttributeData, ICircularList, IBufferLine, ICellData, IMarker, ICharset } from 'common/Types';
+import { IEvent } from 'common/EventEmitter';
+
+// BufferIndex denotes a position in the buffer: [rowIndex, colIndex]
+export type BufferIndex = [number, number];
+
+export interface IBufferStringIteratorResult {
+  range: {first: number, last: number};
+  content: string;
+}
+
+export interface IBufferStringIterator {
+  hasNext(): boolean;
+  next(): IBufferStringIteratorResult;
+}
+
+export interface IBuffer {
+  readonly lines: ICircularList<IBufferLine>;
+  ydisp: number;
+  ybase: number;
+  y: number;
+  x: number;
+  tabs: any;
+  scrollBottom: number;
+  scrollTop: number;
+  hasScrollback: boolean;
+  savedY: number;
+  savedX: number;
+  savedCharset: ICharset | null;
+  savedCurAttrData: IAttributeData;
+  isCursorInViewport: boolean;
+  markers: IMarker[];
+  translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol?: number, endCol?: number): string;
+  getWrappedRangeForLine(y: number): { first: number, last: number };
+  nextStop(x?: number): number;
+  prevStop(x?: number): number;
+  getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine;
+  stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight?: boolean): number[];
+  iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator;
+  getNullCell(attr?: IAttributeData): ICellData;
+  getWhitespaceCell(attr?: IAttributeData): ICellData;
+  addMarker(y: number): IMarker;
+}
+
+export interface IBufferSet {
+  alt: IBuffer;
+  normal: IBuffer;
+  active: IBuffer;
+
+  onBufferActivate: IEvent<{ activeBuffer: IBuffer, inactiveBuffer: IBuffer }>;
+
+  activateNormalBuffer(): void;
+  activateAltBuffer(fillAttr?: IAttributeData): void;
+  resize(newCols: number, newRows: number): void;
+  setupTabStops(i?: number): void;
+}
diff --git a/node_modules/xterm/src/common/data/Charsets.ts b/node_modules/xterm/src/common/data/Charsets.ts
new file mode 100644 (file)
index 0000000..56ca679
--- /dev/null
@@ -0,0 +1,255 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharset } from 'common/Types';
+
+/**
+ * The character sets supported by the terminal. These enable several languages
+ * to be represented within the terminal with only 8-bit encoding. See ISO 2022
+ * for a discussion on character sets. Only VT100 character sets are supported.
+ */
+export const CHARSETS: { [key: string]: ICharset | null } = {};
+
+/**
+ * The default character set, US.
+ */
+export const DEFAULT_CHARSET: ICharset | null = CHARSETS['B'];
+
+/**
+ * DEC Special Character and Line Drawing Set.
+ * Reference: http://vt100.net/docs/vt102-ug/table5-13.html
+ * A lot of curses apps use this if they see TERM=xterm.
+ * testing: echo -e '\e(0a\e(B'
+ * The xterm output sometimes seems to conflict with the
+ * reference above. xterm seems in line with the reference
+ * when running vttest however.
+ * The table below now uses xterm's output from vttest.
+ */
+CHARSETS['0'] = {
+  '`': '\u25c6', // '◆'
+  'a': '\u2592', // '▒'
+  'b': '\u0009', // '\t'
+  'c': '\u000c', // '\f'
+  'd': '\u000d', // '\r'
+  'e': '\u000a', // '\n'
+  'f': '\u00b0', // '°'
+  'g': '\u00b1', // '±'
+  'h': '\u2424', // '\u2424' (NL)
+  'i': '\u000b', // '\v'
+  'j': '\u2518', // '┘'
+  'k': '\u2510', // '┐'
+  'l': '\u250c', // '┌'
+  'm': '\u2514', // '└'
+  'n': '\u253c', // '┼'
+  'o': '\u23ba', // '⎺'
+  'p': '\u23bb', // '⎻'
+  'q': '\u2500', // '─'
+  'r': '\u23bc', // '⎼'
+  's': '\u23bd', // '⎽'
+  't': '\u251c', // '├'
+  'u': '\u2524', // '┤'
+  'v': '\u2534', // '┴'
+  'w': '\u252c', // '┬'
+  'x': '\u2502', // '│'
+  'y': '\u2264', // '≤'
+  'z': '\u2265', // '≥'
+  '{': '\u03c0', // 'π'
+  '|': '\u2260', // '≠'
+  '}': '\u00a3', // '£'
+  '~': '\u00b7'  // '·'
+};
+
+/**
+ * British character set
+ * ESC (A
+ * Reference: http://vt100.net/docs/vt220-rm/table2-5.html
+ */
+CHARSETS['A'] = {
+  '#': '£'
+};
+
+/**
+ * United States character set
+ * ESC (B
+ */
+CHARSETS['B'] = null;
+
+/**
+ * Dutch character set
+ * ESC (4
+ * Reference: http://vt100.net/docs/vt220-rm/table2-6.html
+ */
+CHARSETS['4'] = {
+  '#': '£',
+  '@': '¾',
+  '[': 'ij',
+  '\\': '½',
+  ']': '|',
+  '{': '¨',
+  '|': 'f',
+  '}': '¼',
+  '~': '´'
+};
+
+/**
+ * Finnish character set
+ * ESC (C or ESC (5
+ * Reference: http://vt100.net/docs/vt220-rm/table2-7.html
+ */
+CHARSETS['C'] =
+CHARSETS['5'] = {
+  '[': 'Ä',
+  '\\': 'Ö',
+  ']': 'Å',
+  '^': 'Ü',
+  '`': 'é',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'å',
+  '~': 'ü'
+};
+
+/**
+ * French character set
+ * ESC (R
+ * Reference: http://vt100.net/docs/vt220-rm/table2-8.html
+ */
+CHARSETS['R'] = {
+  '#': '£',
+  '@': 'à',
+  '[': '°',
+  '\\': 'ç',
+  ']': '§',
+  '{': 'é',
+  '|': 'ù',
+  '}': 'è',
+  '~': '¨'
+};
+
+/**
+ * French Canadian character set
+ * ESC (Q
+ * Reference: http://vt100.net/docs/vt220-rm/table2-9.html
+ */
+CHARSETS['Q'] = {
+  '@': 'à',
+  '[': 'â',
+  '\\': 'ç',
+  ']': 'ê',
+  '^': 'î',
+  '`': 'ô',
+  '{': 'é',
+  '|': 'ù',
+  '}': 'è',
+  '~': 'û'
+};
+
+/**
+ * German character set
+ * ESC (K
+ * Reference: http://vt100.net/docs/vt220-rm/table2-10.html
+ */
+CHARSETS['K'] = {
+  '@': '§',
+  '[': 'Ä',
+  '\\': 'Ö',
+  ']': 'Ü',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'ü',
+  '~': 'ß'
+};
+
+/**
+ * Italian character set
+ * ESC (Y
+ * Reference: http://vt100.net/docs/vt220-rm/table2-11.html
+ */
+CHARSETS['Y'] = {
+  '#': '£',
+  '@': '§',
+  '[': '°',
+  '\\': 'ç',
+  ']': 'é',
+  '`': 'ù',
+  '{': 'à',
+  '|': 'ò',
+  '}': 'è',
+  '~': 'ì'
+};
+
+/**
+ * Norwegian/Danish character set
+ * ESC (E or ESC (6
+ * Reference: http://vt100.net/docs/vt220-rm/table2-12.html
+ */
+CHARSETS['E'] =
+CHARSETS['6'] = {
+  '@': 'Ä',
+  '[': 'Æ',
+  '\\': 'Ø',
+  ']': 'Å',
+  '^': 'Ü',
+  '`': 'ä',
+  '{': 'æ',
+  '|': 'ø',
+  '}': 'å',
+  '~': 'ü'
+};
+
+/**
+ * Spanish character set
+ * ESC (Z
+ * Reference: http://vt100.net/docs/vt220-rm/table2-13.html
+ */
+CHARSETS['Z'] = {
+  '#': '£',
+  '@': '§',
+  '[': '¡',
+  '\\': 'Ñ',
+  ']': '¿',
+  '{': '°',
+  '|': 'ñ',
+  '}': 'ç'
+};
+
+/**
+ * Swedish character set
+ * ESC (H or ESC (7
+ * Reference: http://vt100.net/docs/vt220-rm/table2-14.html
+ */
+CHARSETS['H'] =
+CHARSETS['7'] = {
+  '@': 'É',
+  '[': 'Ä',
+  '\\': 'Ö',
+  ']': 'Å',
+  '^': 'Ü',
+  '`': 'é',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'å',
+  '~': 'ü'
+};
+
+/**
+ * Swiss character set
+ * ESC (=
+ * Reference: http://vt100.net/docs/vt220-rm/table2-15.html
+ */
+CHARSETS['='] = {
+  '#': 'ù',
+  '@': 'à',
+  '[': 'é',
+  '\\': 'ç',
+  ']': 'ê',
+  '^': 'î',
+  '_': 'è',
+  '`': 'ô',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'ü',
+  '~': 'û'
+};
diff --git a/node_modules/xterm/src/common/data/EscapeSequences.ts b/node_modules/xterm/src/common/data/EscapeSequences.ts
new file mode 100644 (file)
index 0000000..e35f01d
--- /dev/null
@@ -0,0 +1,150 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/**
+ * C0 control codes
+ * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes
+ */
+export namespace C0 {
+  /** Null (Caret = ^@, C = \0) */
+  export const NUL = '\x00';
+  /** Start of Heading (Caret = ^A) */
+  export const SOH = '\x01';
+  /** Start of Text (Caret = ^B) */
+  export const STX = '\x02';
+  /** End of Text (Caret = ^C) */
+  export const ETX = '\x03';
+  /** End of Transmission (Caret = ^D) */
+  export const EOT = '\x04';
+  /** Enquiry (Caret = ^E) */
+  export const ENQ = '\x05';
+  /** Acknowledge (Caret = ^F) */
+  export const ACK = '\x06';
+  /** Bell (Caret = ^G, C = \a) */
+  export const BEL = '\x07';
+  /** Backspace (Caret = ^H, C = \b) */
+  export const BS  = '\x08';
+  /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \t) */
+  export const HT  = '\x09';
+  /** Line Feed (Caret = ^J, C = \n) */
+  export const LF  = '\x0a';
+  /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \v) */
+  export const VT  = '\x0b';
+  /** Form Feed (Caret = ^L, C = \f) */
+  export const FF  = '\x0c';
+  /** Carriage Return (Caret = ^M, C = \r) */
+  export const CR  = '\x0d';
+  /** Shift Out (Caret = ^N) */
+  export const SO  = '\x0e';
+  /** Shift In (Caret = ^O) */
+  export const SI  = '\x0f';
+  /** Data Link Escape (Caret = ^P) */
+  export const DLE = '\x10';
+  /** Device Control One (XON) (Caret = ^Q) */
+  export const DC1 = '\x11';
+  /** Device Control Two (Caret = ^R) */
+  export const DC2 = '\x12';
+  /** Device Control Three (XOFF) (Caret = ^S) */
+  export const DC3 = '\x13';
+  /** Device Control Four (Caret = ^T) */
+  export const DC4 = '\x14';
+  /** Negative Acknowledge (Caret = ^U) */
+  export const NAK = '\x15';
+  /** Synchronous Idle (Caret = ^V) */
+  export const SYN = '\x16';
+  /** End of Transmission Block (Caret = ^W) */
+  export const ETB = '\x17';
+  /** Cancel (Caret = ^X) */
+  export const CAN = '\x18';
+  /** End of Medium (Caret = ^Y) */
+  export const EM  = '\x19';
+  /** Substitute (Caret = ^Z) */
+  export const SUB = '\x1a';
+  /** Escape (Caret = ^[, C = \e) */
+  export const ESC = '\x1b';
+  /** File Separator (Caret = ^\) */
+  export const FS  = '\x1c';
+  /** Group Separator (Caret = ^]) */
+  export const GS  = '\x1d';
+  /** Record Separator (Caret = ^^) */
+  export const RS  = '\x1e';
+  /** Unit Separator (Caret = ^_) */
+  export const US  = '\x1f';
+  /** Space */
+  export const SP  = '\x20';
+  /** Delete (Caret = ^?) */
+  export const DEL = '\x7f';
+}
+
+/**
+ * C1 control codes
+ * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes
+ */
+export namespace C1 {
+  /** padding character */
+  export const PAD = '\x80';
+  /** High Octet Preset */
+  export const HOP = '\x81';
+  /** Break Permitted Here */
+  export const BPH = '\x82';
+  /** No Break Here */
+  export const NBH = '\x83';
+  /** Index */
+  export const IND = '\x84';
+  /** Next Line */
+  export const NEL = '\x85';
+  /** Start of Selected Area */
+  export const SSA = '\x86';
+  /** End of Selected Area */
+  export const ESA = '\x87';
+  /** Horizontal Tabulation Set */
+  export const HTS = '\x88';
+  /** Horizontal Tabulation With Justification */
+  export const HTJ = '\x89';
+  /** Vertical Tabulation Set */
+  export const VTS = '\x8a';
+  /** Partial Line Down */
+  export const PLD = '\x8b';
+  /** Partial Line Up */
+  export const PLU = '\x8c';
+  /** Reverse Index */
+  export const RI = '\x8d';
+  /** Single-Shift 2 */
+  export const SS2 = '\x8e';
+  /** Single-Shift 3 */
+  export const SS3 = '\x8f';
+  /** Device Control String */
+  export const DCS = '\x90';
+  /** Private Use 1 */
+  export const PU1 = '\x91';
+  /** Private Use 2 */
+  export const PU2 = '\x92';
+  /** Set Transmit State */
+  export const STS = '\x93';
+  /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */
+  export const CCH = '\x94';
+  /** Message Waiting */
+  export const MW = '\x95';
+  /** Start of Protected Area */
+  export const SPA = '\x96';
+  /** End of Protected Area */
+  export const EPA = '\x97';
+  /** Start of String */
+  export const SOS = '\x98';
+  /** Single Graphic Character Introducer */
+  export const SGCI = '\x99';
+  /** Single Character Introducer */
+  export const SCI = '\x9a';
+  /** Control Sequence Introducer */
+  export const CSI = '\x9b';
+  /** String Terminator */
+  export const ST = '\x9c';
+  /** Operating System Command */
+  export const OSC = '\x9d';
+  /** Privacy Message */
+  export const PM = '\x9e';
+  /** Application Program Command */
+  export const APC = '\x9f';
+}
diff --git a/node_modules/xterm/src/common/input/Keyboard.ts b/node_modules/xterm/src/common/input/Keyboard.ts
new file mode 100644 (file)
index 0000000..1bf378c
--- /dev/null
@@ -0,0 +1,372 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * @license MIT
+ */
+
+import { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types';
+import { C0 } from 'common/data/EscapeSequences';
+
+// reg + shift key mappings for digits and special chars
+const KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = {
+  // digits 0-9
+  48: ['0', ')'],
+  49: ['1', '!'],
+  50: ['2', '@'],
+  51: ['3', '#'],
+  52: ['4', '$'],
+  53: ['5', '%'],
+  54: ['6', '^'],
+  55: ['7', '&'],
+  56: ['8', '*'],
+  57: ['9', '('],
+
+  // special chars
+  186: [';', ':'],
+  187: ['=', '+'],
+  188: [',', '<'],
+  189: ['-', '_'],
+  190: ['.', '>'],
+  191: ['/', '?'],
+  192: ['`', '~'],
+  219: ['[', '{'],
+  220: ['\\', '|'],
+  221: [']', '}'],
+  222: ['\'', '"']
+};
+
+export function evaluateKeyboardEvent(
+  ev: IKeyboardEvent,
+  applicationCursorMode: boolean,
+  isMac: boolean,
+  macOptionIsMeta: boolean
+): IKeyboardResult {
+  const result: IKeyboardResult = {
+    type: KeyboardResultType.SEND_KEY,
+    // Whether to cancel event propagation (NOTE: this may not be needed since the event is
+    // canceled at the end of keyDown
+    cancel: false,
+    // The new key even to emit
+    key: undefined
+  };
+  const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);
+  switch (ev.keyCode) {
+    case 0:
+      if (ev.key === 'UIKeyInputUpArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OA';
+        } else {
+          result.key = C0.ESC + '[A';
+        }
+      }
+      else if (ev.key === 'UIKeyInputLeftArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OD';
+        } else {
+          result.key = C0.ESC + '[D';
+        }
+      }
+      else if (ev.key === 'UIKeyInputRightArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OC';
+        } else {
+          result.key = C0.ESC + '[C';
+        }
+      }
+      else if (ev.key === 'UIKeyInputDownArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OB';
+        } else {
+          result.key = C0.ESC + '[B';
+        }
+      }
+      break;
+    case 8:
+      // backspace
+      if (ev.shiftKey) {
+        result.key = C0.BS; // ^H
+        break;
+      } else if (ev.altKey) {
+        result.key = C0.ESC + C0.DEL; // \e ^?
+        break;
+      }
+      result.key = C0.DEL; // ^?
+      break;
+    case 9:
+      // tab
+      if (ev.shiftKey) {
+        result.key = C0.ESC + '[Z';
+        break;
+      }
+      result.key = C0.HT;
+      result.cancel = true;
+      break;
+    case 13:
+      // return/enter
+      result.key = C0.CR;
+      result.cancel = true;
+      break;
+    case 27:
+      // escape
+      result.key = C0.ESC;
+      result.cancel = true;
+      break;
+    case 37:
+      // left-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
+        // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (result.key === C0.ESC + '[1;3D') {
+          result.key = C0.ESC + (isMac ? 'b' : '[1;5D');
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OD';
+      } else {
+        result.key = C0.ESC + '[D';
+      }
+      break;
+    case 39:
+      // right-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
+        // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (result.key === C0.ESC + '[1;3C') {
+          result.key = C0.ESC + (isMac ? 'f' : '[1;5C');
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OC';
+      } else {
+        result.key = C0.ESC + '[C';
+      }
+      break;
+    case 38:
+      // up-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
+        // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (!isMac && result.key === C0.ESC + '[1;3A') {
+          result.key = C0.ESC + '[1;5A';
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OA';
+      } else {
+        result.key = C0.ESC + '[A';
+      }
+      break;
+    case 40:
+      // down-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
+        // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (!isMac && result.key === C0.ESC + '[1;3B') {
+          result.key = C0.ESC + '[1;5B';
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OB';
+      } else {
+        result.key = C0.ESC + '[B';
+      }
+      break;
+    case 45:
+      // insert
+      if (!ev.shiftKey && !ev.ctrlKey) {
+        // <Ctrl> or <Shift> + <Insert> are used to
+        // copy-paste on some systems.
+        result.key = C0.ESC + '[2~';
+      }
+      break;
+    case 46:
+      // delete
+      if (modifiers) {
+        result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[3~';
+      }
+      break;
+    case 36:
+      // home
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OH';
+      } else {
+        result.key = C0.ESC + '[H';
+      }
+      break;
+    case 35:
+      // end
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OF';
+      } else {
+        result.key = C0.ESC + '[F';
+      }
+      break;
+    case 33:
+      // page up
+      if (ev.shiftKey) {
+        result.type = KeyboardResultType.PAGE_UP;
+      } else {
+        result.key = C0.ESC + '[5~';
+      }
+      break;
+    case 34:
+      // page down
+      if (ev.shiftKey) {
+        result.type = KeyboardResultType.PAGE_DOWN;
+      } else {
+        result.key = C0.ESC + '[6~';
+      }
+      break;
+    case 112:
+      // F1-F12
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
+      } else {
+        result.key = C0.ESC + 'OP';
+      }
+      break;
+    case 113:
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
+      } else {
+        result.key = C0.ESC + 'OQ';
+      }
+      break;
+    case 114:
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
+      } else {
+        result.key = C0.ESC + 'OR';
+      }
+      break;
+    case 115:
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
+      } else {
+        result.key = C0.ESC + 'OS';
+      }
+      break;
+    case 116:
+      if (modifiers) {
+        result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[15~';
+      }
+      break;
+    case 117:
+      if (modifiers) {
+        result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[17~';
+      }
+      break;
+    case 118:
+      if (modifiers) {
+        result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[18~';
+      }
+      break;
+    case 119:
+      if (modifiers) {
+        result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[19~';
+      }
+      break;
+    case 120:
+      if (modifiers) {
+        result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[20~';
+      }
+      break;
+    case 121:
+      if (modifiers) {
+        result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[21~';
+      }
+      break;
+    case 122:
+      if (modifiers) {
+        result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[23~';
+      }
+      break;
+    case 123:
+      if (modifiers) {
+        result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[24~';
+      }
+      break;
+    default:
+      // a-z and space
+      if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
+        if (ev.keyCode >= 65 && ev.keyCode <= 90) {
+          result.key = String.fromCharCode(ev.keyCode - 64);
+        } else if (ev.keyCode === 32) {
+          result.key = C0.NUL;
+        } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
+          // escape, file sep, group sep, record sep, unit sep
+          result.key = String.fromCharCode(ev.keyCode - 51 + 27);
+        } else if (ev.keyCode === 56) {
+          result.key = C0.DEL;
+        } else if (ev.keyCode === 219) {
+          result.key = C0.ESC;
+        } else if (ev.keyCode === 220) {
+          result.key = C0.FS;
+        } else if (ev.keyCode === 221) {
+          result.key = C0.GS;
+        }
+      } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) {
+        // On macOS this is a third level shift when !macOptionIsMeta. Use <Esc> instead.
+        const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];
+        const key = keyMapping && keyMapping[!ev.shiftKey ? 0 : 1];
+        if (key) {
+          result.key = C0.ESC + key;
+        } else if (ev.keyCode >= 65 && ev.keyCode <= 90) {
+          const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;
+          result.key = C0.ESC + String.fromCharCode(keyCode);
+        }
+      } else if (isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {
+        if (ev.keyCode === 65) { // cmd + a
+          result.type = KeyboardResultType.SELECT_ALL;
+        }
+      } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) {
+        // Include only keys that that result in a _single_ character; don't include num lock, volume up, etc.
+        result.key = ev.key;
+      } else if (ev.key && ev.ctrlKey) {
+        if (ev.key === '_') { // ^_
+          result.key = C0.US;
+        }
+      }
+      break;
+  }
+
+  return result;
+}
diff --git a/node_modules/xterm/src/common/input/TextDecoder.ts b/node_modules/xterm/src/common/input/TextDecoder.ts
new file mode 100644 (file)
index 0000000..397d25a
--- /dev/null
@@ -0,0 +1,342 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/**
+ * Polyfill - Convert UTF32 codepoint into JS string.
+ * Note: The built-in String.fromCodePoint happens to be much slower
+ *       due to additional sanity checks. We can avoid them since
+ *       we always operate on legal UTF32 (granted by the input decoders)
+ *       and use this faster version instead.
+ */
+export function stringFromCodePoint(codePoint: number): string {
+  if (codePoint > 0xFFFF) {
+    codePoint -= 0x10000;
+    return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00);
+  }
+  return String.fromCharCode(codePoint);
+}
+
+/**
+ * Convert UTF32 char codes into JS string.
+ * Basically the same as `stringFromCodePoint` but for multiple codepoints
+ * in a loop (which is a lot faster).
+ */
+export function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string {
+  let result = '';
+  for (let i = start; i < end; ++i) {
+    let codepoint = data[i];
+    if (codepoint > 0xFFFF) {
+      // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate pair
+      // conversion rules:
+      //  - subtract 0x10000 from code point, leaving a 20 bit number
+      //  - add high 10 bits to 0xD800  --> first surrogate
+      //  - add low 10 bits to 0xDC00   --> second surrogate
+      codepoint -= 0x10000;
+      result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00);
+    } else {
+      result += String.fromCharCode(codepoint);
+    }
+  }
+  return result;
+}
+
+/**
+ * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints.
+ * To keep the decoder in line with JS strings it handles single surrogates as UCS2.
+ */
+export class StringToUtf32 {
+  private _interim: number = 0;
+
+  /**
+   * Clears interim and resets decoder to clean state.
+   */
+  public clear(): void {
+    this._interim = 0;
+  }
+
+  /**
+   * Decode JS string to UTF32 codepoints.
+   * The methods assumes stream input and will store partly transmitted
+   * surrogate pairs and decode them with the next data chunk.
+   * Note: The method does no bound checks for target, therefore make sure
+   * the provided input data does not exceed the size of `target`.
+   * Returns the number of written codepoints in `target`.
+   */
+  decode(input: string, target: Uint32Array): number {
+    const length = input.length;
+
+    if (!length) {
+      return 0;
+    }
+
+    let size = 0;
+    let startPos = 0;
+
+    // handle leftover surrogate high
+    if (this._interim) {
+      const second = input.charCodeAt(startPos++);
+      if (0xDC00 <= second && second <= 0xDFFF) {
+        target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+      } else {
+        // illegal codepoint (USC2 handling)
+        target[size++] = this._interim;
+        target[size++] = second;
+      }
+      this._interim = 0;
+    }
+
+    for (let i = startPos; i < length; ++i) {
+      const code = input.charCodeAt(i);
+      // surrogate pair first
+      if (0xD800 <= code && code <= 0xDBFF) {
+        if (++i >= length) {
+          this._interim = code;
+          return size;
+        }
+        const second = input.charCodeAt(i);
+        if (0xDC00 <= second && second <= 0xDFFF) {
+          target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+        } else {
+          // illegal codepoint (USC2 handling)
+          target[size++] = code;
+          target[size++] = second;
+        }
+        continue;
+      }
+      target[size++] = code;
+    }
+    return size;
+  }
+}
+
+/**
+ * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints.
+ */
+export class Utf8ToUtf32 {
+  public interim: Uint8Array = new Uint8Array(3);
+
+  /**
+   * Clears interim bytes and resets decoder to clean state.
+   */
+  public clear(): void {
+    this.interim.fill(0);
+  }
+
+  /**
+   * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`.
+   * The methods assumes stream input and will store partly transmitted bytes
+   * and decode them with the next data chunk.
+   * Note: The method does no bound checks for target, therefore make sure
+   * the provided data chunk does not exceed the size of `target`.
+   * Returns the number of written codepoints in `target`.
+   */
+  decode(input: Uint8Array, target: Uint32Array): number {
+    const length = input.length;
+
+    if (!length) {
+      return 0;
+    }
+
+    let size = 0;
+    let byte1: number;
+    let byte2: number;
+    let byte3: number;
+    let byte4: number;
+    let codepoint = 0;
+    let startPos = 0;
+
+    // handle leftover bytes
+    if (this.interim[0]) {
+      let discardInterim = false;
+      let cp = this.interim[0];
+      cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07);
+      let pos = 0;
+      let tmp: number;
+      while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) {
+        cp <<= 6;
+        cp |= tmp;
+      }
+      // missing bytes - read ahead from input
+      const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4;
+      const missing = type - pos;
+      while (startPos < missing) {
+        if (startPos >= length) {
+          return 0;
+        }
+        tmp = input[startPos++];
+        if ((tmp & 0xC0) !== 0x80) {
+          // wrong continuation, discard interim bytes completely
+          startPos--;
+          discardInterim = true;
+          break;
+        } else {
+          // need to save so we can continue short inputs in next call
+          this.interim[pos++] = tmp;
+          cp <<= 6;
+          cp |= tmp & 0x3F;
+        }
+      }
+      if (!discardInterim) {
+        // final test is type dependent
+        if (type === 2) {
+          if (cp < 0x80) {
+            // wrong starter byte
+            startPos--;
+          } else {
+            target[size++] = cp;
+          }
+        } else if (type === 3) {
+          if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF)) {
+            // illegal codepoint
+          } else {
+            target[size++] = cp;
+          }
+        } else {
+          if (cp < 0x010000 || cp > 0x10FFFF) {
+            // illegal codepoint
+          } else {
+            target[size++] = cp;
+          }
+        }
+      }
+      this.interim.fill(0);
+    }
+
+    // loop through input
+    const fourStop = length - 4;
+    let i = startPos;
+    while (i < length) {
+      /**
+       * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars.
+       * This is a compromise between speed gain for ASCII
+       * and penalty for non ASCII:
+       * For best ASCII performance the char should be stored directly into target,
+       * but even a single attempt to write to target and compare afterwards
+       * penalizes non ASCII really bad (-50%), thus we load the char into byteX first,
+       * which reduces ASCII performance by ~15%.
+       * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible
+       * compared to the gains.
+       * Note that this optimization only takes place for 4 consecutive ASCII chars,
+       * for any shorter it bails out. Worst case - all 4 bytes being read but
+       * thrown away due to the last being a non ASCII char (-10% performance).
+       */
+      while (i < fourStop
+        && !((byte1 = input[i]) & 0x80)
+        && !((byte2 = input[i + 1]) & 0x80)
+        && !((byte3 = input[i + 2]) & 0x80)
+        && !((byte4 = input[i + 3]) & 0x80))
+      {
+        target[size++] = byte1;
+        target[size++] = byte2;
+        target[size++] = byte3;
+        target[size++] = byte4;
+        i += 4;
+      }
+
+      // reread byte1
+      byte1 = input[i++];
+
+      // 1 byte
+      if (byte1 < 0x80) {
+        target[size++] = byte1;
+
+        // 2 bytes
+      } else if ((byte1 & 0xE0) === 0xC0) {
+        if (i >= length) {
+          this.interim[0] = byte1;
+          return size;
+        }
+        byte2 = input[i++];
+        if ((byte2 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F);
+        if (codepoint < 0x80) {
+          // wrong starter byte
+          i--;
+          continue;
+        }
+        target[size++] = codepoint;
+
+        // 3 bytes
+      } else if ((byte1 & 0xF0) === 0xE0) {
+        if (i >= length) {
+          this.interim[0] = byte1;
+          return size;
+        }
+        byte2 = input[i++];
+        if ((byte2 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        if (i >= length) {
+          this.interim[0] = byte1;
+          this.interim[1] = byte2;
+          return size;
+        }
+        byte3 = input[i++];
+        if ((byte3 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F);
+        if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
+          // illegal codepoint, no i-- here
+          continue;
+        }
+        target[size++] = codepoint;
+
+        // 4 bytes
+      } else if ((byte1 & 0xF8) === 0xF0) {
+        if (i >= length) {
+          this.interim[0] = byte1;
+          return size;
+        }
+        byte2 = input[i++];
+        if ((byte2 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        if (i >= length) {
+          this.interim[0] = byte1;
+          this.interim[1] = byte2;
+          return size;
+        }
+        byte3 = input[i++];
+        if ((byte3 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        if (i >= length) {
+          this.interim[0] = byte1;
+          this.interim[1] = byte2;
+          this.interim[2] = byte3;
+          return size;
+        }
+        byte4 = input[i++];
+        if ((byte4 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F);
+        if (codepoint < 0x010000 || codepoint > 0x10FFFF) {
+          // illegal codepoint, no i-- here
+          continue;
+        }
+        target[size++] = codepoint;
+      } else {
+        // illegal byte, just skip
+      }
+    }
+    return size;
+  }
+}
diff --git a/node_modules/xterm/src/common/input/WriteBuffer.ts b/node_modules/xterm/src/common/input/WriteBuffer.ts
new file mode 100644 (file)
index 0000000..c7d8245
--- /dev/null
@@ -0,0 +1,110 @@
+
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+declare const setTimeout: (handler: () => void, timeout?: number) => void;
+
+/**
+ * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input.
+ * Enable flow control to avoid this limit and make sure that your backend correctly
+ * propagates this to the underlying pty. (see docs for further instructions)
+ * Since this limit is meant as a safety parachute to prevent browser crashs,
+ * it is set to a very high number. Typically xterm.js gets unresponsive with
+ * a 100 times lower number (>500 kB).
+ */
+const DISCARD_WATERMARK = 50000000; // ~50 MB
+
+/**
+ * The max number of ms to spend on writes before allowing the renderer to
+ * catch up with a 0ms setTimeout. A value of < 33 to keep us close to
+ * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS
+ * depends on the time it takes for the renderer to draw the frame.
+ */
+const WRITE_TIMEOUT_MS = 12;
+
+/**
+ * Threshold of max held chunks in the write buffer, that were already processed.
+ * This is a tradeoff between extensive write buffer shifts (bad runtime) and high
+ * memory consumption by data thats not used anymore.
+ */
+const WRITE_BUFFER_LENGTH_THRESHOLD = 50;
+
+export class WriteBuffer {
+  private _writeBuffer: (string | Uint8Array)[] = [];
+  private _callbacks: ((() => void) | undefined)[] = [];
+  private _pendingData = 0;
+  private _bufferOffset = 0;
+
+  constructor(private _action: (data: string | Uint8Array) => void) { }
+
+  public writeSync(data: string | Uint8Array): void {
+    // force sync processing on pending data chunks to avoid in-band data scrambling
+    // does the same as innerWrite but without event loop
+    if (this._writeBuffer.length) {
+      for (let i = this._bufferOffset; i < this._writeBuffer.length; ++i) {
+        const data = this._writeBuffer[i];
+        const cb = this._callbacks[i];
+        this._action(data);
+        if (cb) cb();
+      }
+      // reset all to avoid reprocessing of chunks with scheduled innerWrite call
+      this._writeBuffer = [];
+      this._callbacks = [];
+      this._pendingData = 0;
+      // stop scheduled innerWrite by offset > length condition
+      this._bufferOffset = 0x7FFFFFFF;
+    }
+    // handle current data chunk
+    this._action(data);
+  }
+
+  public write(data: string | Uint8Array, callback?: () => void): void {
+    if (this._pendingData > DISCARD_WATERMARK) {
+      throw new Error('write data discarded, use flow control to avoid losing data');
+    }
+
+    // schedule chunk processing for next event loop run
+    if (!this._writeBuffer.length) {
+      this._bufferOffset = 0;
+      setTimeout(() => this._innerWrite());
+    }
+
+    this._pendingData += data.length;
+    this._writeBuffer.push(data);
+    this._callbacks.push(callback);
+  }
+
+  protected _innerWrite(): void {
+    const startTime = Date.now();
+    while (this._writeBuffer.length > this._bufferOffset) {
+      const data = this._writeBuffer[this._bufferOffset];
+      const cb = this._callbacks[this._bufferOffset];
+      this._bufferOffset++;
+
+      this._action(data);
+      this._pendingData -= data.length;
+      if (cb) cb();
+
+      if (Date.now() - startTime >= WRITE_TIMEOUT_MS) {
+        break;
+      }
+    }
+    if (this._writeBuffer.length > this._bufferOffset) {
+      // Allow renderer to catch up before processing the next batch
+      // trim already processed chunks if we are above threshold
+      if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) {
+        this._writeBuffer = this._writeBuffer.slice(this._bufferOffset);
+        this._callbacks = this._callbacks.slice(this._bufferOffset);
+        this._bufferOffset = 0;
+      }
+      setTimeout(() => this._innerWrite(), 0);
+    } else {
+      this._writeBuffer = [];
+      this._callbacks = [];
+      this._pendingData = 0;
+      this._bufferOffset = 0;
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/Constants.ts b/node_modules/xterm/src/common/parser/Constants.ts
new file mode 100644 (file)
index 0000000..85156c3
--- /dev/null
@@ -0,0 +1,58 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/**
+ * Internal states of EscapeSequenceParser.
+ */
+export const enum ParserState {
+  GROUND = 0,
+  ESCAPE = 1,
+  ESCAPE_INTERMEDIATE = 2,
+  CSI_ENTRY = 3,
+  CSI_PARAM = 4,
+  CSI_INTERMEDIATE = 5,
+  CSI_IGNORE = 6,
+  SOS_PM_APC_STRING = 7,
+  OSC_STRING = 8,
+  DCS_ENTRY = 9,
+  DCS_PARAM = 10,
+  DCS_IGNORE = 11,
+  DCS_INTERMEDIATE = 12,
+  DCS_PASSTHROUGH = 13
+}
+
+/**
+* Internal actions of EscapeSequenceParser.
+*/
+export const enum ParserAction {
+  IGNORE = 0,
+  ERROR = 1,
+  PRINT = 2,
+  EXECUTE = 3,
+  OSC_START = 4,
+  OSC_PUT = 5,
+  OSC_END = 6,
+  CSI_DISPATCH = 7,
+  PARAM = 8,
+  COLLECT = 9,
+  ESC_DISPATCH = 10,
+  CLEAR = 11,
+  DCS_HOOK = 12,
+  DCS_PUT = 13,
+  DCS_UNHOOK = 14
+}
+
+/**
+ * Internal states of OscParser.
+ */
+export const enum OscState {
+  START = 0,
+  ID = 1,
+  PAYLOAD = 2,
+  ABORT = 3
+}
+
+// payload limit for OSC and DCS
+export const PAYLOAD_LIMIT = 10000000;
diff --git a/node_modules/xterm/src/common/parser/DcsParser.ts b/node_modules/xterm/src/common/parser/DcsParser.ts
new file mode 100644 (file)
index 0000000..4622c4a
--- /dev/null
@@ -0,0 +1,146 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+import { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType } from 'common/parser/Types';
+import { utf32ToString } from 'common/input/TextDecoder';
+import { Params } from 'common/parser/Params';
+import { PAYLOAD_LIMIT } from 'common/parser/Constants';
+
+const EMPTY_HANDLERS: IDcsHandler[] = [];
+
+export class DcsParser implements IDcsParser {
+  private _handlers: IHandlerCollection<IDcsHandler> = Object.create(null);
+  private _active: IDcsHandler[] = EMPTY_HANDLERS;
+  private _ident: number = 0;
+  private _handlerFb: DcsFallbackHandlerType = () => {};
+
+  public dispose(): void {
+    this._handlers = Object.create(null);
+    this._handlerFb = () => {};
+  }
+
+  public addHandler(ident: number, handler: IDcsHandler): IDisposable {
+    if (this._handlers[ident] === undefined) {
+      this._handlers[ident] = [];
+    }
+    const handlerList = this._handlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+
+  public setHandler(ident: number, handler: IDcsHandler): void {
+    this._handlers[ident] = [handler];
+  }
+
+  public clearHandler(ident: number): void {
+    if (this._handlers[ident]) delete this._handlers[ident];
+  }
+
+  public setHandlerFallback(handler: DcsFallbackHandlerType): void {
+    this._handlerFb = handler;
+  }
+
+  public reset(): void {
+    if (this._active.length) {
+      this.unhook(false);
+    }
+    this._active = EMPTY_HANDLERS;
+    this._ident = 0;
+  }
+
+  public hook(ident: number, params: IParams): void {
+    // always reset leftover handlers
+    this.reset();
+    this._ident = ident;
+    this._active = this._handlers[ident] || EMPTY_HANDLERS;
+    if (!this._active.length) {
+      this._handlerFb(this._ident, 'HOOK', params);
+    } else {
+      for (let j = this._active.length - 1; j >= 0; j--) {
+        this._active[j].hook(params);
+      }
+    }
+  }
+
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (!this._active.length) {
+      this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end));
+    } else {
+      for (let j = this._active.length - 1; j >= 0; j--) {
+        this._active[j].put(data, start, end);
+      }
+    }
+  }
+
+  public unhook(success: boolean): void {
+    if (!this._active.length) {
+      this._handlerFb(this._ident, 'UNHOOK', success);
+    } else {
+      let j = this._active.length - 1;
+      for (; j >= 0; j--) {
+        if (this._active[j].unhook(success) !== false) {
+          break;
+        }
+      }
+      j--;
+      // cleanup left over handlers
+      for (; j >= 0; j--) {
+        this._active[j].unhook(false);
+      }
+    }
+    this._active = EMPTY_HANDLERS;
+    this._ident = 0;
+  }
+}
+
+/**
+ * Convenient class to create a DCS handler from a single callback function.
+ * Note: The payload is currently limited to 50 MB (hardcoded).
+ */
+export class DcsHandler implements IDcsHandler {
+  private _data = '';
+  private _params: IParams | undefined;
+  private _hitLimit: boolean = false;
+
+  constructor(private _handler: (data: string, params: IParams) => any) {}
+
+  public hook(params: IParams): void {
+    this._params = params.clone();
+    this._data = '';
+    this._hitLimit = false;
+  }
+
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (this._hitLimit) {
+      return;
+    }
+    this._data += utf32ToString(data, start, end);
+    if (this._data.length > PAYLOAD_LIMIT) {
+      this._data = '';
+      this._hitLimit = true;
+    }
+  }
+
+  public unhook(success: boolean): any {
+    let ret;
+    if (this._hitLimit) {
+      ret = false;
+    } else if (success) {
+      ret = this._handler(this._data, this._params ? this._params : new Params());
+    }
+    this._params = undefined;
+    this._data = '';
+    this._hitLimit = false;
+    return ret;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts b/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts
new file mode 100644 (file)
index 0000000..bc0b620
--- /dev/null
@@ -0,0 +1,636 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType } from 'common/parser/Types';
+import { ParserState, ParserAction } from 'common/parser/Constants';
+import { Disposable } from 'common/Lifecycle';
+import { IDisposable } from 'common/Types';
+import { fill } from 'common/TypedArrayUtils';
+import { Params } from 'common/parser/Params';
+import { OscParser } from 'common/parser/OscParser';
+import { DcsParser } from 'common/parser/DcsParser';
+
+/**
+ * Table values are generated like this:
+ *    index:  currentState << TableValue.INDEX_STATE_SHIFT | charCode
+ *    value:  action << TableValue.TRANSITION_ACTION_SHIFT | nextState
+ */
+const enum TableAccess {
+  TRANSITION_ACTION_SHIFT = 4,
+  TRANSITION_STATE_MASK = 15,
+  INDEX_STATE_SHIFT = 8
+}
+
+/**
+ * Transition table for EscapeSequenceParser.
+ */
+export class TransitionTable {
+  public table: Uint8Array;
+
+  constructor(length: number) {
+    this.table = new Uint8Array(length);
+  }
+
+  /**
+   * Set default transition.
+   * @param action default action
+   * @param next default next state
+   */
+  public setDefault(action: ParserAction, next: ParserState): void {
+    fill(this.table, action << TableAccess.TRANSITION_ACTION_SHIFT | next);
+  }
+
+  /**
+   * Add a transition to the transition table.
+   * @param code input character code
+   * @param state current parser state
+   * @param action parser action to be done
+   * @param next next parser state
+   */
+  public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {
+    this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
+  }
+
+  /**
+   * Add transitions for multiple input character codes.
+   * @param codes input character code array
+   * @param state current parser state
+   * @param action parser action to be done
+   * @param next next parser state
+   */
+  public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {
+    for (let i = 0; i < codes.length; i++) {
+      this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
+    }
+  }
+}
+
+
+// Pseudo-character placeholder for printable non-ascii characters (unicode).
+const NON_ASCII_PRINTABLE = 0xA0;
+
+
+/**
+ * VT500 compatible transition table.
+ * Taken from https://vt100.net/emu/dec_ansi_parser.
+ */
+export const VT500_TRANSITION_TABLE = (function (): TransitionTable {
+  const table: TransitionTable = new TransitionTable(4095);
+
+  // range macro for byte
+  const BYTE_VALUES = 256;
+  const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);
+  const r = (start: number, end: number) => blueprint.slice(start, end);
+
+  // Default definitions.
+  const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded
+  const EXECUTABLES = r(0x00, 0x18);
+  EXECUTABLES.push(0x19);
+  EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));
+
+  const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);
+  let state: any;
+
+  // set default transition
+  table.setDefault(ParserAction.ERROR, ParserState.GROUND);
+  // printables
+  table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
+  // global anywhere rules
+  for (state in states) {
+    table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);
+    table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);
+    table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);
+    table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator
+    table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE);  // ESC
+    table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING);  // OSC
+    table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+    table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY);  // CSI
+    table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY);  // DCS
+  }
+  // rules for executables and 7f
+  table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);
+  table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);
+  table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);
+  table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
+  table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);
+  table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);
+  table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);
+  table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);
+  table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);
+  table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);
+  table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);
+  table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);
+  table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);
+  // osc
+  table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);
+  table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
+  table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
+  table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);
+  table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
+  // sos/pm/apc does nothing
+  table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);
+  table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  // csi entries
+  table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);
+  table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);
+  table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
+  table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
+  table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
+  // esc_intermediate
+  table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
+  table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
+  table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  // dcs entry
+  table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);
+  table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
+  table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
+  table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);
+  table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
+  table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
+  table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
+  table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
+  table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
+  table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
+  table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
+  table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
+  table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
+  table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);
+  table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);
+  // special handling of unicode chars
+  table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
+  table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
+  table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
+  return table;
+})();
+
+
+/**
+ * EscapeSequenceParser.
+ * This class implements the ANSI/DEC compatible parser described by
+ * Paul Williams (https://vt100.net/emu/dec_ansi_parser).
+ *
+ * To implement custom ANSI compliant escape sequences it is not needed to
+ * alter this parser, instead consider registering a custom handler.
+ * For non ANSI compliant sequences change the transition table with
+ * the optional `transitions` constructor argument and
+ * reimplement the `parse` method.
+ *
+ * This parser is currently hardcoded to operate in ZDM (Zero Default Mode)
+ * as suggested by the original parser, thus empty parameters are set to 0.
+ * This this is not in line with the latest ECMA-48 specification
+ * (ZDM was part of the early specs and got completely removed later on).
+ *
+ * Other than the original parser from vt100.net this parser supports
+ * sub parameters in digital parameters separated by colons. Empty sub parameters
+ * are set to -1 (no ZDM for sub parameters).
+ *
+ * About prefix and intermediate bytes:
+ * This parser follows the assumptions of the vt100.net parser with these restrictions:
+ * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f
+ * - max. two intermediates are respected, byte range 0x20 .. 0x2f
+ * Note that this is not in line with ECMA-48 which does not limit either of those.
+ * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently
+ * there are no known sequences that follow the broader definition of the specification.
+ *
+ * TODO: implement error recovery hook via error handler return values
+ */
+export class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser {
+  public initialState: number;
+  public currentState: number;
+  public precedingCodepoint: number;
+
+  // buffers over several parse calls
+  protected _params: Params;
+  protected _collect: number;
+
+  // handler lookup containers
+  protected _printHandler: PrintHandlerType;
+  protected _executeHandlers: {[flag: number]: ExecuteHandlerType};
+  protected _csiHandlers: IHandlerCollection<CsiHandlerType>;
+  protected _escHandlers: IHandlerCollection<EscHandlerType>;
+  protected _oscParser: IOscParser;
+  protected _dcsParser: IDcsParser;
+  protected _errorHandler: (state: IParsingState) => IParsingState;
+
+  // fallback handlers
+  protected _printHandlerFb: PrintFallbackHandlerType;
+  protected _executeHandlerFb: ExecuteFallbackHandlerType;
+  protected _csiHandlerFb: CsiFallbackHandlerType;
+  protected _escHandlerFb: EscFallbackHandlerType;
+  protected _errorHandlerFb: (state: IParsingState) => IParsingState;
+
+  constructor(readonly TRANSITIONS: TransitionTable = VT500_TRANSITION_TABLE) {
+    super();
+
+    this.initialState = ParserState.GROUND;
+    this.currentState = this.initialState;
+    this._params = new Params(); // defaults to 32 storable params/subparams
+    this._params.addParam(0);    // ZDM
+    this._collect = 0;
+    this.precedingCodepoint = 0;
+
+    // set default fallback handlers and handler lookup containers
+    this._printHandlerFb = (data, start, end): void => { };
+    this._executeHandlerFb = (code: number): void => { };
+    this._csiHandlerFb = (ident: number, params: IParams): void => { };
+    this._escHandlerFb = (ident: number): void => { };
+    this._errorHandlerFb = (state: IParsingState): IParsingState => state;
+    this._printHandler = this._printHandlerFb;
+    this._executeHandlers = Object.create(null);
+    this._csiHandlers = Object.create(null);
+    this._escHandlers = Object.create(null);
+    this._oscParser = new OscParser();
+    this._dcsParser = new DcsParser();
+    this._errorHandler = this._errorHandlerFb;
+
+    // swallow 7bit ST (ESC+\)
+    this.setEscHandler({final: '\\'}, () => {});
+  }
+
+  protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {
+    let res = 0;
+    if (id.prefix) {
+      if (id.prefix.length > 1) {
+        throw new Error('only one byte as prefix supported');
+      }
+      res = id.prefix.charCodeAt(0);
+      if (res && 0x3c > res || res > 0x3f) {
+        throw new Error('prefix must be in range 0x3c .. 0x3f');
+      }
+    }
+    if (id.intermediates) {
+      if (id.intermediates.length > 2) {
+        throw new Error('only two bytes as intermediates are supported');
+      }
+      for (let i = 0; i < id.intermediates.length; ++i) {
+        const intermediate = id.intermediates.charCodeAt(i);
+        if (0x20 > intermediate || intermediate > 0x2f) {
+          throw new Error('intermediate must be in range 0x20 .. 0x2f');
+        }
+        res <<= 8;
+        res |= intermediate;
+      }
+    }
+    if (id.final.length !== 1) {
+      throw new Error('final must be a single byte');
+    }
+    const finalCode = id.final.charCodeAt(0);
+    if (finalRange[0] > finalCode || finalCode > finalRange[1]) {
+      throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);
+    }
+    res <<= 8;
+    res |= finalCode;
+
+    return res;
+  }
+
+  public identToString(ident: number): string {
+    const res: string[] = [];
+    while (ident) {
+      res.push(String.fromCharCode(ident & 0xFF));
+      ident >>= 8;
+    }
+    return res.reverse().join('');
+  }
+
+  public dispose(): void {
+    this._csiHandlers = Object.create(null);
+    this._executeHandlers = Object.create(null);
+    this._escHandlers = Object.create(null);
+    this._oscParser.dispose();
+    this._dcsParser.dispose();
+  }
+
+  public setPrintHandler(handler: PrintHandlerType): void {
+    this._printHandler = handler;
+  }
+  public clearPrintHandler(): void {
+    this._printHandler = this._printHandlerFb;
+  }
+
+  public addEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {
+    const ident = this._identifier(id, [0x30, 0x7e]);
+    if (this._escHandlers[ident] === undefined) {
+      this._escHandlers[ident] = [];
+    }
+    const handlerList = this._escHandlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+  public setEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): void {
+    this._escHandlers[this._identifier(id, [0x30, 0x7e])] = [handler];
+  }
+  public clearEscHandler(id: IFunctionIdentifier): void {
+    if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];
+  }
+  public setEscHandlerFallback(handler: EscFallbackHandlerType): void {
+    this._escHandlerFb = handler;
+  }
+
+  public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {
+    this._executeHandlers[flag.charCodeAt(0)] = handler;
+  }
+  public clearExecuteHandler(flag: string): void {
+    if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];
+  }
+  public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {
+    this._executeHandlerFb = handler;
+  }
+
+  public addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {
+    const ident = this._identifier(id);
+    if (this._csiHandlers[ident] === undefined) {
+      this._csiHandlers[ident] = [];
+    }
+    const handlerList = this._csiHandlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+  public setCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): void {
+    this._csiHandlers[this._identifier(id)] = [handler];
+  }
+  public clearCsiHandler(id: IFunctionIdentifier): void {
+    if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];
+  }
+  public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void {
+    this._csiHandlerFb = callback;
+  }
+
+  public addDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {
+    return this._dcsParser.addHandler(this._identifier(id), handler);
+  }
+  public setDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): void {
+    this._dcsParser.setHandler(this._identifier(id), handler);
+  }
+  public clearDcsHandler(id: IFunctionIdentifier): void {
+    this._dcsParser.clearHandler(this._identifier(id));
+  }
+  public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {
+    this._dcsParser.setHandlerFallback(handler);
+  }
+
+  public addOscHandler(ident: number, handler: IOscHandler): IDisposable {
+    return this._oscParser.addHandler(ident, handler);
+  }
+  public setOscHandler(ident: number, handler: IOscHandler): void {
+    this._oscParser.setHandler(ident, handler);
+  }
+  public clearOscHandler(ident: number): void {
+    this._oscParser.clearHandler(ident);
+  }
+  public setOscHandlerFallback(handler: OscFallbackHandlerType): void {
+    this._oscParser.setHandlerFallback(handler);
+  }
+
+  public setErrorHandler(callback: (state: IParsingState) => IParsingState): void {
+    this._errorHandler = callback;
+  }
+  public clearErrorHandler(): void {
+    this._errorHandler = this._errorHandlerFb;
+  }
+
+  public reset(): void {
+    this.currentState = this.initialState;
+    this._oscParser.reset();
+    this._dcsParser.reset();
+    this._params.reset();
+    this._params.addParam(0); // ZDM
+    this._collect = 0;
+    this.precedingCodepoint = 0;
+  }
+
+
+
+  /**
+   * Parse UTF32 codepoints in `data` up to `length`.
+   *
+   * Note: For several actions with high data load the parsing is optimized
+   * by using local read ahead loops with hardcoded conditions to
+   * avoid costly table lookups. Make sure that any change of table values
+   * will be reflected in the loop conditions as well and vice versa.
+   * Affected states/actions:
+   * - GROUND:PRINT
+   * - CSI_PARAM:PARAM
+   * - DCS_PARAM:PARAM
+   * - OSC_STRING:OSC_PUT
+   * - DCS_PASSTHROUGH:DCS_PUT
+   */
+  public parse(data: Uint32Array, length: number): void {
+    let code = 0;
+    let transition = 0;
+    let currentState = this.currentState;
+    const osc = this._oscParser;
+    const dcs = this._dcsParser;
+    let collect = this._collect;
+    const params = this._params;
+    const table: Uint8Array = this.TRANSITIONS.table;
+
+    // process input string
+    for (let i = 0; i < length; ++i) {
+      code = data[i];
+
+      // normal transition & action lookup
+      transition = table[currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];
+      switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) {
+        case ParserAction.PRINT:
+          // read ahead with loop unrolling
+          // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded
+          for (let j = i + 1; ; ++j) {
+            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+          }
+          break;
+        case ParserAction.EXECUTE:
+          if (this._executeHandlers[code]) this._executeHandlers[code]();
+          else this._executeHandlerFb(code);
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.IGNORE:
+          break;
+        case ParserAction.ERROR:
+          const inject: IParsingState = this._errorHandler(
+            {
+              position: i,
+              code,
+              currentState,
+              collect,
+              params,
+              abort: false
+            });
+          if (inject.abort) return;
+          // inject values: currently not implemented
+          break;
+        case ParserAction.CSI_DISPATCH:
+          // Trigger CSI Handler
+          const handlers = this._csiHandlers[collect << 8 | code];
+          let j = handlers ? handlers.length - 1 : -1;
+          for (; j >= 0; j--) {
+            // undefined or true means success and to stop bubbling
+            if (handlers[j](params) !== false) {
+              break;
+            }
+          }
+          if (j < 0) {
+            this._csiHandlerFb(collect << 8 | code, params);
+          }
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.PARAM:
+          // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a)
+          do {
+            switch (code) {
+              case 0x3b:
+                params.addParam(0);  // ZDM
+                break;
+              case 0x3a:
+                params.addSubParam(-1);
+                break;
+              default:  // 0x30 - 0x39
+                params.addDigit(code - 48);
+            }
+          } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);
+          i--;
+          break;
+        case ParserAction.COLLECT:
+          collect <<= 8;
+          collect |= code;
+          break;
+        case ParserAction.ESC_DISPATCH:
+          const handlersEsc = this._escHandlers[collect << 8 | code];
+          let jj = handlersEsc ? handlersEsc.length - 1 : -1;
+          for (; jj >= 0; jj--) {
+            // undefined or true means success and to stop bubbling
+            if (handlersEsc[jj]() !== false) {
+              break;
+            }
+          }
+          if (jj < 0) {
+            this._escHandlerFb(collect << 8 | code);
+          }
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.CLEAR:
+          params.reset();
+          params.addParam(0); // ZDM
+          collect = 0;
+          break;
+        case ParserAction.DCS_HOOK:
+          dcs.hook(collect << 8 | code, params);
+          break;
+        case ParserAction.DCS_PUT:
+          // inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f
+          // unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort)
+          for (let j = i + 1; ; ++j) {
+            if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {
+              dcs.put(data, i, j);
+              i = j - 1;
+              break;
+            }
+          }
+          break;
+        case ParserAction.DCS_UNHOOK:
+          dcs.unhook(code !== 0x18 && code !== 0x1a);
+          if (code === 0x1b) transition |= ParserState.ESCAPE;
+          params.reset();
+          params.addParam(0); // ZDM
+          collect = 0;
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.OSC_START:
+          osc.start();
+          break;
+        case ParserAction.OSC_PUT:
+          // inner loop: 0x20 (SP) included, 0x7F (DEL) included
+          for (let j = i + 1; ; j++) {
+            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code <= 0x9f)) {
+              osc.put(data, i, j);
+              i = j - 1;
+              break;
+            }
+          }
+          break;
+        case ParserAction.OSC_END:
+          osc.end(code !== 0x18 && code !== 0x1a);
+          if (code === 0x1b) transition |= ParserState.ESCAPE;
+          params.reset();
+          params.addParam(0); // ZDM
+          collect = 0;
+          this.precedingCodepoint = 0;
+          break;
+      }
+      currentState = transition & TableAccess.TRANSITION_STATE_MASK;
+    }
+
+    // save collected intermediates
+    this._collect = collect;
+
+    // save state
+    this.currentState = currentState;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/OscParser.ts b/node_modules/xterm/src/common/parser/OscParser.ts
new file mode 100644 (file)
index 0000000..e8c5a80
--- /dev/null
@@ -0,0 +1,203 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser } from 'common/parser/Types';
+import { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants';
+import { utf32ToString } from 'common/input/TextDecoder';
+import { IDisposable } from 'common/Types';
+
+
+export class OscParser implements IOscParser {
+  private _state = OscState.START;
+  private _id = -1;
+  private _handlers: IHandlerCollection<IOscHandler> = Object.create(null);
+  private _handlerFb: OscFallbackHandlerType = () => { };
+
+  public addHandler(ident: number, handler: IOscHandler): IDisposable {
+    if (this._handlers[ident] === undefined) {
+      this._handlers[ident] = [];
+    }
+    const handlerList = this._handlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+  public setHandler(ident: number, handler: IOscHandler): void {
+    this._handlers[ident] = [handler];
+  }
+  public clearHandler(ident: number): void {
+    if (this._handlers[ident]) delete this._handlers[ident];
+  }
+  public setHandlerFallback(handler: OscFallbackHandlerType): void {
+    this._handlerFb = handler;
+  }
+
+  public dispose(): void {
+    this._handlers = Object.create(null);
+    this._handlerFb = () => {};
+  }
+
+  public reset(): void {
+    // cleanup handlers if payload was already sent
+    if (this._state === OscState.PAYLOAD) {
+      this.end(false);
+    }
+    this._id = -1;
+    this._state = OscState.START;
+  }
+
+  private _start(): void {
+    const handlers = this._handlers[this._id];
+    if (!handlers) {
+      this._handlerFb(this._id, 'START');
+    } else {
+      for (let j = handlers.length - 1; j >= 0; j--) {
+        handlers[j].start();
+      }
+    }
+  }
+
+  private _put(data: Uint32Array, start: number, end: number): void {
+    const handlers = this._handlers[this._id];
+    if (!handlers) {
+      this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end));
+    } else {
+      for (let j = handlers.length - 1; j >= 0; j--) {
+        handlers[j].put(data, start, end);
+      }
+    }
+  }
+
+  private _end(success: boolean): void {
+    // other than the old code we always have to call .end
+    // to keep the bubbling we use `success` to indicate
+    // whether a handler should execute
+    const handlers = this._handlers[this._id];
+    if (!handlers) {
+      this._handlerFb(this._id, 'END', success);
+    } else {
+      let j = handlers.length - 1;
+      for (; j >= 0; j--) {
+        if (handlers[j].end(success) !== false) {
+          break;
+        }
+      }
+      j--;
+      // cleanup left over handlers
+      for (; j >= 0; j--) {
+        handlers[j].end(false);
+      }
+    }
+  }
+
+  public start(): void {
+    // always reset leftover handlers
+    this.reset();
+    this._id = -1;
+    this._state = OscState.ID;
+  }
+
+  /**
+   * Put data to current OSC command.
+   * Expects the identifier of the OSC command in the form
+   * OSC id ; payload ST/BEL
+   * Payload chunks are not further processed and get
+   * directly passed to the handlers.
+   */
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (this._state === OscState.ABORT) {
+      return;
+    }
+    if (this._state === OscState.ID) {
+      while (start < end) {
+        const code = data[start++];
+        if (code === 0x3b) {
+          this._state = OscState.PAYLOAD;
+          this._start();
+          break;
+        }
+        if (code < 0x30 || 0x39 < code) {
+          this._state = OscState.ABORT;
+          return;
+        }
+        if (this._id === -1) {
+          this._id = 0;
+        }
+        this._id = this._id * 10 + code - 48;
+      }
+    }
+    if (this._state === OscState.PAYLOAD && end - start > 0) {
+      this._put(data, start, end);
+    }
+  }
+
+  /**
+   * Indicates end of an OSC command.
+   * Whether the OSC got aborted or finished normally
+   * is indicated by `success`.
+   */
+  public end(success: boolean): void {
+    if (this._state === OscState.START) {
+      return;
+    }
+    // do nothing if command was faulty
+    if (this._state !== OscState.ABORT) {
+      // if we are still in ID state and get an early end
+      // means that the command has no payload thus we still have
+      // to announce START and send END right after
+      if (this._state === OscState.ID) {
+        this._start();
+      }
+      this._end(success);
+    }
+    this._id = -1;
+    this._state = OscState.START;
+  }
+}
+
+/**
+ * Convenient class to allow attaching string based handler functions
+ * as OSC handlers.
+ */
+export class OscHandler implements IOscHandler {
+  private _data = '';
+  private _hitLimit: boolean = false;
+
+  constructor(private _handler: (data: string) => any) {}
+
+  public start(): void {
+    this._data = '';
+    this._hitLimit = false;
+  }
+
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (this._hitLimit) {
+      return;
+    }
+    this._data += utf32ToString(data, start, end);
+    if (this._data.length > PAYLOAD_LIMIT) {
+      this._data = '';
+      this._hitLimit = true;
+    }
+  }
+
+  public end(success: boolean): any {
+    let ret;
+    if (this._hitLimit) {
+      ret = false;
+    } else if (success) {
+      ret = this._handler(this._data);
+    }
+    this._data = '';
+    this._hitLimit = false;
+    return ret;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/Params.ts b/node_modules/xterm/src/common/parser/Params.ts
new file mode 100644 (file)
index 0000000..47ee129
--- /dev/null
@@ -0,0 +1,229 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+import { IParams, ParamsArray } from 'common/parser/Types';
+
+// max value supported for a single param/subparam (clamped to positive int32 range)
+const MAX_VALUE = 0x7FFFFFFF;
+// max allowed subparams for a single sequence (hardcoded limitation)
+const MAX_SUBPARAMS = 256;
+
+/**
+ * Params storage class.
+ * This type is used by the parser to accumulate sequence parameters and sub parameters
+ * and transmit them to the input handler actions.
+ *
+ * NOTES:
+ *  - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy
+ *  - never read beyond `params.length - 1` (likely to contain arbitrary data)
+ *  - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params
+ *  - hardcoded limitations:
+ *    - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that)
+ *    - max. 256 sub params possible
+ *    - negative values are not allowed beside -1 (placeholder for default value)
+ *
+ * About ZDM (Zero Default Mode):
+ * ZDM is not orchestrated by this class. If the parser is in ZDM,
+ * it should add 0 for empty params, otherwise -1. This does not apply
+ * to subparams, empty subparams should always be added with -1.
+ */
+export class Params implements IParams {
+  // params store and length
+  public params: Int32Array;
+  public length: number;
+
+  // sub params store and length
+  protected _subParams: Int32Array;
+  protected _subParamsLength: number;
+
+  // sub params offsets from param: param idx --> [start, end] offset
+  private _subParamsIdx: Uint16Array;
+  private _rejectDigits: boolean;
+  private _rejectSubDigits: boolean;
+  private _digitIsSub: boolean;
+
+  /**
+   * Create a `Params` type from JS array representation.
+   */
+  public static fromArray(values: ParamsArray): Params {
+    const params = new Params();
+    if (!values.length) {
+      return params;
+    }
+    // skip leading sub params
+    for (let i = (values[0] instanceof Array) ? 1 : 0; i < values.length; ++i) {
+      const value = values[i];
+      if (value instanceof Array) {
+        for (let k = 0; k < value.length; ++k) {
+          params.addSubParam(value[k]);
+        }
+      } else {
+        params.addParam(value);
+      }
+    }
+    return params;
+  }
+
+  /**
+   * @param maxLength max length of storable parameters
+   * @param maxSubParamsLength max length of storable sub parameters
+   */
+  constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) {
+    if (maxSubParamsLength > MAX_SUBPARAMS) {
+      throw new Error('maxSubParamsLength must not be greater than 256');
+    }
+    this.params = new Int32Array(maxLength);
+    this.length = 0;
+    this._subParams = new Int32Array(maxSubParamsLength);
+    this._subParamsLength = 0;
+    this._subParamsIdx = new Uint16Array(maxLength);
+    this._rejectDigits = false;
+    this._rejectSubDigits = false;
+    this._digitIsSub = false;
+  }
+
+  /**
+   * Clone object.
+   */
+  public clone(): Params {
+    const newParams = new Params(this.maxLength, this.maxSubParamsLength);
+    newParams.params.set(this.params);
+    newParams.length = this.length;
+    newParams._subParams.set(this._subParams);
+    newParams._subParamsLength = this._subParamsLength;
+    newParams._subParamsIdx.set(this._subParamsIdx);
+    newParams._rejectDigits = this._rejectDigits;
+    newParams._rejectSubDigits = this._rejectSubDigits;
+    newParams._digitIsSub = this._digitIsSub;
+    return newParams;
+  }
+
+  /**
+   * Get a JS array representation of the current parameters and sub parameters.
+   * The array is structured as follows:
+   *    sequence: "1;2:3:4;5::6"
+   *    array   : [1, 2, [3, 4], 5, [-1, 6]]
+   */
+  public toArray(): ParamsArray {
+    const res: ParamsArray = [];
+    for (let i = 0; i < this.length; ++i) {
+      res.push(this.params[i]);
+      const start = this._subParamsIdx[i] >> 8;
+      const end = this._subParamsIdx[i] & 0xFF;
+      if (end - start > 0) {
+        res.push(Array.prototype.slice.call(this._subParams, start, end));
+      }
+    }
+    return res;
+  }
+
+  /**
+   * Reset to initial empty state.
+   */
+  public reset(): void {
+    this.length = 0;
+    this._subParamsLength = 0;
+    this._rejectDigits = false;
+    this._rejectSubDigits = false;
+    this._digitIsSub = false;
+  }
+
+  /**
+   * Add a parameter value.
+   * `Params` only stores up to `maxLength` parameters, any later
+   * parameter will be ignored.
+   * Note: VT devices only stored up to 16 values, xterm seems to
+   * store up to 30.
+   */
+  public addParam(value: number): void {
+    this._digitIsSub = false;
+    if (this.length >= this.maxLength) {
+      this._rejectDigits = true;
+      return;
+    }
+    if (value < -1) {
+      throw new Error('values lesser than -1 are not allowed');
+    }
+    this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength;
+    this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value;
+  }
+
+  /**
+   * Add a sub parameter value.
+   * The sub parameter is automatically associated with the last parameter value.
+   * Thus it is not possible to add a subparameter without any parameter added yet.
+   * `Params` only stores up to `subParamsLength` sub parameters, any later
+   * sub parameter will be ignored.
+   */
+  public addSubParam(value: number): void {
+    this._digitIsSub = true;
+    if (!this.length) {
+      return;
+    }
+    if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) {
+      this._rejectSubDigits = true;
+      return;
+    }
+    if (value < -1) {
+      throw new Error('values lesser than -1 are not allowed');
+    }
+    this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value;
+    this._subParamsIdx[this.length - 1]++;
+  }
+
+  /**
+   * Whether parameter at index `idx` has sub parameters.
+   */
+  public hasSubParams(idx: number): boolean {
+    return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0);
+  }
+
+  /**
+   * Return sub parameters for parameter at index `idx`.
+   * Note: The values are borrowed, thus you need to copy
+   * the values if you need to hold them in nonlocal scope.
+   */
+  public getSubParams(idx: number): Int32Array | null {
+    const start = this._subParamsIdx[idx] >> 8;
+    const end = this._subParamsIdx[idx] & 0xFF;
+    if (end - start > 0) {
+      return this._subParams.subarray(start, end);
+    }
+    return null;
+  }
+
+  /**
+   * Return all sub parameters as {idx: subparams} mapping.
+   * Note: The values are not borrowed.
+   */
+  public getSubParamsAll(): {[idx: number]: Int32Array} {
+    const result: {[idx: number]: Int32Array} = {};
+    for (let i = 0; i < this.length; ++i) {
+      const start = this._subParamsIdx[i] >> 8;
+      const end = this._subParamsIdx[i] & 0xFF;
+      if (end - start > 0) {
+        result[i] = this._subParams.slice(start, end);
+      }
+    }
+    return result;
+  }
+
+  /**
+   * Add a single digit value to current parameter.
+   * This is used by the parser to account digits on a char by char basis.
+   */
+  public addDigit(value: number): void {
+    let length;
+    if (this._rejectDigits
+      || !(length = this._digitIsSub ? this._subParamsLength : this.length)
+      || (this._digitIsSub && this._rejectSubDigits)
+    ) {
+      return;
+    }
+
+    const store = this._digitIsSub ? this._subParams : this.params;
+    const cur = store[length - 1];
+    store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/Types.d.ts b/node_modules/xterm/src/common/parser/Types.d.ts
new file mode 100644 (file)
index 0000000..e2fac89
--- /dev/null
@@ -0,0 +1,244 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+import { ParserState } from 'common/parser/Constants';
+
+/** sequence params serialized to js arrays */
+export type ParamsArray = (number | number[])[];
+
+/** Params constructor type. */
+export interface IParamsConstructor {
+  new(maxLength: number, maxSubParamsLength: number): IParams;
+
+  /** create params from ParamsArray */
+  fromArray(values: ParamsArray): IParams;
+}
+
+/** Interface of Params storage class. */
+export interface IParams {
+  /** from ctor */
+  maxLength: number;
+  maxSubParamsLength: number;
+
+  /** param values and its length */
+  params: Int32Array;
+  length: number;
+
+  /** methods */
+  clone(): IParams;
+  toArray(): ParamsArray;
+  reset(): void;
+  addParam(value: number): void;
+  addSubParam(value: number): void;
+  hasSubParams(idx: number): boolean;
+  getSubParams(idx: number): Int32Array | null;
+  getSubParamsAll(): {[idx: number]: Int32Array};
+}
+
+/**
+ * Internal state of EscapeSequenceParser.
+ * Used as argument of the error handler to allow
+ * introspection at runtime on parse errors.
+ * Return it with altered values to recover from
+ * faulty states (not yet supported).
+ * Set `abort` to `true` to abort the current parsing.
+ */
+export interface IParsingState {
+  // position in parse string
+  position: number;
+  // actual character code
+  code: number;
+  // current parser state
+  currentState: ParserState;
+  // collect buffer with intermediate characters
+  collect: number;
+  // params buffer
+  params: IParams;
+  // should abort (default: false)
+  abort: boolean;
+}
+
+/**
+ * Command handler interfaces.
+ */
+
+/**
+ * CSI handler types.
+ * Note: `params` is borrowed.
+ */
+export type CsiHandlerType = (params: IParams) => boolean | void;
+export type CsiFallbackHandlerType = (ident: number, params: IParams) => void;
+
+/**
+ * DCS handler types.
+ */
+export interface IDcsHandler {
+  /**
+   * Called when a DCS command starts.
+   * Prepare needed data structures here.
+   * Note: `params` is borrowed.
+   */
+  hook(params: IParams): void;
+  /**
+   * Incoming payload chunk.
+   * Note: `params` is borrowed.
+   */
+  put(data: Uint32Array, start: number, end: number): void;
+  /**
+   * End of DCS command. `success` indicates whether the
+   * command finished normally or got aborted, thus final
+   * execution of the command should depend on `success`.
+   * To save memory also cleanup data structures here.
+   */
+  unhook(success: boolean): void | boolean;
+}
+export type DcsFallbackHandlerType = (ident: number, action: 'HOOK' | 'PUT' | 'UNHOOK', payload?: any) => void;
+
+/**
+ * ESC handler types.
+ */
+export type EscHandlerType = () => boolean | void;
+export type EscFallbackHandlerType = (identifier: number) => void;
+
+/**
+ * EXECUTE handler types.
+ */
+export type ExecuteHandlerType = () => boolean | void;
+export type ExecuteFallbackHandlerType = (ident: number) => void;
+
+/**
+ * OSC handler types.
+ */
+export interface IOscHandler {
+  /**
+   * Announces start of this OSC command.
+   * Prepare needed data structures here.
+   */
+  start(): void;
+  /**
+   * Incoming data chunk.
+   * Note: Data is borrowed.
+   */
+  put(data: Uint32Array, start: number, end: number): void;
+  /**
+   * End of OSC command. `success` indicates whether the
+   * command finished normally or got aborted, thus final
+   * execution of the command should depend on `success`.
+   * To save memory also cleanup data structures here.
+   */
+  end(success: boolean): void | boolean;
+}
+export type OscFallbackHandlerType = (ident: number, action: 'START' | 'PUT' | 'END', payload?: any) => void;
+
+/**
+ * PRINT handler types.
+ */
+export type PrintHandlerType = (data: Uint32Array, start: number, end: number) => void;
+export type PrintFallbackHandlerType = PrintHandlerType;
+
+
+/**
+* EscapeSequenceParser interface.
+*/
+export interface IEscapeSequenceParser extends IDisposable {
+  /**
+   * Preceding codepoint to get REP working correctly.
+   * This must be set by the print handler as last action.
+   * It gets reset by the parser for any valid sequence beside REP itself.
+   */
+  precedingCodepoint: number;
+
+  /**
+   * Reset the parser to its initial state (handlers are kept).
+   */
+  reset(): void;
+
+  /**
+   * Parse UTF32 codepoints in `data` up to `length`.
+   * @param data The data to parse.
+   */
+  parse(data: Uint32Array, length: number): void;
+
+  /**
+   * Get string from numercial function identifier `ident`.
+   * Useful in fallback handlers which expose the low level
+   * numcerical function identifier for debugging purposes.
+   * Note: A full back translation to `IFunctionIdentifier`
+   * is not implemented.
+   */
+  identToString(ident: number): string;
+
+  setPrintHandler(handler: PrintHandlerType): void;
+  clearPrintHandler(): void;
+
+  setEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): void;
+  clearEscHandler(id: IFunctionIdentifier): void;
+  setEscHandlerFallback(handler: EscFallbackHandlerType): void;
+  addEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable;
+
+  setExecuteHandler(flag: string, handler: ExecuteHandlerType): void;
+  clearExecuteHandler(flag: string): void;
+  setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void;
+
+  setCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): void;
+  clearCsiHandler(id: IFunctionIdentifier): void;
+  setCsiHandlerFallback(callback: CsiFallbackHandlerType): void;
+  addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable;
+
+  setDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): void;
+  clearDcsHandler(id: IFunctionIdentifier): void;
+  setDcsHandlerFallback(handler: DcsFallbackHandlerType): void;
+  addDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable;
+
+  setOscHandler(ident: number, handler: IOscHandler): void;
+  clearOscHandler(ident: number): void;
+  setOscHandlerFallback(handler: OscFallbackHandlerType): void;
+  addOscHandler(ident: number, handler: IOscHandler): IDisposable;
+
+  setErrorHandler(handler: (state: IParsingState) => IParsingState): void;
+  clearErrorHandler(): void;
+}
+
+/**
+ * Subparser interfaces.
+ * The subparsers are instantiated in `EscapeSequenceParser` and
+ * called during `EscapeSequenceParser.parse`.
+ */
+export interface ISubParser<T, U> extends IDisposable {
+  reset(): void;
+  addHandler(ident: number, handler: T): IDisposable;
+  setHandler(ident: number, handler: T): void;
+  clearHandler(ident: number): void;
+  setHandlerFallback(handler: U): void;
+  put(data: Uint32Array, start: number, end: number): void;
+}
+
+export interface IOscParser extends ISubParser<IOscHandler, OscFallbackHandlerType> {
+  start(): void;
+  end(success: boolean): void;
+}
+
+export interface IDcsParser extends ISubParser<IDcsHandler, DcsFallbackHandlerType> {
+  hook(ident: number, params: IParams): void;
+  unhook(success: boolean): void;
+}
+
+/**
+ * Interface to denote a specific ESC, CSI or DCS handler slot.
+ * The values are used to create an integer respresentation during handler
+ * regristation before passed to the subparsers as `ident`.
+ * The integer translation is made to allow a faster handler access
+ * in `EscapeSequenceParser.parse`.
+ */
+export interface IFunctionIdentifier {
+  prefix?: string;
+  intermediates?: string;
+  final: string;
+}
+
+export interface IHandlerCollection<T> {
+  [key: string]: T[];
+}
diff --git a/node_modules/xterm/src/common/services/BufferService.ts b/node_modules/xterm/src/common/services/BufferService.ts
new file mode 100644 (file)
index 0000000..c7b6afc
--- /dev/null
@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferService, IOptionsService } from 'common/services/Services';
+import { BufferSet } from 'common/buffer/BufferSet';
+import { IBufferSet, IBuffer } from 'common/buffer/Types';
+
+export const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars
+export const MINIMUM_ROWS = 1;
+
+export class BufferService implements IBufferService {
+  serviceBrand: any;
+
+  public cols: number;
+  public rows: number;
+  public buffers: IBufferSet;
+
+  public get buffer(): IBuffer { return this.buffers.active; }
+
+  constructor(
+    @IOptionsService private _optionsService: IOptionsService
+  ) {
+    this.cols = Math.max(_optionsService.options.cols, MINIMUM_COLS);
+    this.rows = Math.max(_optionsService.options.rows, MINIMUM_ROWS);
+    this.buffers = new BufferSet(_optionsService, this);
+  }
+
+  public resize(cols: number, rows: number): void {
+    this.cols = cols;
+    this.rows = rows;
+  }
+
+  public reset(): void {
+    this.buffers = new BufferSet(this._optionsService, this);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/CoreMouseService.ts b/node_modules/xterm/src/common/services/CoreMouseService.ts
new file mode 100644 (file)
index 0000000..500655b
--- /dev/null
@@ -0,0 +1,296 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+import { IBufferService, ICoreService, ICoreMouseService } from 'common/services/Services';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';
+
+/**
+ * Supported default protocols.
+ */
+const DEFAULT_PROTOCOLS: {[key: string]: ICoreMouseProtocol} = {
+  /**
+   * NONE
+   * Events: none
+   * Modifiers: none
+   */
+  NONE: {
+    events: CoreMouseEventType.NONE,
+    restrict: () => false
+  },
+  /**
+   * X10
+   * Events: mousedown
+   * Modifiers: none
+   */
+  X10: {
+    events: CoreMouseEventType.DOWN,
+    restrict: (e: ICoreMouseEvent) => {
+      // no wheel, no move, no up
+      if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) {
+        return false;
+      }
+      // no modifiers
+      e.ctrl = false;
+      e.alt = false;
+      e.shift = false;
+      return true;
+    }
+  },
+  /**
+   * VT200
+   * Events: mousedown / mouseup / wheel
+   * Modifiers: all
+   */
+  VT200: {
+    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL,
+    restrict: (e: ICoreMouseEvent) => {
+      // no move
+      if (e.action === CoreMouseAction.MOVE) {
+        return false;
+      }
+      return true;
+    }
+  },
+  /**
+   * DRAG
+   * Events: mousedown / mouseup / wheel / mousedrag
+   * Modifiers: all
+   */
+  DRAG: {
+    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG,
+    restrict: (e: ICoreMouseEvent) => {
+      // no move without button
+      if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) {
+        return false;
+      }
+      return true;
+    }
+  },
+  /**
+   * ANY
+   * Events: all mouse related events
+   * Modifiers: all
+   */
+  ANY: {
+    events:
+      CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL
+      | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE,
+    restrict: (e: ICoreMouseEvent) => true
+  }
+};
+
+const enum Modifiers {
+  SHIFT = 4,
+  ALT = 8,
+  CTRL = 16
+}
+
+// helper for default encoders to generate the event code.
+function eventCode(e: ICoreMouseEvent, isSGR: boolean): number {
+  let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0);
+  if (e.button === CoreMouseButton.WHEEL) {
+    code |= 64;
+    code |= e.action;
+  } else {
+    code |= e.button & 3;
+    if (e.button & 4) {
+      code |= 64;
+    }
+    if (e.button & 8) {
+      code |= 128;
+    }
+    if (e.action === CoreMouseAction.MOVE) {
+      code |= CoreMouseAction.MOVE;
+    } else if (e.action === CoreMouseAction.UP && !isSGR) {
+      // special case - only SGR can report button on release
+      // all others have to go with NONE
+      code |= CoreMouseButton.NONE;
+    }
+  }
+  return code;
+}
+
+const S = String.fromCharCode;
+
+/**
+ * Supported default encodings.
+ */
+const DEFAULT_ENCODINGS: {[key: string]: CoreMouseEncoding} = {
+  /**
+   * DEFAULT - CSI M Pb Px Py
+   * Single byte encoding for coords and event code.
+   * Can encode values up to 223. The Encoding of higher
+   * values is not UTF-8 compatible (and currently limited
+   * to 95 in xterm.js).
+   */
+  DEFAULT: (e: ICoreMouseEvent) => {
+    let params = [eventCode(e, false) + 32, e.col + 32, e.row + 32];
+    // FIXME: we are currently limited to ASCII range
+    params = params.map(v => (v > 127) ? 127 : v);
+    // FIXED: params = params.map(v => (v > 255) ? 0 : value);
+    return `\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`;
+  },
+  /**
+   * SGR - CSI < Pb ; Px ; Py M|m
+   * No encoding limitation.
+   * Can report button on release and works with a well formed sequence.
+   */
+  SGR: (e: ICoreMouseEvent) => {
+    const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';
+    return `\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`;
+  }
+};
+
+/**
+ * CoreMouseService
+ *
+ * Provides mouse tracking reports with different protocols and encodings.
+ *  - protocols: NONE (default), X10, VT200, DRAG, ANY
+ *  - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507)
+ *
+ * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`.
+ * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`.
+ * Switching a protocol will send a notification event `onProtocolChange`
+ * with a list of needed events to track.
+ *
+ * The service handles the mouse tracking state and decides whether to send
+ * a tracking report to the backend based on protocol and encoding limitations.
+ * To send a mouse event call `triggerMouseEvent`.
+ */
+export class CoreMouseService implements ICoreMouseService {
+  private _protocols: {[name: string]: ICoreMouseProtocol} = {};
+  private _encodings: {[name: string]: CoreMouseEncoding} = {};
+  private _activeProtocol: string = '';
+  private _activeEncoding: string = '';
+  private _onProtocolChange = new EventEmitter<CoreMouseEventType>();
+  private _lastEvent: ICoreMouseEvent | null = null;
+
+  constructor(
+    @IBufferService private readonly _bufferService: IBufferService,
+    @ICoreService private readonly _coreService: ICoreService
+  ) {
+    // register default protocols and encodings
+    Object.keys(DEFAULT_PROTOCOLS).forEach(name => this.addProtocol(name, DEFAULT_PROTOCOLS[name]));
+    Object.keys(DEFAULT_ENCODINGS).forEach(name => this.addEncoding(name, DEFAULT_ENCODINGS[name]));
+    // call reset to set defaults
+    this.reset();
+  }
+
+  public addProtocol(name: string, protocol: ICoreMouseProtocol): void {
+    this._protocols[name] = protocol;
+  }
+
+  public addEncoding(name: string, encoding: CoreMouseEncoding): void {
+    this._encodings[name] = encoding;
+  }
+
+  public get activeProtocol(): string {
+    return this._activeProtocol;
+  }
+
+  public set activeProtocol(name: string) {
+    if (!this._protocols[name]) {
+      throw new Error(`unknown protocol "${name}"`);
+    }
+    this._activeProtocol = name;
+    this._onProtocolChange.fire(this._protocols[name].events);
+  }
+
+  public get activeEncoding(): string {
+    return this._activeEncoding;
+  }
+
+  public set activeEncoding(name: string) {
+    if (!this._encodings[name]) {
+      throw new Error(`unknown encoding "${name}"`);
+    }
+    this._activeEncoding = name;
+  }
+
+  public reset(): void {
+    this.activeProtocol = 'NONE';
+    this.activeEncoding = 'DEFAULT';
+    this._lastEvent = null;
+  }
+
+  /**
+   * Event to announce changes in mouse tracking.
+   */
+  public get onProtocolChange(): IEvent<CoreMouseEventType> {
+    return this._onProtocolChange.event;
+  }
+
+  /**
+   * Triggers a mouse event to be sent.
+   *
+   * Returns true if the event passed all protocol restrictions and a report
+   * was sent, otherwise false. The return value may be used to decide whether
+   * the default event action in the bowser component should be omitted.
+   *
+   * Note: The method will change values of the given event object
+   * to fullfill protocol and encoding restrictions.
+   */
+  public triggerMouseEvent(e: ICoreMouseEvent): boolean {
+    // range check for col/row
+    if (e.col < 0 || e.col >= this._bufferService.cols
+        || e.row < 0 || e.row >= this._bufferService.rows) {
+      return false;
+    }
+
+    // filter nonsense combinations of button + action
+    if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) {
+      return false;
+    }
+    if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) {
+      return false;
+    }
+    if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) {
+      return false;
+    }
+
+    // report 1-based coords
+    e.col++;
+    e.row++;
+
+    // debounce move at grid level
+    if (e.action === CoreMouseAction.MOVE && this._lastEvent && this._compareEvents(this._lastEvent, e)) {
+      return false;
+    }
+
+    // apply protocol restrictions
+    if (!this._protocols[this._activeProtocol].restrict(e)) {
+      return false;
+    }
+
+    // encode report and send
+    const report = this._encodings[this._activeEncoding](e);
+    this._coreService.triggerDataEvent(report, true);
+
+    this._lastEvent = e;
+
+    return true;
+  }
+
+  public explainEvents(events: CoreMouseEventType): {[event: string]: boolean} {
+    return {
+      DOWN: !!(events & CoreMouseEventType.DOWN),
+      UP: !!(events & CoreMouseEventType.UP),
+      DRAG: !!(events & CoreMouseEventType.DRAG),
+      MOVE: !!(events & CoreMouseEventType.MOVE),
+      WHEEL: !!(events & CoreMouseEventType.WHEEL)
+    };
+  }
+
+  private _compareEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent): boolean {
+    if (e1.col !== e2.col) return false;
+    if (e1.row !== e2.row) return false;
+    if (e1.button !== e2.button) return false;
+    if (e1.action !== e2.action) return false;
+    if (e1.ctrl !== e2.ctrl) return false;
+    if (e1.alt !== e2.alt) return false;
+    if (e1.shift !== e2.shift) return false;
+    return true;
+  }
+}
diff --git a/node_modules/xterm/src/common/services/CoreService.ts b/node_modules/xterm/src/common/services/CoreService.ts
new file mode 100644 (file)
index 0000000..0e0ba60
--- /dev/null
@@ -0,0 +1,60 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICoreService, ILogService, IOptionsService, IBufferService } from 'common/services/Services';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { IDecPrivateModes } from 'common/Types';
+import { clone } from 'common/Clone';
+
+const DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({
+  applicationCursorKeys: false
+});
+
+export class CoreService implements ICoreService {
+  serviceBrand: any;
+
+  public decPrivateModes: IDecPrivateModes;
+
+  private _onData = new EventEmitter<string>();
+  public get onData(): IEvent<string> { return this._onData.event; }
+  private _onUserInput = new EventEmitter<void>();
+  public get onUserInput(): IEvent<void> { return this._onUserInput.event; }
+
+  constructor(
+    // TODO: Move this into a service
+    private readonly _scrollToBottom: () => void,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @ILogService private readonly _logService: ILogService,
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);
+  }
+
+  public reset(): void {
+    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);
+  }
+
+  public triggerDataEvent(data: string, wasUserInput: boolean = false): void {
+    // Prevents all events to pty process if stdin is disabled
+    if (this._optionsService.options.disableStdin) {
+      return;
+    }
+
+    // Input is being sent to the terminal, the terminal should focus the prompt.
+    const buffer = this._bufferService.buffer;
+    if (buffer.ybase !== buffer.ydisp) {
+      this._scrollToBottom();
+    }
+
+    // Fire onUserInput so listeners can react as well (eg. clear selection)
+    if (wasUserInput) {
+      this._onUserInput.fire();
+    }
+
+    // Fire onData API
+    this._logService.debug(`sending data "${data}"`, () => data.split('').map(e => e.charCodeAt(0)));
+    this._onData.fire(data);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/DirtyRowService.ts b/node_modules/xterm/src/common/services/DirtyRowService.ts
new file mode 100644 (file)
index 0000000..0f2f14f
--- /dev/null
@@ -0,0 +1,53 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferService, IDirtyRowService } from 'common/services/Services';
+
+export class DirtyRowService implements IDirtyRowService {
+  serviceBrand: any;
+
+  private _start!: number;
+  private _end!: number;
+
+  public get start(): number { return this._start; }
+  public get end(): number { return this._end; }
+
+  constructor(
+    @IBufferService private readonly _bufferService: IBufferService
+  ) {
+    this.clearRange();
+  }
+
+  public clearRange(): void {
+    this._start = this._bufferService.buffer.y;
+    this._end = this._bufferService.buffer.y;
+  }
+
+  public markDirty(y: number): void {
+    if (y < this._start) {
+      this._start = y;
+    } else if (y > this._end) {
+      this._end = y;
+    }
+  }
+
+  public markRangeDirty(y1: number, y2: number): void {
+    if (y1 > y2) {
+      const temp = y1;
+      y1 = y2;
+      y2 = temp;
+    }
+    if (y1 < this._start) {
+      this._start = y1;
+    }
+    if (y2 > this._end) {
+      this._end = y2;
+    }
+  }
+
+  public markAllDirty(): void {
+    this.markRangeDirty(0, this._bufferService.rows - 1);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/InstantiationService.ts b/node_modules/xterm/src/common/services/InstantiationService.ts
new file mode 100644 (file)
index 0000000..abce8ac
--- /dev/null
@@ -0,0 +1,77 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ *
+ * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).
+ */
+/*---------------------------------------------------------------------------------------------
+ *  Copyright (c) Microsoft Corporation. All rights reserved.
+ *  Licensed under the MIT License. See License.txt in the project root for license information.
+ *--------------------------------------------------------------------------------------------*/
+
+import { IInstantiationService, IServiceIdentifier } from 'common/services/Services';
+import { getServiceDependencies } from 'common/services/ServiceRegistry';
+
+export class ServiceCollection {
+
+  private _entries = new Map<IServiceIdentifier<any>, any>();
+
+  constructor(...entries: [IServiceIdentifier<any>, any][]) {
+    for (const [id, service] of entries) {
+      this.set(id, service);
+    }
+  }
+
+  set<T>(id: IServiceIdentifier<T>, instance: T): T {
+    const result = this._entries.get(id);
+    this._entries.set(id, instance);
+    return result;
+  }
+
+  forEach(callback: (id: IServiceIdentifier<any>, instance: any) => any): void {
+    this._entries.forEach((value, key) => callback(key, value));
+  }
+
+  has(id: IServiceIdentifier<any>): boolean {
+    return this._entries.has(id);
+  }
+
+  get<T>(id: IServiceIdentifier<T>): T {
+    return this._entries.get(id);
+  }
+}
+
+export class InstantiationService implements IInstantiationService {
+  private readonly _services: ServiceCollection = new ServiceCollection();
+
+  constructor() {
+    this._services.set(IInstantiationService, this);
+  }
+
+  public setService<T>(id: IServiceIdentifier<T>, instance: T): void {
+    this._services.set(id, instance);
+  }
+
+  public createInstance<T>(ctor: any, ...args: any[]): any {
+    const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
+
+    const serviceArgs: any[] = [];
+    for (const dependency of serviceDependencies) {
+      const service = this._services.get(dependency.id);
+      if (!service) {
+        throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`);
+      }
+      serviceArgs.push(service);
+    }
+
+    const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
+
+    // check for argument mismatches, adjust static args if needed
+    if (args.length !== firstServiceArgPos) {
+      throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
+    }
+
+    // now create the instance
+    return <T>new ctor(...[...args, ...serviceArgs]);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/LogService.ts b/node_modules/xterm/src/common/services/LogService.ts
new file mode 100644 (file)
index 0000000..4f48d8f
--- /dev/null
@@ -0,0 +1,97 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ILogService, IOptionsService } from 'common/services/Services';
+
+type LogType = (message?: any, ...optionalParams: any[]) => void;
+
+interface IConsole {
+  log: LogType;
+  error: LogType;
+  info: LogType;
+  trace: LogType;
+  warn: LogType;
+}
+
+// console is available on both node.js and browser contexts but the common
+// module doesn't depend on them so we need to explicitly declare it.
+declare const console: IConsole;
+
+
+export enum LogLevel {
+  DEBUG = 0,
+  INFO = 1,
+  WARN = 2,
+  ERROR = 3,
+  OFF = 4
+}
+
+const optionsKeyToLogLevel: { [key: string]: LogLevel } = {
+  debug: LogLevel.DEBUG,
+  info: LogLevel.INFO,
+  warn: LogLevel.WARN,
+  error: LogLevel.ERROR,
+  off: LogLevel.OFF
+};
+
+const LOG_PREFIX = 'xterm.js: ';
+
+export class LogService implements ILogService {
+  serviceBrand: any;
+
+  private _logLevel!: LogLevel;
+
+  constructor(
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    this._updateLogLevel();
+    this._optionsService.onOptionChange(key => {
+      if (key === 'logLevel') {
+        this._updateLogLevel();
+      }
+    });
+  }
+
+  private _updateLogLevel(): void {
+    this._logLevel = optionsKeyToLogLevel[this._optionsService.options.logLevel];
+  }
+
+  private _evalLazyOptionalParams(optionalParams: any[]): void {
+    for (let i = 0; i < optionalParams.length; i++) {
+      if (typeof optionalParams[i] === 'function') {
+        optionalParams[i] = optionalParams[i]();
+      }
+    }
+  }
+
+  private _log(type: LogType, message: string, optionalParams: any[]): void {
+    this._evalLazyOptionalParams(optionalParams);
+    type.call(console, LOG_PREFIX + message, ...optionalParams);
+  }
+
+  debug(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.DEBUG) {
+      this._log(console.log, message, optionalParams);
+    }
+  }
+
+  info(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.INFO) {
+      this._log(console.info, message, optionalParams);
+    }
+  }
+
+  warn(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.WARN) {
+      this._log(console.warn, message, optionalParams);
+    }
+  }
+
+  error(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.ERROR) {
+      this._log(console.error, message, optionalParams);
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/services/OptionsService.ts b/node_modules/xterm/src/common/services/OptionsService.ts
new file mode 100644 (file)
index 0000000..d9ea60d
--- /dev/null
@@ -0,0 +1,141 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOptionsService, ITerminalOptions, IPartialTerminalOptions } from 'common/services/Services';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { isMac } from 'common/Platform';
+import { clone } from 'common/Clone';
+
+// Source: https://freesound.org/people/altemark/sounds/45759/
+// This sound is released under the Creative Commons Attribution 3.0 Unported
+// (CC BY 3.0) license. It was created by 'altemark'. No modifications have been
+// made, apart from the conversion to base64.
+export const DEFAULT_BELL_SOUND = 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';
+
+// TODO: Freeze?
+export const DEFAULT_OPTIONS: ITerminalOptions = Object.freeze({
+  cols: 80,
+  rows: 24,
+  cursorBlink: false,
+  cursorStyle: 'block',
+  bellSound:  DEFAULT_BELL_SOUND,
+  bellStyle: 'none',
+  drawBoldTextInBrightColors: true,
+  fastScrollModifier: 'alt',
+  fastScrollSensitivity: 5,
+  fontFamily: 'courier-new, courier, monospace',
+  fontSize: 15,
+  fontWeight: 'normal',
+  fontWeightBold: 'bold',
+  lineHeight: 1.0,
+  letterSpacing: 0,
+  logLevel: 'info',
+  scrollback: 1000,
+  scrollSensitivity: 1,
+  screenReaderMode: false,
+  macOptionIsMeta: false,
+  macOptionClickForcesSelection: false,
+  disableStdin: false,
+  allowTransparency: false,
+  tabStopWidth: 8,
+  theme: {},
+  rightClickSelectsWord: isMac,
+  rendererType: 'canvas',
+  windowsMode: false,
+
+  convertEol: false,
+  termName: 'xterm',
+  screenKeys: false,
+  cancelEvents: false,
+  useFlowControl: false,
+  wordSeparator: ' ()[]{}\',:;"'
+});
+
+/**
+ * The set of options that only have an effect when set in the Terminal constructor.
+ */
+const CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows'];
+
+export class OptionsService implements IOptionsService {
+  serviceBrand: any;
+
+  public options: ITerminalOptions;
+
+  private _onOptionChange = new EventEmitter<string>();
+  public get onOptionChange(): IEvent<string> { return this._onOptionChange.event; }
+
+  constructor(options: IPartialTerminalOptions) {
+    this.options = clone(DEFAULT_OPTIONS);
+    Object.keys(options).forEach(k => {
+      if (k in this.options) {
+        const newValue = options[k as keyof IPartialTerminalOptions] as any;
+        this.options[k] = newValue;
+      }
+    });
+  }
+
+  public setOption(key: string, value: any): void {
+    if (!(key in DEFAULT_OPTIONS)) {
+      throw new Error('No option with key "' + key + '"');
+    }
+    if (CONSTRUCTOR_ONLY_OPTIONS.indexOf(key) !== -1) {
+      throw new Error(`Option "${key}" can only be set in the constructor`);
+    }
+    if (this.options[key] === value) {
+      return;
+    }
+
+    value = this._sanitizeAndValidateOption(key, value);
+
+    // Don't fire an option change event if they didn't change
+    if (this.options[key] === value) {
+      return;
+    }
+
+    this.options[key] = value;
+    this._onOptionChange.fire(key);
+  }
+
+  private _sanitizeAndValidateOption(key: string, value: any): any {
+    switch (key) {
+      case 'bellStyle':
+      case 'cursorStyle':
+      case 'fontWeight':
+      case 'fontWeightBold':
+      case 'rendererType':
+      case 'wordSeparator':
+        if (!value) {
+          value = DEFAULT_OPTIONS[key];
+        }
+        break;
+      case 'lineHeight':
+      case 'tabStopWidth':
+        if (value < 1) {
+          throw new Error(`${key} cannot be less than 1, value: ${value}`);
+        }
+        break;
+      case 'scrollback':
+        value = Math.min(value, 4294967295);
+        if (value < 0) {
+          throw new Error(`${key} cannot be less than 0, value: ${value}`);
+        }
+        break;
+      case 'fastScrollSensitivity':
+      case 'scrollSensitivity':
+        if (value <= 0) {
+          throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`);
+        }
+        break;
+    }
+    return value;
+  }
+
+  public getOption(key: string): any {
+    if (!(key in DEFAULT_OPTIONS)) {
+      throw new Error(`No option with key "${key}"`);
+    }
+    return this.options[key];
+  }
+}
diff --git a/node_modules/xterm/src/common/services/ServiceRegistry.ts b/node_modules/xterm/src/common/services/ServiceRegistry.ts
new file mode 100644 (file)
index 0000000..450af49
--- /dev/null
@@ -0,0 +1,49 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ *
+ * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).
+ */
+/*---------------------------------------------------------------------------------------------
+ *  Copyright (c) Microsoft Corporation. All rights reserved.
+ *  Licensed under the MIT License. See License.txt in the project root for license information.
+ *--------------------------------------------------------------------------------------------*/
+
+import { IServiceIdentifier } from 'common/services/Services';
+
+const DI_TARGET = 'di$target';
+const DI_DEPENDENCIES = 'di$dependencies';
+
+export const serviceRegistry: Map<string, IServiceIdentifier<any>> = new Map();
+
+export function getServiceDependencies(ctor: any): { id: IServiceIdentifier<any>, index: number, optional: boolean }[] {
+  return ctor[DI_DEPENDENCIES] || [];
+}
+
+export function createDecorator<T>(id: string): IServiceIdentifier<T> {
+  if (serviceRegistry.has(id)) {
+    return serviceRegistry.get(id)!;
+  }
+
+  const decorator = <any>function (target: Function, key: string, index: number): any {
+    if (arguments.length !== 3) {
+      throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
+    }
+
+    storeServiceDependency(decorator, target, index);
+  };
+
+  decorator.toString = () => id;
+
+  serviceRegistry.set(id, decorator);
+  return decorator;
+}
+
+function storeServiceDependency(id: Function, target: Function, index: number): void {
+  if ((target as any)[DI_TARGET] === target) {
+    (target as any)[DI_DEPENDENCIES].push({ id, index });
+  } else {
+    (target as any)[DI_DEPENDENCIES] = [{ id, index }];
+    (target as any)[DI_TARGET] = target;
+  }
+}
diff --git a/node_modules/xterm/src/common/services/Services.ts b/node_modules/xterm/src/common/services/Services.ts
new file mode 100644 (file)
index 0000000..0872d3d
--- /dev/null
@@ -0,0 +1,267 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent } from 'common/EventEmitter';
+import { IBuffer, IBufferSet } from 'common/buffer/Types';
+import { IDecPrivateModes, ICoreMouseEvent, CoreMouseEncoding, ICoreMouseProtocol, CoreMouseEventType } from 'common/Types';
+import { createDecorator } from 'common/services/ServiceRegistry';
+
+export const IBufferService = createDecorator<IBufferService>('BufferService');
+export interface IBufferService {
+  serviceBrand: any;
+
+  readonly cols: number;
+  readonly rows: number;
+  readonly buffer: IBuffer;
+  readonly buffers: IBufferSet;
+
+  // TODO: Move resize event here
+
+  resize(cols: number, rows: number): void;
+  reset(): void;
+}
+
+export const ICoreMouseService = createDecorator<ICoreMouseService>('CoreMouseService');
+export interface ICoreMouseService {
+  activeProtocol: string;
+  activeEncoding: string;
+  addProtocol(name: string, protocol: ICoreMouseProtocol): void;
+  addEncoding(name: string, encoding: CoreMouseEncoding): void;
+  reset(): void;
+
+  /**
+   * Triggers a mouse event to be sent.
+   *
+   * Returns true if the event passed all protocol restrictions and a report
+   * was sent, otherwise false. The return value may be used to decide whether
+   * the default event action in the bowser component should be omitted.
+   *
+   * Note: The method will change values of the given event object
+   * to fullfill protocol and encoding restrictions.
+   */
+  triggerMouseEvent(event: ICoreMouseEvent): boolean;
+
+  /**
+   * Event to announce changes in mouse tracking.
+   */
+  onProtocolChange: IEvent<CoreMouseEventType>;
+
+  /**
+   * Human readable version of mouse events.
+   */
+  explainEvents(events: CoreMouseEventType): {[event: string]: boolean};
+}
+
+export const ICoreService = createDecorator<ICoreService>('CoreService');
+export interface ICoreService {
+  serviceBrand: any;
+
+  readonly decPrivateModes: IDecPrivateModes;
+
+  readonly onData: IEvent<string>;
+  readonly onUserInput: IEvent<void>;
+
+  reset(): void;
+
+  /**
+   * Triggers the onData event in the public API.
+   * @param data The data that is being emitted.
+   * @param wasFromUser Whether the data originated from the user (as opposed to
+   * resulting from parsing incoming data). When true this will also:
+   * - Scroll to the bottom of the buffer.s
+   * - Fire the `onUserInput` event (so selection can be cleared).
+    */
+  triggerDataEvent(data: string, wasUserInput?: boolean): void;
+}
+
+export const IDirtyRowService = createDecorator<IDirtyRowService>('DirtyRowService');
+export interface IDirtyRowService {
+  serviceBrand: any;
+
+  readonly start: number;
+  readonly end: number;
+
+  clearRange(): void;
+  markDirty(y: number): void;
+  markRangeDirty(y1: number, y2: number): void;
+  markAllDirty(): void;
+}
+
+export interface IServiceIdentifier<T> {
+  (...args: any[]): void;
+  type: T;
+}
+
+export interface IConstructorSignature0<T> {
+  new(...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature1<A1, T> {
+  new(first: A1, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature2<A1, A2, T> {
+  new(first: A1, second: A2, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature3<A1, A2, A3, T> {
+  new(first: A1, second: A2, third: A3, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature4<A1, A2, A3, A4, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature5<A1, A2, A3, A4, A5, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: { serviceBrand: any; }[]): T;
+}
+
+export const IInstantiationService = createDecorator<IInstantiationService>('InstantiationService');
+export interface IInstantiationService {
+  setService<T>(id: IServiceIdentifier<T>, instance: T): void;
+
+  createInstance<T>(ctor: IConstructorSignature0<T>): T;
+  createInstance<A1, T>(ctor: IConstructorSignature1<A1, T>, first: A1): T;
+  createInstance<A1, A2, T>(ctor: IConstructorSignature2<A1, A2, T>, first: A1, second: A2): T;
+  createInstance<A1, A2, A3, T>(ctor: IConstructorSignature3<A1, A2, A3, T>, first: A1, second: A2, third: A3): T;
+  createInstance<A1, A2, A3, A4, T>(ctor: IConstructorSignature4<A1, A2, A3, A4, T>, first: A1, second: A2, third: A3, fourth: A4): T;
+  createInstance<A1, A2, A3, A4, A5, T>(ctor: IConstructorSignature5<A1, A2, A3, A4, A5, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T;
+  createInstance<A1, A2, A3, A4, A5, A6, T>(ctor: IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T;
+  createInstance<A1, A2, A3, A4, A5, A6, A7, T>(ctor: IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T;
+  createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T;
+}
+
+export const ILogService = createDecorator<ILogService>('LogService');
+export interface ILogService {
+  serviceBrand: any;
+
+  debug(message: any, ...optionalParams: any[]): void;
+  info(message: any, ...optionalParams: any[]): void;
+  warn(message: any, ...optionalParams: any[]): void;
+  error(message: any, ...optionalParams: any[]): void;
+}
+
+export const IOptionsService = createDecorator<IOptionsService>('OptionsService');
+export interface IOptionsService {
+  serviceBrand: any;
+
+  readonly options: ITerminalOptions;
+
+  readonly onOptionChange: IEvent<string>;
+
+  setOption<T>(key: string, value: T): void;
+  getOption<T>(key: string): T | undefined;
+}
+
+export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
+export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';
+export type RendererType = 'dom' | 'canvas';
+
+export interface IPartialTerminalOptions {
+  allowTransparency?: boolean;
+  bellSound?: string;
+  bellStyle?: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;
+  cols?: number;
+  cursorBlink?: boolean;
+  cursorStyle?: 'block' | 'underline' | 'bar';
+  disableStdin?: boolean;
+  drawBoldTextInBrightColors?: boolean;
+  fastScrollModifier?: 'alt' | 'ctrl' | 'shift';
+  fastScrollSensitivity?: number;
+  fontSize?: number;
+  fontFamily?: string;
+  fontWeight?: FontWeight;
+  fontWeightBold?: FontWeight;
+  letterSpacing?: number;
+  lineHeight?: number;
+  logLevel?: LogLevel;
+  macOptionIsMeta?: boolean;
+  macOptionClickForcesSelection?: boolean;
+  rendererType?: RendererType;
+  rightClickSelectsWord?: boolean;
+  rows?: number;
+  screenReaderMode?: boolean;
+  scrollback?: number;
+  scrollSensitivity?: number;
+  tabStopWidth?: number;
+  theme?: ITheme;
+  windowsMode?: boolean;
+  wordSeparator?: string;
+}
+
+export interface ITerminalOptions {
+  allowTransparency: boolean;
+  bellSound: string;
+  bellStyle: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;
+  cols: number;
+  cursorBlink: boolean;
+  cursorStyle: 'block' | 'underline' | 'bar';
+  disableStdin: boolean;
+  drawBoldTextInBrightColors: boolean;
+  fastScrollModifier: 'alt' | 'ctrl' | 'shift' | undefined;
+  fastScrollSensitivity: number;
+  fontSize: number;
+  fontFamily: string;
+  fontWeight: FontWeight;
+  fontWeightBold: FontWeight;
+  letterSpacing: number;
+  lineHeight: number;
+  logLevel: LogLevel;
+  macOptionIsMeta: boolean;
+  macOptionClickForcesSelection: boolean;
+  rendererType: RendererType;
+  rightClickSelectsWord: boolean;
+  rows: number;
+  screenReaderMode: boolean;
+  scrollback: number;
+  scrollSensitivity: number;
+  tabStopWidth: number;
+  theme: ITheme;
+  windowsMode: boolean;
+  wordSeparator: string;
+
+  [key: string]: any;
+  cancelEvents: boolean;
+  convertEol: boolean;
+  screenKeys: boolean;
+  termName: string;
+  useFlowControl: boolean;
+}
+
+export interface ITheme {
+  foreground?: string;
+  background?: string;
+  cursor?: string;
+  cursorAccent?: string;
+  selection?: string;
+  black?: string;
+  red?: string;
+  green?: string;
+  yellow?: string;
+  blue?: string;
+  magenta?: string;
+  cyan?: string;
+  white?: string;
+  brightBlack?: string;
+  brightRed?: string;
+  brightGreen?: string;
+  brightYellow?: string;
+  brightBlue?: string;
+  brightMagenta?: string;
+  brightCyan?: string;
+  brightWhite?: string;
+}
diff --git a/node_modules/xterm/src/common/tsconfig.json b/node_modules/xterm/src/common/tsconfig.json
new file mode 100644 (file)
index 0000000..59050a0
--- /dev/null
@@ -0,0 +1,14 @@
+{
+  "extends": "../tsconfig-library-base",
+  "compilerOptions": {
+    "lib": [
+      "es2015"
+    ],
+    "outDir": "../../out",
+    "types": [
+      "../../node_modules/@types/mocha"
+    ],
+    "baseUrl": ".."
+  },
+  "include": [ "./**/*" ]
+}
diff --git a/node_modules/xterm/src/public/AddonManager.ts b/node_modules/xterm/src/public/AddonManager.ts
new file mode 100644 (file)
index 0000000..0261fd6
--- /dev/null
@@ -0,0 +1,56 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ITerminalAddon, IDisposable, Terminal } from 'xterm';
+
+export interface ILoadedAddon {
+  instance: ITerminalAddon;
+  dispose: () => void;
+  isDisposed: boolean;
+}
+
+export class AddonManager implements IDisposable {
+  protected _addons: ILoadedAddon[] = [];
+
+  constructor() {
+  }
+
+  public dispose(): void {
+    for (let i = this._addons.length - 1; i >= 0; i--) {
+      this._addons[i].instance.dispose();
+    }
+  }
+
+  public loadAddon(terminal: Terminal, instance: ITerminalAddon): void {
+    const loadedAddon: ILoadedAddon = {
+      instance,
+      dispose: instance.dispose,
+      isDisposed: false
+    };
+    this._addons.push(loadedAddon);
+    instance.dispose = () => this._wrappedAddonDispose(loadedAddon);
+    instance.activate(<any>terminal);
+  }
+
+  private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void {
+    if (loadedAddon.isDisposed) {
+      // Do nothing if already disposed
+      return;
+    }
+    let index = -1;
+    for (let i = 0; i < this._addons.length; i++) {
+      if (this._addons[i] === loadedAddon) {
+        index = i;
+        break;
+      }
+    }
+    if (index === -1) {
+      throw new Error('Could not dispose an addon that has not been loaded');
+    }
+    loadedAddon.isDisposed = true;
+    loadedAddon.dispose.apply(loadedAddon.instance);
+    this._addons.splice(index, 1);
+  }
+}
diff --git a/node_modules/xterm/src/public/Terminal.ts b/node_modules/xterm/src/public/Terminal.ts
new file mode 100644 (file)
index 0000000..c167bed
--- /dev/null
@@ -0,0 +1,241 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Terminal as ITerminalApi, ITerminalOptions, IMarker, IDisposable, ILinkMatcherOptions, ITheme, ILocalizableStrings, ITerminalAddon, ISelectionPosition, IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi, IParser, IFunctionIdentifier } from 'xterm';
+import { ITerminal } from '../Types';
+import { IBufferLine } from 'common/Types';
+import { IBuffer } from 'common/buffer/Types';
+import { Terminal as TerminalCore } from '../Terminal';
+import * as Strings from '../browser/LocalizableStrings';
+import { IEvent } from 'common/EventEmitter';
+import { AddonManager } from './AddonManager';
+import { IParams } from 'common/parser/Types';
+
+export class Terminal implements ITerminalApi {
+  private _core: ITerminal;
+  private _addonManager: AddonManager;
+  private _parser: IParser;
+
+  constructor(options?: ITerminalOptions) {
+    this._core = new TerminalCore(options);
+    this._addonManager = new AddonManager();
+  }
+
+  public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }
+  public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }
+  public get onSelectionChange(): IEvent<void> { return this._core.onSelectionChange; }
+  public get onData(): IEvent<string> { return this._core.onData; }
+  public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }
+  public get onScroll(): IEvent<number> { return this._core.onScroll; }
+  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }
+  public get onRender(): IEvent<{ start: number, end: number }> { return this._core.onRender; }
+  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._core.onResize; }
+
+  public get element(): HTMLElement | undefined { return this._core.element; }
+  public get parser(): IParser {
+    if (!this._parser) {
+      this._parser = new ParserApi(this._core);
+    }
+    return this._parser;
+  }
+  public get textarea(): HTMLTextAreaElement | undefined { return this._core.textarea; }
+  public get rows(): number { return this._core.rows; }
+  public get cols(): number { return this._core.cols; }
+  public get buffer(): IBufferApi { return new BufferApiView(this._core.buffer); }
+  public get markers(): ReadonlyArray<IMarker> { return this._core.markers; }
+  public blur(): void {
+    this._core.blur();
+  }
+  public focus(): void {
+    this._core.focus();
+  }
+  public resize(columns: number, rows: number): void {
+    this._verifyIntegers(columns, rows);
+    this._core.resize(columns, rows);
+  }
+  public open(parent: HTMLElement): void {
+    this._core.open(parent);
+  }
+  public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void {
+    this._core.attachCustomKeyEventHandler(customKeyEventHandler);
+  }
+  public registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number {
+    return this._core.registerLinkMatcher(regex, handler, options);
+  }
+  public deregisterLinkMatcher(matcherId: number): void {
+    this._core.deregisterLinkMatcher(matcherId);
+  }
+  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {
+    return this._core.registerCharacterJoiner(handler);
+  }
+  public deregisterCharacterJoiner(joinerId: number): void {
+    this._core.deregisterCharacterJoiner(joinerId);
+  }
+  public addMarker(cursorYOffset: number): IMarker {
+    this._verifyIntegers(cursorYOffset);
+    return this._core.addMarker(cursorYOffset);
+  }
+  public hasSelection(): boolean {
+    return this._core.hasSelection();
+  }
+  public select(column: number, row: number, length: number): void {
+    this._verifyIntegers(column, row, length);
+    this._core.select(column, row, length);
+  }
+  public getSelection(): string {
+    return this._core.getSelection();
+  }
+  public getSelectionPosition(): ISelectionPosition | undefined {
+    return this._core.getSelectionPosition();
+  }
+  public clearSelection(): void {
+    this._core.clearSelection();
+  }
+  public selectAll(): void {
+    this._core.selectAll();
+  }
+  public selectLines(start: number, end: number): void {
+    this._verifyIntegers(start, end);
+    this._core.selectLines(start, end);
+  }
+  public dispose(): void {
+    this._addonManager.dispose();
+    this._core.dispose();
+  }
+  public scrollLines(amount: number): void {
+    this._verifyIntegers(amount);
+    this._core.scrollLines(amount);
+  }
+  public scrollPages(pageCount: number): void {
+    this._verifyIntegers(pageCount);
+    this._core.scrollPages(pageCount);
+  }
+  public scrollToTop(): void {
+    this._core.scrollToTop();
+  }
+  public scrollToBottom(): void {
+    this._core.scrollToBottom();
+  }
+  public scrollToLine(line: number): void {
+    this._verifyIntegers(line);
+    this._core.scrollToLine(line);
+  }
+  public clear(): void {
+    this._core.clear();
+  }
+  public write(data: string | Uint8Array, callback?: () => void): void {
+    this._core.write(data, callback);
+  }
+  public writeUtf8(data: Uint8Array, callback?: () => void): void {
+    this._core.write(data, callback);
+  }
+  public writeln(data: string | Uint8Array, callback?: () => void): void {
+    this._core.write(data);
+    this._core.write('\r\n', callback);
+  }
+  public paste(data: string): void {
+    this._core.paste(data);
+  }
+  public getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'fontWeight' | 'fontWeightBold' | 'logLevel' | 'rendererType' | 'termName' | 'wordSeparator'): string;
+  public getOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell'): boolean;
+  public getOption(key: 'colors'): string[];
+  public getOption(key: 'cols' | 'fontSize' | 'letterSpacing' | 'lineHeight' | 'rows' | 'tabStopWidth' | 'scrollback'): number;
+  public getOption(key: 'handler'): (data: string) => void;
+  public getOption(key: string): any;
+  public getOption(key: any): any {
+    return this._core.optionsService.getOption(key);
+  }
+  public setOption(key: 'bellSound' | 'fontFamily' | 'termName' | 'wordSeparator', value: string): void;
+  public setOption(key: 'fontWeight' | 'fontWeightBold', value: 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'): void;
+  public setOption(key: 'logLevel', value: 'debug' | 'info' | 'warn' | 'error' | 'off'): void;
+  public setOption(key: 'bellStyle', value: 'none' | 'visual' | 'sound' | 'both'): void;
+  public setOption(key: 'cursorStyle', value: 'block' | 'underline' | 'bar'): void;
+  public setOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell', value: boolean): void;
+  public setOption(key: 'colors', value: string[]): void;
+  public setOption(key: 'fontSize' | 'letterSpacing' | 'lineHeight' | 'tabStopWidth' | 'scrollback', value: number): void;
+  public setOption(key: 'handler', value: (data: string) => void): void;
+  public setOption(key: 'theme', value: ITheme): void;
+  public setOption(key: 'cols' | 'rows', value: number): void;
+  public setOption(key: string, value: any): void;
+  public setOption(key: any, value: any): void {
+    this._core.optionsService.setOption(key, value);
+  }
+  public refresh(start: number, end: number): void {
+    this._verifyIntegers(start, end);
+    this._core.refresh(start, end);
+  }
+  public reset(): void {
+    this._core.reset();
+  }
+  public loadAddon(addon: ITerminalAddon): void {
+    return this._addonManager.loadAddon(this, addon);
+  }
+  public static get strings(): ILocalizableStrings {
+    return Strings;
+  }
+
+  private _verifyIntegers(...values: number[]): void {
+    values.forEach(value => {
+      if (value === Infinity || isNaN(value) || value % 1 !== 0) {
+        throw new Error('This API only accepts integers');
+      }
+    });
+  }
+}
+
+class BufferApiView implements IBufferApi {
+  constructor(private _buffer: IBuffer) {}
+
+  public get cursorY(): number { return this._buffer.y; }
+  public get cursorX(): number { return this._buffer.x; }
+  public get viewportY(): number { return this._buffer.ydisp; }
+  public get baseY(): number { return this._buffer.ybase; }
+  public get length(): number { return this._buffer.lines.length; }
+  public getLine(y: number): IBufferLineApi | undefined {
+    const line = this._buffer.lines.get(y);
+    if (!line) {
+      return undefined;
+    }
+    return new BufferLineApiView(line);
+  }
+}
+
+class BufferLineApiView implements IBufferLineApi {
+  constructor(private _line: IBufferLine) {}
+
+  public get isWrapped(): boolean { return this._line.isWrapped; }
+  public getCell(x: number): IBufferCellApi | undefined {
+    if (x < 0 || x >= this._line.length) {
+      return undefined;
+    }
+    return new BufferCellApiView(this._line, x);
+  }
+  public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string {
+    return this._line.translateToString(trimRight, startColumn, endColumn);
+  }
+}
+
+class BufferCellApiView implements IBufferCellApi {
+  constructor(private _line: IBufferLine, private _x: number) {}
+  public get char(): string { return this._line.getString(this._x); }
+  public get width(): number { return this._line.getWidth(this._x); }
+}
+
+class ParserApi implements IParser {
+  constructor(private _core: ITerminal) {}
+
+  public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable {
+    return this._core.addCsiHandler(id, (params: IParams) => callback(params.toArray()));
+  }
+  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable {
+    return this._core.addDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray()));
+  }
+  public addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable {
+    return this._core.addEscHandler(id, handler);
+  }
+  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {
+    return this._core.addOscHandler(ident, callback);
+  }
+}
diff --git a/node_modules/xterm/src/renderer/CursorRenderLayer.ts b/node_modules/xterm/src/renderer/CursorRenderLayer.ts
new file mode 100644 (file)
index 0000000..1f2791f
--- /dev/null
@@ -0,0 +1,368 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions } from 'browser/renderer/Types';
+import { BaseRenderLayer } from '../browser/renderer/BaseRenderLayer';
+import { ITerminal } from '../Types';
+import { ICellData } from 'common/Types';
+import { CellData } from 'common/buffer/CellData';
+import { IColorSet } from 'browser/Types';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+interface ICursorState {
+  x: number;
+  y: number;
+  isFocused: boolean;
+  style: string;
+  width: number;
+}
+
+/**
+ * The time between cursor blinks.
+ */
+const BLINK_INTERVAL = 600;
+
+export class CursorRenderLayer extends BaseRenderLayer {
+  private _state: ICursorState;
+  private _cursorRenderers: {[key: string]: (x: number, y: number, cell: ICellData) => void};
+  private _cursorBlinkStateManager: CursorBlinkStateManager;
+  private _cell: ICellData = new CellData();
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    private _terminal: ITerminal,
+    rendererId: number,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'cursor', zIndex, true, colors, rendererId, bufferService, optionsService);
+    this._state = {
+      x: null,
+      y: null,
+      isFocused: null,
+      style: null,
+      width: null
+    };
+    this._cursorRenderers = {
+      'bar': this._renderBarCursor.bind(this),
+      'block': this._renderBlockCursor.bind(this),
+      'underline': this._renderUnderlineCursor.bind(this)
+    };
+    // TODO: Consider initial options? Maybe onOptionsChanged should be called at the end of open?
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._state = {
+      x: null,
+      y: null,
+      isFocused: null,
+      style: null,
+      width: null
+    };
+  }
+
+  public reset(): void {
+    this._clearCursor();
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.dispose();
+      this._cursorBlinkStateManager = null;
+      this.onOptionsChanged();
+    }
+  }
+
+  public onBlur(): void {
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.pause();
+    }
+    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);
+  }
+
+  public onFocus(): void {
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.resume();
+    } else {
+      this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);
+    }
+  }
+
+  public onOptionsChanged(): void {
+    if (this._optionsService.options.cursorBlink) {
+      if (!this._cursorBlinkStateManager) {
+        this._cursorBlinkStateManager = new CursorBlinkStateManager(this._terminal.isFocused, () => {
+          this._render(true);
+        });
+      }
+    } else {
+      if (this._cursorBlinkStateManager) {
+        this._cursorBlinkStateManager.dispose();
+        this._cursorBlinkStateManager = null;
+      }
+    }
+    // Request a refresh from the terminal as management of rendering is being
+    // moved back to the terminal
+    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);
+  }
+
+  public onCursorMove(): void {
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.restartBlinkAnimation();
+    }
+  }
+
+  public onGridChanged(startRow: number, endRow: number): void {
+    if (!this._cursorBlinkStateManager || this._cursorBlinkStateManager.isPaused) {
+      this._render(false);
+    } else {
+      this._cursorBlinkStateManager.restartBlinkAnimation();
+    }
+  }
+
+  private _render(triggeredByAnimationFrame: boolean): void {
+    // Don't draw the cursor if it's hidden
+    if (!this._terminal.cursorState || this._terminal.cursorHidden) {
+      this._clearCursor();
+      return;
+    }
+
+    const cursorY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;
+    const viewportRelativeCursorY = cursorY - this._bufferService.buffer.ydisp;
+
+    // Don't draw the cursor if it's off-screen
+    if (viewportRelativeCursorY < 0 || viewportRelativeCursorY >= this._bufferService.rows) {
+      this._clearCursor();
+      return;
+    }
+
+    this._bufferService.buffer.lines.get(cursorY).loadCell(this._bufferService.buffer.x, this._cell);
+    if (this._cell.content === undefined) {
+      return;
+    }
+
+    if (!this._terminal.isFocused) {
+      this._clearCursor();
+      this._ctx.save();
+      this._ctx.fillStyle = this._colors.cursor.css;
+      const cursorStyle = this._optionsService.options.cursorStyle;
+      if (cursorStyle && cursorStyle !== 'block') {
+        this._cursorRenderers[cursorStyle](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);
+      } else {
+        this._renderBlurCursor(this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);
+      }
+      this._ctx.restore();
+      this._state.x = this._bufferService.buffer.x;
+      this._state.y = viewportRelativeCursorY;
+      this._state.isFocused = false;
+      this._state.style = cursorStyle;
+      this._state.width = this._cell.getWidth();
+      return;
+    }
+
+    // Don't draw the cursor if it's blinking
+    if (this._cursorBlinkStateManager && !this._cursorBlinkStateManager.isCursorVisible) {
+      this._clearCursor();
+      return;
+    }
+
+    if (this._state) {
+      // The cursor is already in the correct spot, don't redraw
+      if (this._state.x === this._bufferService.buffer.x &&
+          this._state.y === viewportRelativeCursorY &&
+          this._state.isFocused === this._terminal.isFocused &&
+          this._state.style === this._optionsService.options.cursorStyle &&
+          this._state.width === this._cell.getWidth()) {
+        return;
+      }
+      this._clearCursor();
+    }
+
+    this._ctx.save();
+    this._cursorRenderers[this._optionsService.options.cursorStyle || 'block'](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);
+    this._ctx.restore();
+
+    this._state.x = this._bufferService.buffer.x;
+    this._state.y = viewportRelativeCursorY;
+    this._state.isFocused = false;
+    this._state.style = this._optionsService.options.cursorStyle;
+    this._state.width = this._cell.getWidth();
+  }
+
+  private _clearCursor(): void {
+    if (this._state) {
+      this._clearCells(this._state.x, this._state.y, this._state.width, 1);
+      this._state = {
+        x: null,
+        y: null,
+        isFocused: null,
+        style: null,
+        width: null
+      };
+    }
+  }
+
+  private _renderBarCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.fillStyle = this._colors.cursor.css;
+    this._fillLeftLineAtCell(x, y);
+    this._ctx.restore();
+  }
+
+  private _renderBlockCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.fillStyle = this._colors.cursor.css;
+    this._fillCells(x, y, cell.getWidth(), 1);
+    this._ctx.fillStyle = this._colors.cursorAccent.css;
+    this._fillCharTrueColor(cell, x, y);
+    this._ctx.restore();
+  }
+
+  private _renderUnderlineCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.fillStyle = this._colors.cursor.css;
+    this._fillBottomLineAtCells(x, y);
+    this._ctx.restore();
+  }
+
+  private _renderBlurCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.strokeStyle = this._colors.cursor.css;
+    this._strokeRectAtCell(x, y, cell.getWidth(), 1);
+    this._ctx.restore();
+  }
+}
+
+class CursorBlinkStateManager {
+  public isCursorVisible: boolean;
+
+  private _animationFrame: number;
+  private _blinkStartTimeout: number;
+  private _blinkInterval: number;
+
+  /**
+   * The time at which the animation frame was restarted, this is used on the
+   * next render to restart the timers so they don't need to restart the timers
+   * multiple times over a short period.
+   */
+  private _animationTimeRestarted: number;
+
+  constructor(
+    isFocused: boolean,
+    private _renderCallback: () => void
+  ) {
+    this.isCursorVisible = true;
+    if (isFocused) {
+      this._restartInterval();
+    }
+  }
+
+  public get isPaused(): boolean { return !(this._blinkStartTimeout || this._blinkInterval); }
+
+  public dispose(): void {
+    if (this._blinkInterval) {
+      window.clearInterval(this._blinkInterval);
+      this._blinkInterval = null;
+    }
+    if (this._blinkStartTimeout) {
+      window.clearTimeout(this._blinkStartTimeout);
+      this._blinkStartTimeout = null;
+    }
+    if (this._animationFrame) {
+      window.cancelAnimationFrame(this._animationFrame);
+      this._animationFrame = null;
+    }
+  }
+
+  public restartBlinkAnimation(): void {
+    if (this.isPaused) {
+      return;
+    }
+    // Save a timestamp so that the restart can be done on the next interval
+    this._animationTimeRestarted = Date.now();
+    // Force a cursor render to ensure it's visible and in the correct position
+    this.isCursorVisible = true;
+    if (!this._animationFrame) {
+      this._animationFrame = window.requestAnimationFrame(() => {
+        this._renderCallback();
+        this._animationFrame = null;
+      });
+    }
+  }
+
+  private _restartInterval(timeToStart: number = BLINK_INTERVAL): void {
+    // Clear any existing interval
+    if (this._blinkInterval) {
+      window.clearInterval(this._blinkInterval);
+    }
+
+    // Setup the initial timeout which will hide the cursor, this is done before
+    // the regular interval is setup in order to support restarting the blink
+    // animation in a lightweight way (without thrashing clearInterval and
+    // setInterval).
+    this._blinkStartTimeout = <number><any>setTimeout(() => {
+      // Check if another animation restart was requested while this was being
+      // started
+      if (this._animationTimeRestarted) {
+        const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
+        this._animationTimeRestarted = null;
+        if (time > 0) {
+          this._restartInterval(time);
+          return;
+        }
+      }
+
+      // Hide the cursor
+      this.isCursorVisible = false;
+      this._animationFrame = window.requestAnimationFrame(() => {
+        this._renderCallback();
+        this._animationFrame = null;
+      });
+
+      // Setup the blink interval
+      this._blinkInterval = <number><any>setInterval(() => {
+        // Adjust the animation time if it was restarted
+        if (this._animationTimeRestarted) {
+          // calc time diff
+          // Make restart interval do a setTimeout initially?
+          const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
+          this._animationTimeRestarted = null;
+          this._restartInterval(time);
+          return;
+        }
+
+        // Invert visibility and render
+        this.isCursorVisible = !this.isCursorVisible;
+        this._animationFrame = window.requestAnimationFrame(() => {
+          this._renderCallback();
+          this._animationFrame = null;
+        });
+      }, BLINK_INTERVAL);
+    }, timeToStart);
+  }
+
+  public pause(): void {
+    this.isCursorVisible = true;
+    if (this._blinkInterval) {
+      window.clearInterval(this._blinkInterval);
+      this._blinkInterval = null;
+    }
+    if (this._blinkStartTimeout) {
+      window.clearTimeout(this._blinkStartTimeout);
+      this._blinkStartTimeout = null;
+    }
+    if (this._animationFrame) {
+      window.cancelAnimationFrame(this._animationFrame);
+      this._animationFrame = null;
+    }
+  }
+
+  public resume(): void {
+    this._animationTimeRestarted = null;
+    this._restartInterval();
+    this.restartBlinkAnimation();
+  }
+}
diff --git a/node_modules/xterm/src/renderer/Renderer.ts b/node_modules/xterm/src/renderer/Renderer.ts
new file mode 100644 (file)
index 0000000..d3977af
--- /dev/null
@@ -0,0 +1,208 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { TextRenderLayer } from '../browser/renderer/TextRenderLayer';
+import { SelectionRenderLayer } from '../browser/renderer/SelectionRenderLayer';
+import { CursorRenderLayer } from './CursorRenderLayer';
+import { IRenderLayer, IRenderer, IRenderDimensions, CharacterJoinerHandler, ICharacterJoinerRegistry } from 'browser/renderer/Types';
+import { ITerminal } from '../Types';
+import { LinkRenderLayer } from '../browser/renderer/LinkRenderLayer';
+import { CharacterJoinerRegistry } from 'browser/renderer/CharacterJoinerRegistry';
+import { Disposable } from 'common/Lifecycle';
+import { IColorSet } from 'browser/Types';
+import { ICharSizeService } from 'browser/services/Services';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+import { removeTerminalFromCache } from 'browser/renderer/atlas/CharAtlasCache';
+
+let nextRendererId = 1;
+
+export class Renderer extends Disposable implements IRenderer {
+  private _id = nextRendererId++;
+
+  private _renderLayers: IRenderLayer[];
+  private _devicePixelRatio: number;
+  private _characterJoinerRegistry: ICharacterJoinerRegistry;
+
+  public dimensions: IRenderDimensions;
+
+  constructor(
+    private _colors: IColorSet,
+    private readonly _terminal: ITerminal,
+    readonly bufferService: IBufferService,
+    private readonly _charSizeService: ICharSizeService,
+    readonly optionsService: IOptionsService
+  ) {
+    super();
+    const allowTransparency = this._terminal.options.allowTransparency;
+    this._characterJoinerRegistry = new CharacterJoinerRegistry(bufferService);
+
+    this._renderLayers = [
+      new TextRenderLayer(this._terminal.screenElement, 0, this._colors, this._characterJoinerRegistry, allowTransparency, this._id, bufferService, optionsService),
+      new SelectionRenderLayer(this._terminal.screenElement, 1, this._colors, this._id, bufferService, optionsService),
+      new LinkRenderLayer(this._terminal.screenElement, 2, this._colors, this._id, this._terminal.linkifier, bufferService, optionsService),
+      new CursorRenderLayer(this._terminal.screenElement, 3, this._colors, this._terminal, this._id, bufferService, optionsService)
+    ];
+    this.dimensions = {
+      scaledCharWidth: null,
+      scaledCharHeight: null,
+      scaledCellWidth: null,
+      scaledCellHeight: null,
+      scaledCharLeft: null,
+      scaledCharTop: null,
+      scaledCanvasWidth: null,
+      scaledCanvasHeight: null,
+      canvasWidth: null,
+      canvasHeight: null,
+      actualCellWidth: null,
+      actualCellHeight: null
+    };
+    this._devicePixelRatio = window.devicePixelRatio;
+    this._updateDimensions();
+    this.onOptionsChanged();
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this._renderLayers.forEach(l => l.dispose());
+    removeTerminalFromCache(this._id);
+  }
+
+  public onDevicePixelRatioChange(): void {
+    // If the device pixel ratio changed, the char atlas needs to be regenerated
+    // and the terminal needs to refreshed
+    if (this._devicePixelRatio !== window.devicePixelRatio) {
+      this._devicePixelRatio = window.devicePixelRatio;
+      this.onResize(this._terminal.cols, this._terminal.rows);
+    }
+  }
+
+  public setColors(colors: IColorSet): void {
+    this._colors = colors;
+
+    // Clear layers and force a full render
+    this._renderLayers.forEach(l => {
+      l.setColors(this._colors);
+      l.reset();
+    });
+  }
+
+  public onResize(cols: number, rows: number): void {
+    // Update character and canvas dimensions
+    this._updateDimensions();
+
+    // Resize all render layers
+    this._renderLayers.forEach(l => l.resize(this.dimensions));
+
+    // Resize the screen
+    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;
+    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;
+  }
+
+  public onCharSizeChanged(): void {
+    this.onResize(this._terminal.cols, this._terminal.rows);
+  }
+
+  public onBlur(): void {
+    this._runOperation(l => l.onBlur());
+  }
+
+  public onFocus(): void {
+    this._runOperation(l => l.onFocus());
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {
+    this._runOperation(l => l.onSelectionChanged(start, end, columnSelectMode));
+  }
+
+  public onCursorMove(): void {
+    this._runOperation(l => l.onCursorMove());
+  }
+
+  public onOptionsChanged(): void {
+    this._runOperation(l => l.onOptionsChanged());
+  }
+
+  public clear(): void {
+    this._runOperation(l => l.reset());
+  }
+
+  private _runOperation(operation: (layer: IRenderLayer) => void): void {
+    this._renderLayers.forEach(l => operation(l));
+  }
+
+  /**
+   * Performs the refresh loop callback, calling refresh only if a refresh is
+   * necessary before queueing up the next one.
+   */
+  public renderRows(start: number, end: number): void {
+    this._renderLayers.forEach(l => l.onGridChanged(start, end));
+  }
+
+  /**
+   * Recalculates the character and canvas dimensions.
+   */
+  private _updateDimensions(): void {
+    if (!this._charSizeService.hasValidSize) {
+      return;
+    }
+
+    // Calculate the scaled character width. Width is floored as it must be
+    // drawn to an integer grid in order for the CharAtlas "stamps" to not be
+    // blurry. When text is drawn to the grid not using the CharAtlas, it is
+    // clipped to ensure there is no overlap with the next cell.
+    this.dimensions.scaledCharWidth = Math.floor(this._charSizeService.width * window.devicePixelRatio);
+
+    // Calculate the scaled character height. Height is ceiled in case
+    // devicePixelRatio is a floating point number in order to ensure there is
+    // enough space to draw the character to the cell.
+    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);
+
+    // Calculate the scaled cell height, if lineHeight is not 1 then the value
+    // will be floored because since lineHeight can never be lower then 1, there
+    // is a guarentee that the scaled line height will always be larger than
+    // scaled char height.
+    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);
+
+    // Calculate the y coordinate within a cell that text should draw from in
+    // order to draw in the center of a cell.
+    this.dimensions.scaledCharTop = this._terminal.options.lineHeight === 1 ? 0 : Math.round((this.dimensions.scaledCellHeight - this.dimensions.scaledCharHeight) / 2);
+
+    // Calculate the scaled cell width, taking the letterSpacing into account.
+    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);
+
+    // Calculate the x coordinate with a cell that text should draw from in
+    // order to draw in the center of a cell.
+    this.dimensions.scaledCharLeft = Math.floor(this._terminal.options.letterSpacing / 2);
+
+    // Recalculate the canvas dimensions; scaled* define the actual number of
+    // pixel in the canvas
+    this.dimensions.scaledCanvasHeight = this._terminal.rows * this.dimensions.scaledCellHeight;
+    this.dimensions.scaledCanvasWidth = this._terminal.cols * this.dimensions.scaledCellWidth;
+
+    // The the size of the canvas on the page. It's very important that this
+    // rounds to nearest integer and not ceils as browsers often set
+    // window.devicePixelRatio as something like 1.100000023841858, when it's
+    // actually 1.1. Ceiling causes blurriness as the backing canvas image is 1
+    // pixel too large for the canvas element size.
+    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);
+    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);
+
+    // Get the _actual_ dimensions of an individual cell. This needs to be
+    // derived from the canvasWidth/Height calculated above which takes into
+    // account window.devicePixelRatio. ICharSizeService.width/height by itself
+    // is insufficient when the page is not at 100% zoom level as it's measured
+    // in CSS pixels, but the actual char size on the canvas can differ.
+    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;
+    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {
+    return this._characterJoinerRegistry.registerCharacterJoiner(handler);
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): boolean {
+    return this._characterJoinerRegistry.deregisterCharacterJoiner(joinerId);
+  }
+}
diff --git a/node_modules/xterm/src/renderer/dom/DomRenderer.ts b/node_modules/xterm/src/renderer/dom/DomRenderer.ts
new file mode 100644 (file)
index 0000000..ef927f2
--- /dev/null
@@ -0,0 +1,392 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { ITerminal } from '../../Types';
+import { BOLD_CLASS, ITALIC_CLASS, CURSOR_CLASS, CURSOR_STYLE_BLOCK_CLASS, CURSOR_BLINK_CLASS, CURSOR_STYLE_BAR_CLASS, CURSOR_STYLE_UNDERLINE_CLASS, DomRendererRowFactory } from 'browser/renderer/dom/DomRendererRowFactory';
+import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { Disposable } from 'common/Lifecycle';
+import { IColorSet, ILinkifierEvent } from 'browser/Types';
+import { ICharSizeService } from 'browser/services/Services';
+import { IOptionsService } from 'common/services/Services';
+
+const TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-';
+const ROW_CONTAINER_CLASS = 'xterm-rows';
+const FG_CLASS_PREFIX = 'xterm-fg-';
+const BG_CLASS_PREFIX = 'xterm-bg-';
+const FOCUS_CLASS = 'xterm-focus';
+const SELECTION_CLASS = 'xterm-selection';
+
+let nextTerminalId = 1;
+
+/**
+ * A fallback renderer for when canvas is slow. This is not meant to be
+ * particularly fast or feature complete, more just stable and usable for when
+ * canvas is not an option.
+ */
+export class DomRenderer extends Disposable implements IRenderer {
+  private _rowFactory: DomRendererRowFactory;
+  private _terminalClass: number = nextTerminalId++;
+
+  private _themeStyleElement: HTMLStyleElement;
+  private _dimensionsStyleElement: HTMLStyleElement;
+  private _rowContainer: HTMLElement;
+  private _rowElements: HTMLElement[] = [];
+  private _selectionContainer: HTMLElement;
+
+  public dimensions: IRenderDimensions;
+
+  constructor(
+    private _terminal: ITerminal,
+    private _colors: IColorSet,
+    private _charSizeService: ICharSizeService,
+    private _optionsService: IOptionsService
+  ) {
+    super();
+
+    this._rowContainer = document.createElement('div');
+    this._rowContainer.classList.add(ROW_CONTAINER_CLASS);
+    this._rowContainer.style.lineHeight = 'normal';
+    this._rowContainer.setAttribute('aria-hidden', 'true');
+    this._refreshRowElements(this._terminal.cols, this._terminal.rows);
+    this._selectionContainer = document.createElement('div');
+    this._selectionContainer.classList.add(SELECTION_CLASS);
+    this._selectionContainer.setAttribute('aria-hidden', 'true');
+
+    this.dimensions = {
+      scaledCharWidth: null,
+      scaledCharHeight: null,
+      scaledCellWidth: null,
+      scaledCellHeight: null,
+      scaledCharLeft: null,
+      scaledCharTop: null,
+      scaledCanvasWidth: null,
+      scaledCanvasHeight: null,
+      canvasWidth: null,
+      canvasHeight: null,
+      actualCellWidth: null,
+      actualCellHeight: null
+    };
+    this._updateDimensions();
+    this._injectCss();
+
+    this._rowFactory = new DomRendererRowFactory(document, this._optionsService);
+
+    this._terminal.element.classList.add(TERMINAL_CLASS_PREFIX + this._terminalClass);
+    this._terminal.screenElement.appendChild(this._rowContainer);
+    this._terminal.screenElement.appendChild(this._selectionContainer);
+
+    this._terminal.linkifier.onLinkHover(e => this._onLinkHover(e));
+    this._terminal.linkifier.onLinkLeave(e => this._onLinkLeave(e));
+  }
+
+  public dispose(): void {
+    this._terminal.element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass);
+    this._terminal.screenElement.removeChild(this._rowContainer);
+    this._terminal.screenElement.removeChild(this._selectionContainer);
+    this._terminal.screenElement.removeChild(this._themeStyleElement);
+    this._terminal.screenElement.removeChild(this._dimensionsStyleElement);
+    super.dispose();
+  }
+
+  private _updateDimensions(): void {
+    this.dimensions.scaledCharWidth = this._charSizeService.width * window.devicePixelRatio;
+    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);
+    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);
+    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);
+    this.dimensions.scaledCharLeft = 0;
+    this.dimensions.scaledCharTop = 0;
+    this.dimensions.scaledCanvasWidth = this.dimensions.scaledCellWidth * this._terminal.cols;
+    this.dimensions.scaledCanvasHeight = this.dimensions.scaledCellHeight * this._terminal.rows;
+    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);
+    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);
+    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;
+    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;
+
+    this._rowElements.forEach(element => {
+      element.style.width = `${this.dimensions.canvasWidth}px`;
+      element.style.height = `${this.dimensions.actualCellHeight}px`;
+      element.style.lineHeight = `${this.dimensions.actualCellHeight}px`;
+      // Make sure rows don't overflow onto following row
+      element.style.overflow = 'hidden';
+    });
+
+    if (!this._dimensionsStyleElement) {
+      this._dimensionsStyleElement = document.createElement('style');
+      this._terminal.screenElement.appendChild(this._dimensionsStyleElement);
+    }
+
+    const styles =
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} span {` +
+        ` display: inline-block;` +
+        ` height: 100%;` +
+        ` vertical-align: top;` +
+        ` width: ${this.dimensions.actualCellWidth}px` +
+        `}`;
+
+    this._dimensionsStyleElement.innerHTML = styles;
+
+    this._selectionContainer.style.height = (<any>this._terminal)._viewportElement.style.height;
+    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;
+    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;
+  }
+
+  public setColors(colors: IColorSet): void {
+    this._colors = colors;
+    this._injectCss();
+  }
+
+  private _injectCss(): void {
+    if (!this._themeStyleElement) {
+      this._themeStyleElement = document.createElement('style');
+      this._terminal.screenElement.appendChild(this._themeStyleElement);
+    }
+
+    // Base CSS
+    let styles =
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} {` +
+        ` color: ${this._colors.foreground.css};` +
+        ` background-color: ${this._colors.background.css};` +
+        ` font-family: ${this._terminal.options.fontFamily};` +
+        ` font-size: ${this._terminal.options.fontSize}px;` +
+        `}`;
+    // Text styles
+    styles +=
+        `${this._terminalSelector} span:not(.${BOLD_CLASS}) {` +
+        ` font-weight: ${this._terminal.options.fontWeight};` +
+        `}` +
+        `${this._terminalSelector} span.${BOLD_CLASS} {` +
+        ` font-weight: ${this._terminal.options.fontWeightBold};` +
+        `}` +
+        `${this._terminalSelector} span.${ITALIC_CLASS} {` +
+        ` font-style: italic;` +
+        `}`;
+    // Blink animation
+    styles +=
+        `@keyframes blink_box_shadow {` +
+        ` 50% {` +
+        `  box-shadow: none;` +
+        ` }` +
+        `}`;
+    styles +=
+        `@keyframes blink_block {` +
+        ` 0% {` +
+        `  background-color: ${this._colors.cursor.css};` +
+        `  color: ${this._colors.cursorAccent.css};` +
+        ` }` +
+        ` 50% {` +
+        `  background-color: ${this._colors.cursorAccent.css};` +
+        `  color: ${this._colors.cursor.css};` +
+        ` }` +
+        `}`;
+    // Cursor
+    styles +=
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}:not(.${FOCUS_CLASS}) .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +
+        ` outline: 1px solid ${this._colors.cursor.css};` +
+        ` outline-offset: -1px;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}:not(.${CURSOR_STYLE_BLOCK_CLASS}) {` +
+        ` animation: blink_box_shadow 1s step-end infinite;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +
+        ` animation: blink_block 1s step-end infinite;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +
+        ` background-color: ${this._colors.cursor.css};` +
+        ` color: ${this._colors.cursorAccent.css};` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BAR_CLASS} {` +
+        ` box-shadow: 1px 0 0 ${this._colors.cursor.css} inset;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_UNDERLINE_CLASS} {` +
+        ` box-shadow: 0 -1px 0 ${this._colors.cursor.css} inset;` +
+        `}`;
+    // Selection
+    styles +=
+        `${this._terminalSelector} .${SELECTION_CLASS} {` +
+        ` position: absolute;` +
+        ` top: 0;` +
+        ` left: 0;` +
+        ` z-index: 1;` +
+        ` pointer-events: none;` +
+        `}` +
+        `${this._terminalSelector} .${SELECTION_CLASS} div {` +
+        ` position: absolute;` +
+        ` background-color: ${this._colors.selection.css};` +
+        `}`;
+    // Colors
+    this._colors.ansi.forEach((c, i) => {
+      styles +=
+          `${this._terminalSelector} .${FG_CLASS_PREFIX}${i} { color: ${c.css}; }` +
+          `${this._terminalSelector} .${BG_CLASS_PREFIX}${i} { background-color: ${c.css}; }`;
+    });
+    styles +=
+        `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { color: ${this._colors.background.css}; }` +
+        `${this._terminalSelector} .${BG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { background-color: ${this._colors.foreground.css}; }`;
+
+    this._themeStyleElement.innerHTML = styles;
+  }
+
+  public onDevicePixelRatioChange(): void {
+    this._updateDimensions();
+  }
+
+  private _refreshRowElements(cols: number, rows: number): void {
+    // Add missing elements
+    for (let i = this._rowElements.length; i <= rows; i++) {
+      const row = document.createElement('div');
+      this._rowContainer.appendChild(row);
+      this._rowElements.push(row);
+    }
+    // Remove excess elements
+    while (this._rowElements.length > rows) {
+      this._rowContainer.removeChild(this._rowElements.pop());
+    }
+  }
+
+  public onResize(cols: number, rows: number): void {
+    this._refreshRowElements(cols, rows);
+    this._updateDimensions();
+  }
+
+  public onCharSizeChanged(): void {
+    this._updateDimensions();
+  }
+
+  public onBlur(): void {
+    this._rowContainer.classList.remove(FOCUS_CLASS);
+  }
+
+  public onFocus(): void {
+    this._rowContainer.classList.add(FOCUS_CLASS);
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {
+    // Remove all selections
+    while (this._selectionContainer.children.length) {
+      this._selectionContainer.removeChild(this._selectionContainer.children[0]);
+    }
+
+    // Selection does not exist
+    if (!start || !end) {
+      return;
+    }
+
+    // Translate from buffer position to viewport position
+    const viewportStartRow = start[1] - this._terminal.buffer.ydisp;
+    const viewportEndRow = end[1] - this._terminal.buffer.ydisp;
+    const viewportCappedStartRow = Math.max(viewportStartRow, 0);
+    const viewportCappedEndRow = Math.min(viewportEndRow, this._terminal.rows - 1);
+
+    // No need to draw the selection
+    if (viewportCappedStartRow >= this._terminal.rows || viewportCappedEndRow < 0) {
+      return;
+    }
+
+    // Create the selections
+    const documentFragment = document.createDocumentFragment();
+
+    if (columnSelectMode) {
+      documentFragment.appendChild(
+        this._createSelectionElement(viewportCappedStartRow, start[0], end[0], viewportCappedEndRow - viewportCappedStartRow + 1)
+      );
+    } else {
+      // Draw first row
+      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;
+      const endCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._terminal.cols;
+      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol));
+      // Draw middle rows
+      const middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1;
+      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._terminal.cols, middleRowsCount));
+      // Draw final row
+      if (viewportCappedStartRow !== viewportCappedEndRow) {
+        // Only draw viewportEndRow if it's not the same as viewporttartRow
+        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._terminal.cols;
+        documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol));
+      }
+    }
+    this._selectionContainer.appendChild(documentFragment);
+  }
+
+  /**
+   * Creates a selection element at the specified position.
+   * @param row The row of the selection.
+   * @param colStart The start column.
+   * @param colEnd The end columns.
+   */
+  private _createSelectionElement(row: number, colStart: number, colEnd: number, rowCount: number = 1): HTMLElement {
+    const element = document.createElement('div');
+    element.style.height = `${rowCount * this.dimensions.actualCellHeight}px`;
+    element.style.top = `${row * this.dimensions.actualCellHeight}px`;
+    element.style.left = `${colStart * this.dimensions.actualCellWidth}px`;
+    element.style.width = `${this.dimensions.actualCellWidth * (colEnd - colStart)}px`;
+    return element;
+  }
+
+  public onCursorMove(): void {
+    // No-op, the cursor is drawn when rows are drawn
+  }
+
+  public onOptionsChanged(): void {
+    // Force a refresh
+    this._updateDimensions();
+    this._injectCss();
+    this._terminal.refresh(0, this._terminal.rows - 1);
+  }
+
+  public clear(): void {
+    this._rowElements.forEach(e => e.innerHTML = '');
+  }
+
+  public renderRows(start: number, end: number): void {
+    const terminal = this._terminal;
+
+    const cursorAbsoluteY = terminal.buffer.ybase + terminal.buffer.y;
+    const cursorX = this._terminal.buffer.x;
+    const cursorBlink = this._terminal.options.cursorBlink;
+
+    for (let y = start; y <= end; y++) {
+      const rowElement = this._rowElements[y];
+      rowElement.innerHTML = '';
+
+      const row = y + terminal.buffer.ydisp;
+      const lineData = terminal.buffer.lines.get(row);
+      const cursorStyle = terminal.options.cursorStyle;
+      rowElement.appendChild(this._rowFactory.createRow(lineData, row === cursorAbsoluteY, cursorStyle, cursorX, cursorBlink, this.dimensions.actualCellWidth, terminal.cols));
+    }
+  }
+
+  private get _terminalSelector(): string {
+    return `.${TERMINAL_CLASS_PREFIX}${this._terminalClass}`;
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number { return -1; }
+  public deregisterCharacterJoiner(joinerId: number): boolean { return false; }
+
+  private _onLinkHover(e: ILinkifierEvent): void {
+    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true);
+  }
+
+  private _onLinkLeave(e: ILinkifierEvent): void {
+    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false);
+  }
+
+  private _setCellUnderline(x: number, x2: number, y: number, y2: number, cols: number, enabled: boolean): void {
+    while (x !== x2 || y !== y2) {
+      const row = this._rowElements[y];
+      if (!row) {
+        return;
+      }
+      const span = <HTMLElement>row.children[x];
+      if (span) {
+        span.style.textDecoration = enabled ? 'underline' : 'none';
+      }
+      if (++x >= cols) {
+        x = 0;
+        y++;
+      }
+    }
+  }
+}
diff --git a/node_modules/xterm/src/tsconfig-base.json b/node_modules/xterm/src/tsconfig-base.json
new file mode 100644 (file)
index 0000000..84d0c92
--- /dev/null
@@ -0,0 +1,13 @@
+{
+  "compilerOptions": {
+    "target": "es5",
+    "lib": [ "es5" ],
+    "rootDir": ".",
+
+    "sourceMap": true,
+    "removeComments": true,
+    "pretty": true,
+
+    "incremental": true
+  }
+}
diff --git a/node_modules/xterm/src/tsconfig-library-base.json b/node_modules/xterm/src/tsconfig-library-base.json
new file mode 100644 (file)
index 0000000..e08695d
--- /dev/null
@@ -0,0 +1,9 @@
+{
+  "extends": "./tsconfig-base.json",
+  "compilerOptions": {
+    "composite": true,
+    "strict": true,
+    "declarationMap": true,
+    "experimentalDecorators": true
+  }
+}
diff --git a/node_modules/xterm/src/tsconfig.json b/node_modules/xterm/src/tsconfig.json
new file mode 100644 (file)
index 0000000..9757666
--- /dev/null
@@ -0,0 +1,34 @@
+{
+  "extends": "./tsconfig-base",
+  "compilerOptions": {
+    "module": "commonjs",
+    "lib": [
+      "dom",
+      "es5",
+      "es6",
+      "scripthost",
+      "es2015.promise"
+    ],
+    "rootDir": ".",
+    "outDir": "../out",
+    "baseUrl": ".",
+    "paths": {
+      "common/*": [ "./common/*" ],
+      "browser/*": [ "./browser/*" ]
+    },
+
+    "noUnusedLocals": true,
+    "noImplicitAny": true
+  },
+  "include": [
+    "./**/*",
+    "../typings/xterm.d.ts"
+  ],
+  "exclude": [
+    "./addons/**/*"
+  ],
+  "references": [
+    { "path": "./common" },
+    { "path": "./browser" }
+  ]
+}
diff --git a/node_modules/xterm/tsconfig.all.json b/node_modules/xterm/tsconfig.all.json
new file mode 100644 (file)
index 0000000..7ddf33d
--- /dev/null
@@ -0,0 +1,14 @@
+{
+  "files": [],
+  "include": [],
+  "references": [
+    { "path": "./src" },
+    { "path": "./test/api" },
+    { "path": "./test/benchmark" },
+    { "path": "./addons/xterm-addon-attach/src" },
+    { "path": "./addons/xterm-addon-fit/src" },
+    { "path": "./addons/xterm-addon-search/src" },
+    { "path": "./addons/xterm-addon-web-links/src" },
+    { "path": "./addons/xterm-addon-webgl/src" }
+  ]
+}
diff --git a/node_modules/xterm/typings/xterm.d.ts b/node_modules/xterm/typings/xterm.d.ts
new file mode 100644 (file)
index 0000000..295a03b
--- /dev/null
@@ -0,0 +1,1105 @@
+/**
+ * @license MIT
+ *
+ * This contains the type declarations for the xterm.js library. Note that
+ * some interfaces differ between this file and the actual implementation in
+ * src/, that's because this file declares the *public* API which is intended
+ * to be stable and consumed by external programs.
+ */
+
+/// <reference lib="dom"/>
+
+declare module 'xterm' {
+  /**
+   * A string representing text font weight.
+   */
+  export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
+
+  /**
+   * A string representing log level.
+   */
+  export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';
+
+  /**
+   * A string representing a renderer type.
+   */
+  export type RendererType = 'dom' | 'canvas';
+
+  /**
+   * An object containing start up options for the terminal.
+   */
+  export interface ITerminalOptions {
+    /**
+     * Whether background should support non-opaque color. It must be set before
+     * executing the `Terminal.open()` method and can't be changed later without
+     * executing it again. Note that enabling this can negatively impact
+     * performance.
+     */
+    allowTransparency?: boolean;
+
+    /**
+     * A data uri of the sound to use for the bell when `bellStyle = 'sound'`.
+     */
+    bellSound?: string;
+
+    /**
+     * The type of the bell notification the terminal will use.
+     */
+    bellStyle?: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;
+
+    /**
+     * When enabled the cursor will be set to the beginning of the next line
+     * with every new line. This equivalent to sending '\r\n' for each '\n'.
+     * Normally the termios settings of the underlying PTY deals with the
+     * translation of '\n' to '\r\n' and this setting should not be used. If you
+     * deal with data from a non-PTY related source, this settings might be
+     * useful.
+     */
+    convertEol?: boolean;
+
+    /**
+     * The number of columns in the terminal.
+     */
+    cols?: number;
+
+    /**
+     * Whether the cursor blinks.
+     */
+    cursorBlink?: boolean;
+
+    /**
+     * The style of the cursor.
+     */
+    cursorStyle?: 'block' | 'underline' | 'bar';
+
+    /**
+     * Whether input should be disabled.
+     */
+    disableStdin?: boolean;
+
+    /**
+     * Whether to draw bold text in bright colors. The default is true.
+     */
+    drawBoldTextInBrightColors?: boolean;
+
+    /**
+     * The modifier key hold to multiply scroll speed.
+     */
+    fastScrollModifier?: 'alt' | 'ctrl' | 'shift' | undefined;
+
+    /**
+     * The scroll speed multiplier used for fast scrolling.
+     */
+    fastScrollSensitivity?: number;
+
+    /**
+     * The font size used to render text.
+     */
+    fontSize?: number;
+
+    /**
+     * The font family used to render text.
+     */
+    fontFamily?: string;
+
+    /**
+     * The font weight used to render non-bold text.
+     */
+    fontWeight?: FontWeight;
+
+    /**
+     * The font weight used to render bold text.
+     */
+    fontWeightBold?: FontWeight;
+
+    /**
+     * The spacing in whole pixels between characters..
+     */
+    letterSpacing?: number;
+
+    /**
+     * The line height used to render text.
+     */
+    lineHeight?: number;
+
+    /**
+     * What log level to use, this will log for all levels below and including
+     * what is set:
+     *
+     * 1. debug
+     * 2. info (default)
+     * 3. warn
+     * 4. error
+     * 5. off
+     */
+    logLevel?: LogLevel;
+
+    /**
+     * Whether to treat option as the meta key.
+     */
+    macOptionIsMeta?: boolean;
+
+    /**
+     * Whether holding a modifier key will force normal selection behavior,
+     * regardless of whether the terminal is in mouse events mode. This will
+     * also prevent mouse events from being emitted by the terminal. For
+     * example, this allows you to use xterm.js' regular selection inside tmux
+     * with mouse mode enabled.
+     */
+    macOptionClickForcesSelection?: boolean;
+
+    /**
+     * The type of renderer to use, this allows using the fallback DOM renderer
+     * when canvas is too slow for the environment. The following features do
+     * not work when the DOM renderer is used:
+     *
+     * - Letter spacing
+     * - Cursor blink
+     */
+    rendererType?: RendererType;
+
+    /**
+     * Whether to select the word under the cursor on right click, this is
+     * standard behavior in a lot of macOS applications.
+     */
+    rightClickSelectsWord?: boolean;
+
+    /**
+     * The number of rows in the terminal.
+     */
+    rows?: number;
+
+    /**
+     * Whether screen reader support is enabled. When on this will expose
+     * supporting elements in the DOM to support NVDA on Windows and VoiceOver
+     * on macOS.
+     */
+    screenReaderMode?: boolean;
+
+    /**
+     * The amount of scrollback in the terminal. Scrollback is the amount of
+     * rows that are retained when lines are scrolled beyond the initial
+     * viewport.
+     */
+    scrollback?: number;
+
+    /**
+     * The scrolling speed multiplier used for adjusting normal scrolling speed.
+     */
+    scrollSensitivity?: number;
+
+    /**
+     * The size of tab stops in the terminal.
+     */
+    tabStopWidth?: number;
+
+    /**
+     * The color theme of the terminal.
+     */
+    theme?: ITheme;
+
+    /**
+     * Whether "Windows mode" is enabled. Because Windows backends winpty and
+     * conpty operate by doing line wrapping on their side, xterm.js does not
+     * have access to wrapped lines. When Windows mode is enabled the following
+     * changes will be in effect:
+     *
+     * - Reflow is disabled.
+     * - Lines are assumed to be wrapped if the last character of the line is
+     *   not whitespace.
+     */
+    windowsMode?: boolean;
+
+    /**
+     * A string containing all characters that are considered word separated by the
+     * double click to select work logic.
+    */
+    wordSeparator?: string;
+  }
+
+  /**
+   * Contains colors to theme the terminal with.
+   */
+  export interface ITheme {
+    /** The default foreground color */
+    foreground?: string;
+    /** The default background color */
+    background?: string;
+    /** The cursor color */
+    cursor?: string;
+    /** The accent color of the cursor (fg color for a block cursor) */
+    cursorAccent?: string;
+    /** The selection background color (can be transparent) */
+    selection?: string;
+    /** ANSI black (eg. `\x1b[30m`) */
+    black?: string;
+    /** ANSI red (eg. `\x1b[31m`) */
+    red?: string;
+    /** ANSI green (eg. `\x1b[32m`) */
+    green?: string;
+    /** ANSI yellow (eg. `\x1b[33m`) */
+    yellow?: string;
+    /** ANSI blue (eg. `\x1b[34m`) */
+    blue?: string;
+    /** ANSI magenta (eg. `\x1b[35m`) */
+    magenta?: string;
+    /** ANSI cyan (eg. `\x1b[36m`) */
+    cyan?: string;
+    /** ANSI white (eg. `\x1b[37m`) */
+    white?: string;
+    /** ANSI bright black (eg. `\x1b[1;30m`) */
+    brightBlack?: string;
+    /** ANSI bright red (eg. `\x1b[1;31m`) */
+    brightRed?: string;
+    /** ANSI bright green (eg. `\x1b[1;32m`) */
+    brightGreen?: string;
+    /** ANSI bright yellow (eg. `\x1b[1;33m`) */
+    brightYellow?: string;
+    /** ANSI bright blue (eg. `\x1b[1;34m`) */
+    brightBlue?: string;
+    /** ANSI bright magenta (eg. `\x1b[1;35m`) */
+    brightMagenta?: string;
+    /** ANSI bright cyan (eg. `\x1b[1;36m`) */
+    brightCyan?: string;
+    /** ANSI bright white (eg. `\x1b[1;37m`) */
+    brightWhite?: string;
+  }
+
+  /**
+   * An object containing options for a link matcher.
+   */
+  export interface ILinkMatcherOptions {
+    /**
+     * The index of the link from the regex.match(text) call. This defaults to 0
+     * (for regular expressions without capture groups).
+     */
+    matchIndex?: number;
+
+    /**
+     * A callback that validates whether to create an individual link, pass
+     * whether the link is valid to the callback.
+     */
+    validationCallback?: (uri: string, callback: (isValid: boolean) => void) => void;
+
+    /**
+     * A callback that fires when the mouse hovers over a link for a moment.
+     */
+    tooltipCallback?: (event: MouseEvent, uri: string, location: IViewportRange) => boolean | void;
+
+    /**
+     * A callback that fires when the mouse leaves a link. Note that this can
+     * happen even when tooltipCallback hasn't fired for the link yet.
+     */
+    leaveCallback?: () => void;
+
+    /**
+     * The priority of the link matcher, this defines the order in which the
+     * link matcher is evaluated relative to others, from highest to lowest. The
+     * default value is 0.
+     */
+    priority?: number;
+
+    /**
+     * A callback that fires when the mousedown and click events occur that
+     * determines whether a link will be activated upon click. This enables
+     * only activating a link when a certain modifier is held down, if not the
+     * mouse event will continue propagation (eg. double click to select word).
+     */
+    willLinkActivate?: (event: MouseEvent, uri: string) => boolean;
+  }
+
+  /**
+   * An object that can be disposed via a dispose function.
+   */
+  export interface IDisposable {
+    dispose(): void;
+  }
+
+  /**
+   * An event that can be listened to.
+   * @returns an `IDisposable` to stop listening.
+   */
+  export interface IEvent<T> {
+    (listener: (e: T) => any): IDisposable;
+  }
+
+  /**
+   * Represents a specific line in the terminal that is tracked when scrollback
+   * is trimmed and lines are added or removed. This is a single line that may
+   * be part of a larger wrapped line.
+   */
+  export interface IMarker extends IDisposable {
+    /**
+     * A unique identifier for this marker.
+     */
+    readonly id: number;
+
+    /**
+     * Whether this marker is disposed.
+     */
+    readonly isDisposed: boolean;
+
+    /**
+     * The actual line index in the buffer at this point in time. This is set to
+     * -1 if the marker has been disposed.
+     */
+    readonly line: number;
+  }
+
+  /**
+   * The set of localizable strings.
+   */
+  export interface ILocalizableStrings {
+    /**
+     * The aria label for the underlying input textarea for the terminal.
+     */
+    promptLabel: string;
+
+    /**
+     * Announcement for when line reading is suppressed due to too many lines
+     * being printed to the terminal when `screenReaderMode` is enabled.
+     */
+    tooMuchOutput: string;
+  }
+
+  /**
+   * The class that represents an xterm.js terminal.
+   */
+  export class Terminal implements IDisposable {
+    /**
+     * The element containing the terminal.
+     */
+    readonly element: HTMLElement | undefined;
+
+    /**
+     * The textarea that accepts input for the terminal.
+     */
+    readonly textarea: HTMLTextAreaElement | undefined;
+
+    /**
+     * The number of rows in the terminal's viewport. Use
+     * `ITerminalOptions.rows` to set this in the constructor and
+     * `Terminal.resize` for when the terminal exists.
+     */
+    readonly rows: number;
+
+    /**
+     * The number of columns in the terminal's viewport. Use
+     * `ITerminalOptions.cols` to set this in the constructor and
+     * `Terminal.resize` for when the terminal exists.
+     */
+    readonly cols: number;
+
+    /**
+     * (EXPERIMENTAL) The terminal's current buffer, this might be either the
+     * normal buffer or the alt buffer depending on what's running in the
+     * terminal.
+     */
+    readonly buffer: IBuffer;
+
+    /**
+     * (EXPERIMENTAL) Get all markers registered against the buffer. If the alt
+     * buffer is active this will always return [].
+     */
+    readonly markers: ReadonlyArray<IMarker>;
+
+    /**
+     * (EXPERIMENTAL) Get the parser interface to register
+     * custom escape sequence handlers.
+     */
+    readonly parser: IParser;
+
+    /**
+     * Natural language strings that can be localized.
+     */
+    static strings: ILocalizableStrings;
+
+    /**
+     * Creates a new `Terminal` object.
+     *
+     * @param options An object containing a set of options.
+     */
+    constructor(options?: ITerminalOptions);
+
+    /**
+     * Adds an event listener for the cursor moves.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onCursorMove: IEvent<void>;
+
+    /**
+     * Adds an event listener for when a data event fires. This happens for
+     * example when the user types or pastes into the terminal. The event value
+     * is whatever `string` results, in a typical setup, this should be passed
+     * on to the backing pty.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onData: IEvent<string>;
+
+    /**
+     * Adds an event listener for a key is pressed. The event value contains the
+     * string that will be sent in the data event as well as the DOM event that
+     * triggered it.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onKey: IEvent<{ key: string, domEvent: KeyboardEvent }>;
+
+    /**
+     * Adds an event listener for when a line feed is added.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onLineFeed: IEvent<void>;
+
+    /**
+     * Adds an event listener for when a scroll occurs. The event value is the
+     * new position of the viewport.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onScroll: IEvent<number>;
+
+    /**
+     * Adds an event listener for when a selection change occurs.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onSelectionChange: IEvent<void>;
+
+    /**
+     * Adds an event listener for when rows are rendered. The event value
+     * contains the start row and end rows of the rendered area (ranges from `0`
+     * to `Terminal.rows - 1`).
+     * @returns an `IDisposable` to stop listening.
+     */
+    onRender: IEvent<{ start: number, end: number }>;
+
+    /**
+     * Adds an event listener for when the terminal is resized. The event value
+     * contains the new size.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onResize: IEvent<{ cols: number, rows: number }>;
+
+    /**
+     * Adds an event listener for when an OSC 0 or OSC 2 title change occurs.
+     * The event value is the new title.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onTitleChange: IEvent<string>;
+
+    /**
+     * Unfocus the terminal.
+     */
+    blur(): void;
+
+    /**
+     * Focus the terminal.
+     */
+    focus(): void;
+
+    /**
+     * Resizes the terminal. It's best practice to debounce calls to resize,
+     * this will help ensure that the pty can respond to the resize event
+     * before another one occurs.
+     * @param x The number of columns to resize to.
+     * @param y The number of rows to resize to.
+     */
+    resize(columns: number, rows: number): void;
+
+    /**
+     * Opens the terminal within an element.
+     * @param parent The element to create the terminal within. This element
+     * must be visible (have dimensions) when `open` is called as several DOM-
+     * based measurements need to be performed when this function is called.
+     */
+    open(parent: HTMLElement): void;
+
+    /**
+     * Attaches a custom key event handler which is run before keys are
+     * processed, giving consumers of xterm.js ultimate control as to what keys
+     * should be processed by the terminal and what keys should not.
+     * @param customKeyEventHandler The custom KeyboardEvent handler to attach.
+     * This is a function that takes a KeyboardEvent, allowing consumers to stop
+     * propagation and/or prevent the default action. The function returns
+     * whether the event should be processed by xterm.js.
+     */
+    attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void;
+
+    /**
+     * (EXPERIMENTAL) Registers a link matcher, allowing custom link patterns to
+     * be matched and handled.
+     * @param regex The regular expression to search for, specifically this
+     * searches the textContent of the rows. You will want to use \s to match a
+     * space ' ' character for example.
+     * @param handler The callback when the link is called.
+     * @param options Options for the link matcher.
+     * @return The ID of the new matcher, this can be used to deregister.
+     */
+    registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number;
+
+    /**
+     * (EXPERIMENTAL) Deregisters a link matcher if it has been registered.
+     * @param matcherId The link matcher's ID (returned after register)
+     */
+    deregisterLinkMatcher(matcherId: number): void;
+
+    /**
+     * (EXPERIMENTAL) Registers a character joiner, allowing custom sequences of
+     * characters to be rendered as a single unit. This is useful in particular
+     * for rendering ligatures and graphemes, among other things.
+     *
+     * Each registered character joiner is called with a string of text
+     * representing a portion of a line in the terminal that can be rendered as
+     * a single unit. The joiner must return a sorted array, where each entry is
+     * itself an array of length two, containing the start (inclusive) and end
+     * (exclusive) index of a substring of the input that should be rendered as
+     * a single unit. When multiple joiners are provided, the results of each
+     * are collected. If there are any overlapping substrings between them, they
+     * are combined into one larger unit that is drawn together.
+     *
+     * All character joiners that are registered get called every time a line is
+     * rendered in the terminal, so it is essential for the handler function to
+     * run as quickly as possible to avoid slowdowns when rendering. Similarly,
+     * joiners should strive to return the smallest possible substrings to
+     * render together, since they aren't drawn as optimally as individual
+     * characters.
+     *
+     * NOTE: character joiners are only used by the canvas renderer.
+     *
+     * @param handler The function that determines character joins. It is called
+     * with a string of text that is eligible for joining and returns an array
+     * where each entry is an array containing the start (inclusive) and end
+     * (exclusive) indexes of ranges that should be rendered as a single unit.
+     * @return The ID of the new joiner, this can be used to deregister
+     */
+    registerCharacterJoiner(handler: (text: string) => [number, number][]): number;
+
+    /**
+     * (EXPERIMENTAL) Deregisters the character joiner if one was registered.
+     * NOTE: character joiners are only used by the canvas renderer.
+     * @param joinerId The character joiner's ID (returned after register)
+     */
+    deregisterCharacterJoiner(joinerId: number): void;
+
+    /**
+     * (EXPERIMENTAL) Adds a marker to the normal buffer and returns it. If the
+     * alt buffer is active, undefined is returned.
+     * @param cursorYOffset The y position offset of the marker from the cursor.
+     */
+    addMarker(cursorYOffset: number): IMarker;
+
+    /**
+     * Gets whether the terminal has an active selection.
+     */
+    hasSelection(): boolean;
+
+    /**
+     * Gets the terminal's current selection, this is useful for implementing
+     * copy behavior outside of xterm.js.
+     */
+    getSelection(): string;
+
+    /**
+     * Gets the selection position or undefined if there is no selection.
+     */
+    getSelectionPosition(): ISelectionPosition | undefined;
+
+    /**
+     * Clears the current terminal selection.
+     */
+    clearSelection(): void;
+
+    /**
+     * Selects text within the terminal.
+     * @param column The column the selection starts at..
+     * @param row The row the selection starts at.
+     * @param length The length of the selection.
+     */
+    select(column: number, row: number, length: number): void;
+
+    /**
+     * Selects all text within the terminal.
+     */
+    selectAll(): void;
+
+    /**
+     * Selects text in the buffer between 2 lines.
+     * @param start The 0-based line index to select from (inclusive).
+     * @param end The 0-based line index to select to (inclusive).
+     */
+    selectLines(start: number, end: number): void;
+
+    /*
+     * Disposes of the terminal, detaching it from the DOM and removing any
+     * active listeners.
+     */
+    dispose(): void;
+
+    /**
+     * Scroll the display of the terminal
+     * @param amount The number of lines to scroll down (negative scroll up).
+     */
+    scrollLines(amount: number): void;
+
+    /**
+     * Scroll the display of the terminal by a number of pages.
+     * @param pageCount The number of pages to scroll (negative scrolls up).
+     */
+    scrollPages(pageCount: number): void;
+
+    /**
+     * Scrolls the display of the terminal to the top.
+     */
+    scrollToTop(): void;
+
+    /**
+     * Scrolls the display of the terminal to the bottom.
+     */
+    scrollToBottom(): void;
+
+    /**
+     * Scrolls to a line within the buffer.
+     * @param line The 0-based line index to scroll to.
+     */
+    scrollToLine(line: number): void;
+
+    /**
+     * Clear the entire buffer, making the prompt line the new first line.
+     */
+    clear(): void;
+
+    /**
+     * Write data to the terminal.
+     * @param data The data to write to the terminal. This can either be raw
+     * bytes given as Uint8Array from the pty or a string. Raw bytes will always
+     * be treated as UTF-8 encoded, string data as UTF-16.
+     * @param callback Optional callback that fires when the data was processed
+     * by the parser.
+     */
+    write(data: string | Uint8Array, callback?: () => void): void;
+
+    /**
+     * Writes data to the terminal, followed by a break line character (\n).
+     * @param data The data to write to the terminal. This can either be raw
+     * bytes given as Uint8Array from the pty or a string. Raw bytes will always
+     * be treated as UTF-8 encoded, string data as UTF-16.
+     * @param callback Optional callback that fires when the data was processed
+     * by the parser.
+     */
+    writeln(data: string | Uint8Array, callback?: () => void): void;
+
+    /**
+     * Write UTF8 data to the terminal.
+     * @param data The data to write to the terminal.
+     * @param callback Optional callback when data was processed.
+     * @deprecated use `write` instead
+     */
+    writeUtf8(data: Uint8Array, callback?: () => void): void;
+
+    /**
+     * Writes text to the terminal, performing the necessary transformations for pasted text.
+     * @param data The text to write to the terminal.
+     */
+    paste(data: string): void;
+
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'fontWeight' | 'fontWeightBold' | 'logLevel' | 'rendererType' | 'termName' | 'wordSeparator'): string;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell' | 'windowsMode'): boolean;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'colors'): string[];
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'cols' | 'fontSize' | 'letterSpacing' | 'lineHeight' | 'rows' | 'tabStopWidth' | 'scrollback'): number;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'handler'): (data: string) => void;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: string): any;
+
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'fontFamily' | 'termName' | 'bellSound' | 'wordSeparator', value: string): void;
+    /**
+    * Sets an option on the terminal.
+    * @param key The option key.
+    * @param value The option value.
+    */
+    setOption(key: 'fontWeight' | 'fontWeightBold', value: null | 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'): void;
+    /**
+    * Sets an option on the terminal.
+    * @param key The option key.
+    * @param value The option value.
+    */
+    setOption(key: 'logLevel', value: LogLevel): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'bellStyle', value: null | 'none' | 'visual' | 'sound' | 'both'): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'cursorStyle', value: null | 'block' | 'underline' | 'bar'): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'popOnBell' | 'rightClickSelectsWord' | 'screenKeys' | 'useFlowControl' | 'visualBell' | 'windowsMode', value: boolean): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'colors', value: string[]): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'fontSize' | 'letterSpacing' | 'lineHeight' | 'tabStopWidth' | 'scrollback', value: number): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'handler', value: (data: string) => void): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'theme', value: ITheme): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'cols' | 'rows', value: number): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: string, value: any): void;
+
+    /**
+     * Tells the renderer to refresh terminal content between two rows
+     * (inclusive) at the next opportunity.
+     * @param start The row to start from (between 0 and this.rows - 1).
+     * @param end The row to end at (between start and this.rows - 1).
+     */
+    refresh(start: number, end: number): void;
+
+    /**
+     * Perform a full reset (RIS, aka '\x1bc').
+     */
+    reset(): void;
+
+    /**
+     * Loads an addon into this instance of xterm.js.
+     * @param addon The addon to load.
+     */
+    loadAddon(addon: ITerminalAddon): void;
+  }
+
+  /**
+   * An addon that can provide additional functionality to the terminal.
+   */
+  export interface ITerminalAddon extends IDisposable {
+    /**
+     * This is called when the addon is activated.
+     */
+    activate(terminal: Terminal): void;
+  }
+
+  /**
+   * An object representing a selection within the terminal.
+   */
+  interface ISelectionPosition {
+    /**
+     * The start column of the selection.
+     */
+    startColumn: number;
+
+    /**
+     * The start row of the selection.
+     */
+    startRow: number;
+
+    /**
+     * The end column of the selection.
+     */
+    endColumn: number;
+
+    /**
+     * The end row of the selection.
+     */
+    endRow: number;
+  }
+
+  /**
+   * An object representing a range within the viewport of the terminal.
+   */
+  export interface IViewportRange {
+    /**
+     * The start of the range.
+     */
+    start: IViewportRangePosition;
+
+    /**
+     * The end of the range.
+     */
+    end: IViewportRangePosition;
+  }
+
+  /**
+   * An object representing a cell position within the viewport of the terminal.
+   */
+  interface IViewportRangePosition {
+    /**
+     * The x position of the cell. This is a 0-based index that refers to the
+     * space in between columns, not the column itself. Index 0 refers to the
+     * left side of the viewport, index `Terminal.cols` refers to the right side
+     * of the viewport. This can be thought of as how a cursor is positioned in
+     * a text editor.
+     */
+    x: number;
+
+    /**
+     * The y position of the cell. This is a 0-based index that refers to a
+     * specific row.
+     */
+    y: number;
+  }
+
+  /**
+   * Represents a terminal buffer.
+   */
+  interface IBuffer {
+    /**
+     * The y position of the cursor. This ranges between `0` (when the
+     * cursor is at baseY) and `Terminal.rows - 1` (when the cursor is on the
+     * last row).
+     */
+    readonly cursorY: number;
+
+    /**
+     * The x position of the cursor. This ranges between `0` (left side) and
+     * `Terminal.cols - 1` (right side).
+     */
+    readonly cursorX: number;
+
+    /**
+     * The line within the buffer where the top of the viewport is.
+     */
+    readonly viewportY: number;
+
+    /**
+     * The line within the buffer where the top of the bottom page is (when
+     * fully scrolled down);
+     */
+    readonly baseY: number;
+
+    /**
+     * The amount of lines in the buffer.
+     */
+    readonly length: number;
+
+    /**
+     * Gets a line from the buffer, or undefined if the line index does not
+     * exist.
+     *
+     * Note that the result of this function should be used immediately after
+     * calling as when the terminal updates it could lead to unexpected
+     * behavior.
+     *
+     * @param y The line index to get.
+     */
+    getLine(y: number): IBufferLine | undefined;
+  }
+
+  /**
+   * Represents a line in the terminal's buffer.
+   */
+  interface IBufferLine {
+    /**
+     * Whether the line is wrapped from the previous line.
+     */
+    readonly isWrapped: boolean;
+
+    /**
+     * Gets a cell from the line, or undefined if the line index does not exist.
+     *
+     * Note that the result of this function should be used immediately after
+     * calling as when the terminal updates it could lead to unexpected
+     * behavior.
+     *
+     * @param x The character index to get.
+     */
+    getCell(x: number): IBufferCell | undefined;
+
+    /**
+     * Gets the line as a string. Note that this is gets only the string for the
+     * line, not taking isWrapped into account.
+     *
+     * @param trimRight Whether to trim any whitespace at the right of the line.
+     * @param startColumn The column to start from (inclusive).
+     * @param endColumn The column to end at (exclusive).
+     */
+    translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string;
+  }
+
+  /**
+   * Represents a single cell in the terminal's buffer.
+   */
+  interface IBufferCell {
+    /**
+     * The character within the cell.
+     */
+    readonly char: string;
+
+    /**
+     * The width of the character. Some examples:
+     *
+     * - This is `1` for most cells.
+     * - This is `2` for wide character like CJK glyphs.
+     * - This is `0` for cells immediately following cells with a width of `2`.
+     */
+    readonly width: number;
+  }
+
+  /**
+   * (EXPERIMENTAL) Data type to register a CSI, DCS or ESC callback in the parser
+   * in the form:
+   *    ESC I..I F
+   *    CSI Prefix P..P I..I F
+   *    DCS Prefix P..P I..I F data_bytes ST
+   *
+   * with these rules/restrictions:
+   * - prefix can only be used with CSI and DCS
+   * - only one leading prefix byte is recognized by the parser
+   *   before any other parameter bytes (P..P)
+   * - intermediate bytes are recognized up to 2
+   *
+   * For custom sequences make sure to read ECMA-48 and the resources at
+   * vt100.net to not clash with existing sequences or reserved address space.
+   * General recommendations:
+   * - use private address space (see ECMA-48)
+   * - use max one intermediate byte (technically not limited by the spec,
+   *   in practice there are no sequences with more than one intermediate byte,
+   *   thus parsers might get confused with more intermediates)
+   * - test against other common emulators to check whether they escape/ignore
+   *   the sequence correctly
+   *
+   * Notes: OSC command registration is handled differently (see addOscHandler)
+   *        APC, PM or SOS is currently not supported.
+   */
+  export interface IFunctionIdentifier {
+    /**
+     * Optional prefix byte, must be in range \x3c .. \x3f.
+     * Usable in CSI and DCS.
+     */
+    prefix?: string;
+    /**
+     * Optional intermediate bytes, must be in range \x20 .. \x2f.
+     * Usable in CSI, DCS and ESC.
+     */
+    intermediates?: string;
+    /**
+     * Final byte, must be in range \x40 .. \x7e for CSI and DCS,
+     * \x30 .. \x7e for ESC.
+     */
+    final: string;
+  }
+
+  /**
+   * (EXPERIMENTAL) Parser interface.
+   */
+  export interface IParser {
+    /**
+     * Adds a handler for CSI escape sequences.
+     * @param id Specifies the function identifier under which the callback
+     * gets registered, e.g. {final: 'm'} for SGR.
+     * @param callback The function to handle the sequence. The callback is
+     * called with the numerical params. If the sequence has subparams the
+     * array will contain subarrays with their numercial values.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addCsiHandler or setCsiHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable;
+
+    /**
+     * Adds a handler for DCS escape sequences.
+     * @param id Specifies the function identifier under which the callback
+     * gets registered, e.g. {intermediates: '$' final: 'q'} for DECRQSS.
+     * @param callback The function to handle the sequence. Note that the
+     * function will only be called once if the sequence finished sucessfully.
+     * There is currently no way to intercept smaller data chunks, data chunks
+     * will be stored up until the sequence is finished. Since DCS sequences
+     * are not limited by the amount of data this might impose a problem for
+     * big payloads. Currently xterm.js limits DCS payload to 10 MB
+     * which should give enough room for most use cases.
+     * The function gets the payload and numerical parameters as arguments.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addDcsHandler or setDcsHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable;
+
+    /**
+     * Adds a handler for ESC escape sequences.
+     * @param id Specifies the function identifier under which the callback
+     * gets registered, e.g. {intermediates: '%' final: 'G'} for
+     * default charset selection.
+     * @param callback The function to handle the sequence.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addEscHandler or setEscHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable;
+
+    /**
+     * Adds a handler for OSC escape sequences.
+     * @param ident The number (first parameter) of the sequence.
+     * @param callback The function to handle the sequence. Note that the
+     * function will only be called once if the sequence finished sucessfully.
+     * There is currently no way to intercept smaller data chunks, data chunks
+     * will be stored up until the sequence is finished. Since OSC sequences
+     * are not limited by the amount of data this might impose a problem for
+     * big payloads. Currently xterm.js limits OSC payload to 10 MB
+     * which should give enough room for most use cases.
+     * The callback is called with OSC data string.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addOscHandler or setOscHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable;
+  }
+}
diff --git a/npm-debug.log b/npm-debug.log
deleted file mode 100644 (file)
index a2cfa34..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-0 info it worked if it ends with ok
-1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'start' ]
-2 info using npm@1.4.21
-3 info using node@v8.11.1
-4 verbose run-script [ 'prestart', 'start', 'poststart' ]
-5 info prestart web@1.0.0
-6 info start web@1.0.0
-7 verbose unsafe-perm in lifecycle true
-8 info web@1.0.0 Failed to exec start script
-9 error web@1.0.0 start: `node src/index.js`
-9 error Exit status 1
-10 error Failed at the web@1.0.0 start script.
-10 error This is most likely a problem with the web package,
-10 error not with npm itself.
-10 error Tell the author that this fails on your system:
-10 error     node src/index.js
-10 error You can get their info via:
-10 error     npm owner ls web
-10 error There is likely additional logging output above.
-11 error System Linux 4.19.57-v7+
-12 error command "/usr/bin/node" "/usr/bin/npm" "start"
-13 error cwd /home/pi/VSoRC
-14 error node -v v8.11.1
-15 error npm -v 1.4.21
-16 error code ELIFECYCLE
-17 verbose exit [ 1, true ]
index 072e61e8ec8a4231a9918fdb2761358d82d40328..e231888305ea033abbb49f688d344db78c84f9f5 100644 (file)
@@ -18,6 +18,7 @@ app.use(express.json());
 app.use('/styles', express.static('styles'));
 app.use('/js', express.static('js'));
 app.use('/img', express.static('img'));
+app.use('/node_modules', express.static('node_modules'));
 //rutas
 app.use(require('./routes/index'));
 // Configurar cabeceras y cors
index 01b83278f1dd3d2eb4a99485b82be695da6886a8..ead4f5f564506cbc4feb707ffb1dc031122d8bce 100644 (file)
@@ -3,7 +3,9 @@
 
 <head>
   <title></title>
-  <!-- <link rel="stylesheet" type="text/css" href="/styles/main.css" /> -->
+  <!-- these are for the terminal -->
+  <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
+  <script src="node_modules/xterm/lib/xterm.js"></script>
   <%include ../../partials/head%>
   <style media="screen">
     body {
     </script>
   </main>
   <aside class="">
-    <div class="statuscontroller">
+    <div class="terminal"></div>
+    <script>
+      var term = new Terminal();
+      term.open(document.getElementById('terminal'));
+      term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
+    </script>
+
+
 
-    </div>
     <div class="statusproyect">
 
     </div>
 </footer>
 
 
-</html>
\ No newline at end of file
+</html>