From 4339da12467b75fb8b6ca831f4bf0081c485ed2c Mon Sep 17 00:00:00 2001 From: VSORC Date: Wed, 13 Nov 2019 17:31:35 -0400 Subject: [PATCH] xterm --- node_modules/.bin/mime | 9 +- node_modules/.bin/static | 132 +- node_modules/.bin/wscat | 368 ++- node_modules/xterm/LICENSE | 21 + node_modules/xterm/README.md | 190 ++ node_modules/xterm/css/xterm.css | 171 ++ node_modules/xterm/lib/xterm.js | 2 + node_modules/xterm/lib/xterm.js.map | 1 + node_modules/xterm/package.json | 99 + .../xterm/src/AccessibilityManager.ts | 297 +++ node_modules/xterm/src/InputHandler.ts | 2242 +++++++++++++++++ node_modules/xterm/src/Terminal.ts | 1610 ++++++++++++ node_modules/xterm/src/Types.d.ts | 260 ++ node_modules/xterm/src/WindowsMode.ts | 28 + node_modules/xterm/src/browser/Clipboard.ts | 111 + .../xterm/src/browser/ColorManager.ts | 190 ++ node_modules/xterm/src/browser/Lifecycle.ts | 29 + node_modules/xterm/src/browser/Linkifier.ts | 348 +++ .../xterm/src/browser/LocalizableStrings.ts | 7 + .../xterm/src/browser/MouseZoneManager.ts | 241 ++ .../xterm/src/browser/RenderDebouncer.ts | 63 + .../xterm/src/browser/ScreenDprMonitor.ts | 69 + node_modules/xterm/src/browser/Types.d.ts | 145 ++ node_modules/xterm/src/browser/Viewport.ts | 267 ++ .../src/browser/input/CompositionHelper.ts | 229 ++ node_modules/xterm/src/browser/input/Mouse.ts | 58 + .../xterm/src/browser/input/MoveToCell.ts | 230 ++ .../src/browser/renderer/BaseRenderLayer.ts | 385 +++ .../renderer/CharacterJoinerRegistry.ts | 326 +++ .../xterm/src/browser/renderer/GridCache.ts | 33 + .../src/browser/renderer/LinkRenderLayer.ts | 79 + .../src/browser/renderer/RendererUtils.ts | 11 + .../browser/renderer/SelectionRenderLayer.ts | 127 + .../src/browser/renderer/TextRenderLayer.ts | 324 +++ .../xterm/src/browser/renderer/Types.d.ts | 116 + .../browser/renderer/atlas/BaseCharAtlas.ts | 56 + .../browser/renderer/atlas/CharAtlasCache.ts | 95 + .../browser/renderer/atlas/CharAtlasUtils.ts | 56 + .../src/browser/renderer/atlas/Constants.ts | 9 + .../renderer/atlas/DynamicCharAtlas.ts | 369 +++ .../src/browser/renderer/atlas/LRUMap.ts | 136 + .../src/browser/renderer/atlas/Types.d.ts | 29 + .../renderer/dom/DomRendererRowFactory.ts | 132 + .../src/browser/selection/SelectionModel.ts | 135 + .../xterm/src/browser/selection/Types.d.ts | 10 + .../src/browser/services/CharSizeService.ts | 87 + .../src/browser/services/MouseService.ts | 35 + .../src/browser/services/RenderService.ts | 172 ++ .../src/browser/services/SelectionService.ts | 952 +++++++ .../xterm/src/browser/services/Services.ts | 95 + .../src/browser/services/SoundService.ts | 63 + node_modules/xterm/src/browser/tsconfig.json | 21 + node_modules/xterm/src/common/CharWidth.ts | 171 ++ node_modules/xterm/src/common/CircularList.ts | 235 ++ node_modules/xterm/src/common/Clone.ts | 23 + node_modules/xterm/src/common/EventEmitter.ts | 54 + node_modules/xterm/src/common/Lifecycle.ts | 47 + node_modules/xterm/src/common/Platform.ts | 39 + .../xterm/src/common/TypedArrayUtils.ts | 52 + node_modules/xterm/src/common/Types.d.ts | 253 ++ .../xterm/src/common/buffer/AttributeData.ts | 68 + .../xterm/src/common/buffer/Buffer.ts | 671 +++++ .../xterm/src/common/buffer/BufferLine.ts | 393 +++ .../xterm/src/common/buffer/BufferReflow.ts | 220 ++ .../xterm/src/common/buffer/BufferSet.ts | 122 + .../xterm/src/common/buffer/CellData.ts | 93 + .../xterm/src/common/buffer/Constants.ts | 128 + .../xterm/src/common/buffer/Marker.ts | 36 + .../xterm/src/common/buffer/Types.d.ts | 61 + .../xterm/src/common/data/Charsets.ts | 255 ++ .../xterm/src/common/data/EscapeSequences.ts | 150 ++ .../xterm/src/common/input/Keyboard.ts | 372 +++ .../xterm/src/common/input/TextDecoder.ts | 342 +++ .../xterm/src/common/input/WriteBuffer.ts | 110 + .../xterm/src/common/parser/Constants.ts | 58 + .../xterm/src/common/parser/DcsParser.ts | 146 ++ .../src/common/parser/EscapeSequenceParser.ts | 636 +++++ .../xterm/src/common/parser/OscParser.ts | 203 ++ .../xterm/src/common/parser/Params.ts | 229 ++ .../xterm/src/common/parser/Types.d.ts | 244 ++ .../src/common/services/BufferService.ts | 38 + .../src/common/services/CoreMouseService.ts | 296 +++ .../xterm/src/common/services/CoreService.ts | 60 + .../src/common/services/DirtyRowService.ts | 53 + .../common/services/InstantiationService.ts | 77 + .../xterm/src/common/services/LogService.ts | 97 + .../src/common/services/OptionsService.ts | 141 ++ .../src/common/services/ServiceRegistry.ts | 49 + .../xterm/src/common/services/Services.ts | 267 ++ node_modules/xterm/src/common/tsconfig.json | 14 + node_modules/xterm/src/public/AddonManager.ts | 56 + node_modules/xterm/src/public/Terminal.ts | 241 ++ .../xterm/src/renderer/CursorRenderLayer.ts | 368 +++ node_modules/xterm/src/renderer/Renderer.ts | 208 ++ .../xterm/src/renderer/dom/DomRenderer.ts | 392 +++ node_modules/xterm/src/tsconfig-base.json | 13 + .../xterm/src/tsconfig-library-base.json | 9 + node_modules/xterm/src/tsconfig.json | 34 + node_modules/xterm/tsconfig.all.json | 14 + node_modules/xterm/typings/xterm.d.ts | 1105 ++++++++ npm-debug.log | 26 - src/index.js | 1 + src/views/starter.ejs | 16 +- 103 files changed, 20223 insertions(+), 33 deletions(-) mode change 120000 => 100755 node_modules/.bin/mime mode change 120000 => 100755 node_modules/.bin/static mode change 120000 => 100755 node_modules/.bin/wscat create mode 100644 node_modules/xterm/LICENSE create mode 100644 node_modules/xterm/README.md create mode 100644 node_modules/xterm/css/xterm.css create mode 100644 node_modules/xterm/lib/xterm.js create mode 100644 node_modules/xterm/lib/xterm.js.map create mode 100644 node_modules/xterm/package.json create mode 100644 node_modules/xterm/src/AccessibilityManager.ts create mode 100644 node_modules/xterm/src/InputHandler.ts create mode 100644 node_modules/xterm/src/Terminal.ts create mode 100644 node_modules/xterm/src/Types.d.ts create mode 100644 node_modules/xterm/src/WindowsMode.ts create mode 100644 node_modules/xterm/src/browser/Clipboard.ts create mode 100644 node_modules/xterm/src/browser/ColorManager.ts create mode 100644 node_modules/xterm/src/browser/Lifecycle.ts create mode 100644 node_modules/xterm/src/browser/Linkifier.ts create mode 100644 node_modules/xterm/src/browser/LocalizableStrings.ts create mode 100644 node_modules/xterm/src/browser/MouseZoneManager.ts create mode 100644 node_modules/xterm/src/browser/RenderDebouncer.ts create mode 100644 node_modules/xterm/src/browser/ScreenDprMonitor.ts create mode 100644 node_modules/xterm/src/browser/Types.d.ts create mode 100644 node_modules/xterm/src/browser/Viewport.ts create mode 100644 node_modules/xterm/src/browser/input/CompositionHelper.ts create mode 100644 node_modules/xterm/src/browser/input/Mouse.ts create mode 100644 node_modules/xterm/src/browser/input/MoveToCell.ts create mode 100644 node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts create mode 100644 node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts create mode 100644 node_modules/xterm/src/browser/renderer/GridCache.ts create mode 100644 node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts create mode 100644 node_modules/xterm/src/browser/renderer/RendererUtils.ts create mode 100644 node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts create mode 100644 node_modules/xterm/src/browser/renderer/TextRenderLayer.ts create mode 100644 node_modules/xterm/src/browser/renderer/Types.d.ts create mode 100644 node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts create mode 100644 node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts create mode 100644 node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts create mode 100644 node_modules/xterm/src/browser/renderer/atlas/Constants.ts create mode 100644 node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts create mode 100644 node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts create mode 100644 node_modules/xterm/src/browser/renderer/atlas/Types.d.ts create mode 100644 node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts create mode 100644 node_modules/xterm/src/browser/selection/SelectionModel.ts create mode 100644 node_modules/xterm/src/browser/selection/Types.d.ts create mode 100644 node_modules/xterm/src/browser/services/CharSizeService.ts create mode 100644 node_modules/xterm/src/browser/services/MouseService.ts create mode 100644 node_modules/xterm/src/browser/services/RenderService.ts create mode 100644 node_modules/xterm/src/browser/services/SelectionService.ts create mode 100644 node_modules/xterm/src/browser/services/Services.ts create mode 100644 node_modules/xterm/src/browser/services/SoundService.ts create mode 100644 node_modules/xterm/src/browser/tsconfig.json create mode 100644 node_modules/xterm/src/common/CharWidth.ts create mode 100644 node_modules/xterm/src/common/CircularList.ts create mode 100644 node_modules/xterm/src/common/Clone.ts create mode 100644 node_modules/xterm/src/common/EventEmitter.ts create mode 100644 node_modules/xterm/src/common/Lifecycle.ts create mode 100644 node_modules/xterm/src/common/Platform.ts create mode 100644 node_modules/xterm/src/common/TypedArrayUtils.ts create mode 100644 node_modules/xterm/src/common/Types.d.ts create mode 100644 node_modules/xterm/src/common/buffer/AttributeData.ts create mode 100644 node_modules/xterm/src/common/buffer/Buffer.ts create mode 100644 node_modules/xterm/src/common/buffer/BufferLine.ts create mode 100644 node_modules/xterm/src/common/buffer/BufferReflow.ts create mode 100644 node_modules/xterm/src/common/buffer/BufferSet.ts create mode 100644 node_modules/xterm/src/common/buffer/CellData.ts create mode 100644 node_modules/xterm/src/common/buffer/Constants.ts create mode 100644 node_modules/xterm/src/common/buffer/Marker.ts create mode 100644 node_modules/xterm/src/common/buffer/Types.d.ts create mode 100644 node_modules/xterm/src/common/data/Charsets.ts create mode 100644 node_modules/xterm/src/common/data/EscapeSequences.ts create mode 100644 node_modules/xterm/src/common/input/Keyboard.ts create mode 100644 node_modules/xterm/src/common/input/TextDecoder.ts create mode 100644 node_modules/xterm/src/common/input/WriteBuffer.ts create mode 100644 node_modules/xterm/src/common/parser/Constants.ts create mode 100644 node_modules/xterm/src/common/parser/DcsParser.ts create mode 100644 node_modules/xterm/src/common/parser/EscapeSequenceParser.ts create mode 100644 node_modules/xterm/src/common/parser/OscParser.ts create mode 100644 node_modules/xterm/src/common/parser/Params.ts create mode 100644 node_modules/xterm/src/common/parser/Types.d.ts create mode 100644 node_modules/xterm/src/common/services/BufferService.ts create mode 100644 node_modules/xterm/src/common/services/CoreMouseService.ts create mode 100644 node_modules/xterm/src/common/services/CoreService.ts create mode 100644 node_modules/xterm/src/common/services/DirtyRowService.ts create mode 100644 node_modules/xterm/src/common/services/InstantiationService.ts create mode 100644 node_modules/xterm/src/common/services/LogService.ts create mode 100644 node_modules/xterm/src/common/services/OptionsService.ts create mode 100644 node_modules/xterm/src/common/services/ServiceRegistry.ts create mode 100644 node_modules/xterm/src/common/services/Services.ts create mode 100644 node_modules/xterm/src/common/tsconfig.json create mode 100644 node_modules/xterm/src/public/AddonManager.ts create mode 100644 node_modules/xterm/src/public/Terminal.ts create mode 100644 node_modules/xterm/src/renderer/CursorRenderLayer.ts create mode 100644 node_modules/xterm/src/renderer/Renderer.ts create mode 100644 node_modules/xterm/src/renderer/dom/DomRenderer.ts create mode 100644 node_modules/xterm/src/tsconfig-base.json create mode 100644 node_modules/xterm/src/tsconfig-library-base.json create mode 100644 node_modules/xterm/src/tsconfig.json create mode 100644 node_modules/xterm/tsconfig.all.json create mode 100644 node_modules/xterm/typings/xterm.d.ts delete mode 100644 npm-debug.log diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime deleted file mode 120000 index fbb7ee0..0000000 --- a/node_modules/.bin/mime +++ /dev/null @@ -1 +0,0 @@ -../mime/cli.js \ No newline at end of file diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 100755 index 0000000..20b1ffe --- /dev/null +++ b/node_modules/.bin/mime @@ -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'); + diff --git a/node_modules/.bin/static b/node_modules/.bin/static deleted file mode 120000 index 66f6f8a..0000000 --- a/node_modules/.bin/static +++ /dev/null @@ -1 +0,0 @@ -../node-static/bin/cli.js \ No newline at end of file diff --git a/node_modules/.bin/static b/node_modules/.bin/static new file mode 100755 index 0000000..ecdab3f --- /dev/null +++ b/node_modules/.bin/static @@ -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 ] []', + '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'] +')'); +} diff --git a/node_modules/.bin/wscat b/node_modules/.bin/wscat deleted file mode 120000 index 5392fc9..0000000 --- a/node_modules/.bin/wscat +++ /dev/null @@ -1 +0,0 @@ -../wscat/bin/wscat \ No newline at end of file diff --git a/node_modules/.bin/wscat b/node_modules/.bin/wscat new file mode 100755 index 0000000..48f0889 --- /dev/null +++ b/node_modules/.bin/wscat @@ -0,0 +1,367 @@ +#!/usr/bin/env node + +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * 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 | --connect )') + .option('-l, --listen ', 'listen on port') + .option('-c, --connect ', 'connect to a websocket server') + .option('-p, --protocol ', 'optional protocol version') + .option('-o, --origin ', 'optional origin') + .option('-x, --execute ', 'execute command after connecting') + .option('-w, --wait ', 'wait given seconds after executing command') + .option('--host ', 'optional host') + .option('-s, --subprotocol ', 'optional subprotocol', collect, []) + .option('-n, --no-check', 'Do not check for unauthorized certificates') + .option( + '-H, --header ', + 'Set an HTTP header. Repeat to set multiple. (--connect only)', + collect, + [] + ) + .option( + '--auth ', + 'Add basic HTTP authentication header. (--connect only)' + ) + .option('--ca ', 'Specify a Certificate Authority (--connect only)') + .option('--cert ', 'Specify a Client SSL Certificate (--connect only)') + .option( + '--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 index 0000000..4472336 --- /dev/null +++ b/node_modules/xterm/LICENSE @@ -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 index 0000000..5cf2848 --- /dev/null +++ b/node_modules/xterm/README.md @@ -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 `
` 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 + + + + + + + +
+ + + +``` + +### 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 `` 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)
+Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)
+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 index 0000000..b3d8d4f --- /dev/null +++ b/node_modules/xterm/css/xterm.css @@ -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 index 0000000..7ee6ebc --- /dev/null +++ b/node_modules/xterm/lib/xterm.js @@ -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>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;n65535?(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)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=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)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="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="",e.BS="\b",e.HT="\t",e.LF="\n",e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""}(t.C0||(t.C0={})),function(e){e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"}(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>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=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(n=0;nthis.length){var i=new Uint32Array(e*a);this.length&&(e*a=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=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=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>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;ot[n][1])return!1;for(;n>=r;)if(e>t[i=r+n>>1][1])r=i+1;else{if(!(e=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)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>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>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(;t0&&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=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>>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;t1)for(var u=this._getJoinedRanges(r,a,s,t,n),f=0;f1)for(u=this._getJoinedRanges(r,a,s,t,n),f=0;f=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=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=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&&i0?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?"[200~"+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.length131072)for(var n=0;n=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.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.yi.scrollBottom||i.yt.scrollBottom||t.yt.scrollBottom||t.yt.scrollBottom||t.yt.scrollBottom||t.y0||(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=2||2===r[1]&&s+n>=5)break;r[1]&&(n=1)}while(++s+t=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;i1)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;rn||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>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(++h47&&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;h0&&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)&&_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>>24,n=t.rgba>>>16&255,s=t.rgba>>>8&255,o=0;o=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.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=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>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]=t[0]&&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]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]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(;c1&&(_+=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(;p1&&(_+=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=0&&t0?r-s(o,r):t,e=i&&ct?"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;r0?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=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;ie&&r.y1<=t+1||r.y2>e&&r.y2<=t+1||r.y1t+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=s.x1&&i=s.x1||r===s.y2&&is.y1&&re;)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;t0)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=" ":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;et;)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;_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&&et.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._cols0&&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(r0&&(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;sthis._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=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&&h0&&(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;v0;)0===this.ybase?this.y0){var L=[],A=[];for(v=0;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;s0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);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?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.linee.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._currentthis._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;ithis._length)for(var t=this._length;t=e;n--)this._array[this._getCyclicIndex(n+i.length)]=this._array[this._getCyclicIndex(n)];for(n=0;nthis._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=a&&n0&&(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;ol&&(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=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){ethis._end&&(this._end=e)},e.prototype.markRangeDirty=function(e,t){if(e>t){var i=e;e=t,t=i}ethis._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;t0?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}),""+l(t[0])+l(t[1])+l(t[2])},SGR:function(e){var t=0===e.action&&4!==e.button?"m":"M";return"[<"+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;t5e7)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('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('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;\n\n /**\n * Human readable version of mouse events.\n */\n explainEvents(events: CoreMouseEventType): {[event: string]: boolean};\n}\n\nexport const ICoreService = createDecorator('CoreService');\nexport interface ICoreService {\n serviceBrand: any;\n\n readonly decPrivateModes: IDecPrivateModes;\n\n readonly onData: IEvent;\n readonly onUserInput: IEvent;\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('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 {\n (...args: any[]): void;\n type: T;\n}\n\nexport interface IConstructorSignature0 {\n new(...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature1 {\n new(first: A1, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature2 {\n new(first: A1, second: A2, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature3 {\n new(first: A1, second: A2, third: A3, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature4 {\n new(first: A1, second: A2, third: A3, fourth: A4, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature5 {\n new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature6 {\n new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature7 {\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 {\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('InstantiationService');\nexport interface IInstantiationService {\n setService(id: IServiceIdentifier, instance: T): void;\n\n createInstance(ctor: IConstructorSignature0): T;\n createInstance(ctor: IConstructorSignature1, first: A1): T;\n createInstance(ctor: IConstructorSignature2, first: A1, second: A2): T;\n createInstance(ctor: IConstructorSignature3, first: A1, second: A2, third: A3): T;\n createInstance(ctor: IConstructorSignature4, first: A1, second: A2, third: A3, fourth: A4): T;\n createInstance(ctor: IConstructorSignature5, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T;\n createInstance(ctor: IConstructorSignature6, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T;\n createInstance(ctor: IConstructorSignature7, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T;\n createInstance(ctor: IConstructorSignature8, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T;\n}\n\nexport const ILogService = createDecorator('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('OptionsService');\nexport interface IOptionsService {\n serviceBrand: any;\n\n readonly options: ITerminalOptions;\n\n readonly onOptionChange: IEvent;\n\n setOption(key: string, value: T): void;\n getOption(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 {\n (e: T): void;\n}\n\nexport interface IEvent {\n (listener: (e: T) => any): IDisposable;\n}\n\nexport interface IEventEmitter {\n event: IEvent;\n fire(data: T): void;\n}\n\nexport class EventEmitter implements IEventEmitter {\n private _listeners: IListener[] = [];\n private _event?: IEvent;\n\n public get event(): IEvent {\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[] = [];\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(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(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('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;\n\n measure(): void;\n}\n\nexport const IMouseService = createDecorator('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('RenderService');\nexport interface IRenderService extends IDisposable {\n serviceBrand: any;\n\n onDimensionsChange: IEvent;\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('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;\n readonly onRedrawRequest: IEvent;\n readonly onSelectionChange: IEvent;\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('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 = 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> = new Map();\n\nexport function getServiceDependencies(ctor: any): { id: IServiceIdentifier, index: number, optional: boolean }[] {\n return ctor[DI_DEPENDENCIES] || [];\n}\n\nexport function createDecorator(id: string): IServiceIdentifier {\n if (serviceRegistry.has(id)) {\n return serviceRegistry.get(id)!;\n }\n\n const decorator = 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(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(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(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 = 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 = 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 = {\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(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(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 { return this._core.onCursorMove; }\n public get onLineFeed(): IEvent { return this._core.onLineFeed; }\n public get onSelectionChange(): IEvent { return this._core.onSelectionChange; }\n public get onData(): IEvent { return this._core.onData; }\n public get onTitleChange(): IEvent { return this._core.onTitleChange; }\n public get onScroll(): IEvent { 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 { 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 = 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();\n public get onCursorMove(): IEvent { return this._onCursorMove.event; }\n private _onData = new EventEmitter();\n public get onData(): IEvent { 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();\n public get onLineFeed(): IEvent { 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();\n public get onScroll(): IEvent { return this._onScroll.event; }\n private _onSelectionChange = new EventEmitter();\n public get onSelectionChange(): IEvent { return this._onSelectionChange.event; }\n private _onTitleChange = new EventEmitter();\n public get onTitleChange(): IEvent { return this._onTitleChange.event; }\n\n private _onFocus = new EventEmitter();\n public get onFocus(): IEvent { return this._onFocus.event; }\n private _onBlur = new EventEmitter();\n public get onBlur(): IEvent { return this._onBlur.event; }\n public onA11yCharEmitter = new EventEmitter();\n public get onA11yChar(): IEvent { return this.onA11yCharEmitter.event; }\n public onA11yTabEmitter = new EventEmitter();\n public get onA11yTab(): IEvent { 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 ((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();\n public get onCursorMove(): IEvent { return this._onCursorMove.event; }\n private _onLineFeed = new EventEmitter();\n public get onLineFeed(): IEvent { return this._onLineFeed.event; }\n private _onScroll = new EventEmitter();\n public get onScroll(): IEvent { 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= 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; ST (set icon name + window title)\n * OSC 2; 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;\n protected _escHandlers: IHandlerCollection;\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;\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();\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 {\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;\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 {\n prev: ILinkedListNode | null;\n next: ILinkedListNode | null;\n key: number | null;\n value: T | null;\n}\n\nexport class LRUMap {\n private _map: { [key: number]: ILinkedListNode } = {};\n private _head: ILinkedListNode | null = null;\n private _tail: ILinkedListNode | null = null;\n private _nodePool: ILinkedListNode[] = [];\n public size: number = 0;\n\n constructor(public capacity: number) { }\n\n private _unlinkNode(node: ILinkedListNode): 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): 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 = 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 = 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();\n public get onLinkHover(): IEvent { return this._onLinkHover.event; }\n private _onLinkLeave = new EventEmitter();\n public get onLinkLeave(): IEvent { return this._onLinkLeave.event; }\n private _onLinkTooltip = new EventEmitter();\n public get onLinkTooltip(): IEvent { 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 = 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();\n public get onLinuxMouseSelection(): IEvent { return this._onLinuxMouseSelection.event; }\n private _onRedrawRequest = new EventEmitter();\n public get onRedrawRequest(): IEvent { return this._onRedrawRequest.event; }\n private _onSelectionChange = new EventEmitter();\n public get onSelectionChange(): IEvent { 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(event);\n this._mouseUpListener = event => this._onMouseUp(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 = (window).AudioContext || (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 = 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 = 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 = ' ';\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 = (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 = 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 // or + 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 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();\n public get onDimensionsChange(): IEvent { 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();\n public get onOptionChange(): IEvent { 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();\n public get onCharSizeChange(): IEvent { 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;\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(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(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 implements ICircularList {\n protected _array: (T | undefined)[];\n private _startIndex: number;\n private _length: number;\n\n public onDeleteEmitter = new EventEmitter();\n public get onDelete(): IEvent { return this.onDeleteEmitter.event; }\n public onInsertEmitter = new EventEmitter();\n public get onInsert(): IEvent { return this.onInsertEmitter.event; }\n public onTrimEmitter = new EventEmitter();\n public get onTrim(): IEvent { return this.onTrimEmitter.event; }\n\n constructor(\n private _maxLength: number\n ) {\n this._array = new Array(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(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, 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, 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, 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();\n public get onDispose(): IEvent { 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();\n public get onData(): IEvent { return this._onData.event; }\n private _onUserInput = new EventEmitter();\n public get onUserInput(): IEvent { 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, any>();\n\n constructor(...entries: [IServiceIdentifier, any][]) {\n for (const [id, service] of entries) {\n this.set(id, service);\n }\n }\n\n set(id: IServiceIdentifier, 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, instance: any) => any): void {\n this._entries.forEach((value, key) => callback(key, value));\n }\n\n has(id: IServiceIdentifier): boolean {\n return this._entries.has(id);\n }\n\n get(id: IServiceIdentifier): 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(id: IServiceIdentifier, instance: T): void {\n this._services.set(id, instance);\n }\n\n public createInstance(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 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();\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 {\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(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 index 0000000..1a629e7 --- /dev/null +++ b/node_modules/xterm/package.json @@ -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 index 0000000..75393ea --- /dev/null +++ b/node_modules/xterm/src/AccessibilityManager.ts @@ -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 = 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 = ' '; + } 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 index 0000000..7b6ea1f --- /dev/null +++ b/node_modules/xterm/src/InputHandler.ts @@ -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(); + public get onCursorMove(): IEvent { return this._onCursorMove.event; } + private _onLineFeed = new EventEmitter(); + public get onLineFeed(): IEvent { return this._onLineFeed.event; } + private _onScroll = new EventEmitter(); + public get onScroll(): IEvent { 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= 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; ST (set icon name + window title) + * OSC 2; 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 index 0000000..3e7e55c --- /dev/null +++ b/node_modules/xterm/src/Terminal.ts @@ -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 = 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(); + public get onCursorMove(): IEvent { return this._onCursorMove.event; } + private _onData = new EventEmitter(); + public get onData(): IEvent { 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(); + public get onLineFeed(): IEvent { 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(); + public get onScroll(): IEvent { return this._onScroll.event; } + private _onSelectionChange = new EventEmitter(); + public get onSelectionChange(): IEvent { return this._onSelectionChange.event; } + private _onTitleChange = new EventEmitter(); + public get onTitleChange(): IEvent { return this._onTitleChange.event; } + + private _onFocus = new EventEmitter(); + public get onFocus(): IEvent { return this._onFocus.event; } + private _onBlur = new EventEmitter(); + public get onBlur(): IEvent { return this._onBlur.event; } + public onA11yCharEmitter = new EventEmitter(); + public get onA11yChar(): IEvent { return this.onA11yCharEmitter.event; } + public onA11yTabEmitter = new EventEmitter(); + public get onA11yTab(): IEvent { 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 ((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 index 0000000..be1019e --- /dev/null +++ b/node_modules/xterm/src/Types.d.ts @@ -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; + onA11yTabEmitter: IEventEmitter; + + 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; + onFocus: IEvent; + onA11yChar: IEvent; + onA11yTab: IEvent; + + 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; + onData: IEvent; + onKey: IEvent<{ key: string, domEvent: KeyboardEvent }>; + onLineFeed: IEvent; + onScroll: IEvent; + onSelectionChange: IEvent; + onRender: IEvent<{ start: number, end: number }>; + onResize: IEvent<{ cols: number, rows: number }>; + onTitleChange: IEvent; + 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 index 0000000..0838cae --- /dev/null +++ b/node_modules/xterm/src/WindowsMode.ts @@ -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 index 0000000..594e442 --- /dev/null +++ b/node_modules/xterm/src/browser/Clipboard.ts @@ -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 index 0000000..70d21a7 --- /dev/null +++ b/node_modules/xterm/src/browser/ColorManager.ts @@ -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 index 0000000..1344ea9 --- /dev/null +++ b/node_modules/xterm/src/browser/Lifecycle.ts @@ -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 index 0000000..58aca70 --- /dev/null +++ b/node_modules/xterm/src/browser/Linkifier.ts @@ -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(); + public get onLinkHover(): IEvent { return this._onLinkHover.event; } + private _onLinkLeave = new EventEmitter(); + public get onLinkLeave(): IEvent { return this._onLinkLeave.event; } + private _onLinkTooltip = new EventEmitter(); + public get onLinkTooltip(): IEvent { 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 = 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 index 0000000..8e78233 --- /dev/null +++ b/node_modules/xterm/src/browser/LocalizableStrings.ts @@ -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 index 0000000..7eb7c5f --- /dev/null +++ b/node_modules/xterm/src/browser/MouseZoneManager.ts @@ -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 = 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 index 0000000..27c866d --- /dev/null +++ b/node_modules/xterm/src/browser/RenderDebouncer.ts @@ -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 index 0000000..ec8c6d8 --- /dev/null +++ b/node_modules/xterm/src/browser/ScreenDprMonitor.ts @@ -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 index 0000000..aa7a4c8 --- /dev/null +++ b/node_modules/xterm/src/browser/Types.d.ts @@ -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; + onLinkLeave: IEvent; + onLinkTooltip: IEvent; + + 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 index 0000000..b88f381 --- /dev/null +++ b/node_modules/xterm/src/browser/Viewport.ts @@ -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 index 0000000..e6994ea --- /dev/null +++ b/node_modules/xterm/src/browser/input/CompositionHelper.ts @@ -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 index 0000000..2986fb3 --- /dev/null +++ b/node_modules/xterm/src/browser/input/Mouse.ts @@ -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 index 0000000..406ec80 --- /dev/null +++ b/node_modules/xterm/src/browser/input/MoveToCell.ts @@ -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 index 0000000..e9ad5b3 --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts @@ -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 = 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 index 0000000..5385b76 --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts @@ -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 index 0000000..b48798d --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/GridCache.ts @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export class GridCache { + 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 index 0000000..a7be54e --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts @@ -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 index 0000000..48fd26a --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/RendererUtils.ts @@ -0,0 +1,11 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export function throwIfFalsy(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 index 0000000..5cd2fd9 --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts @@ -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 index 0000000..330400c --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/TextRenderLayer.ts @@ -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; + 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(); + 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 index 0000000..7f84dfd --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/Types.d.ts @@ -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 index 0000000..dc11460 --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts @@ -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 index 0000000..257835b --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts @@ -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 index 0000000..346b35f --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts @@ -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 = { + 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 index 0000000..150aad8 --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/atlas/Constants.ts @@ -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 index 0000000..40103bc --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts @@ -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; + + // 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 index 0000000..f70962f --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +interface ILinkedListNode { + prev: ILinkedListNode | null; + next: ILinkedListNode | null; + key: number | null; + value: T | null; +} + +export class LRUMap { + private _map: { [key: number]: ILinkedListNode } = {}; + private _head: ILinkedListNode | null = null; + private _tail: ILinkedListNode | null = null; + private _nodePool: ILinkedListNode[] = []; + public size: number = 0; + + constructor(public capacity: number) { } + + private _unlinkNode(node: ILinkedListNode): 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): 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 index 0000000..d8bc54c --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/atlas/Types.d.ts @@ -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 index 0000000..3e3b5df --- /dev/null +++ b/node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts @@ -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 index 0000000..1420444 --- /dev/null +++ b/node_modules/xterm/src/browser/selection/SelectionModel.ts @@ -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 index 0000000..d5a03ec --- /dev/null +++ b/node_modules/xterm/src/browser/selection/Types.d.ts @@ -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 index 0000000..0749a42 --- /dev/null +++ b/node_modules/xterm/src/browser/services/CharSizeService.ts @@ -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(); + public get onCharSizeChange(): IEvent { 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 index 0000000..b0f8c35 --- /dev/null +++ b/node_modules/xterm/src/browser/services/MouseService.ts @@ -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 index 0000000..63084f5 --- /dev/null +++ b/node_modules/xterm/src/browser/services/RenderService.ts @@ -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(); + public get onDimensionsChange(): IEvent { 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 index 0000000..3631bbb --- /dev/null +++ b/node_modules/xterm/src/browser/services/SelectionService.ts @@ -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(); + public get onLinuxMouseSelection(): IEvent { return this._onLinuxMouseSelection.event; } + private _onRedrawRequest = new EventEmitter(); + public get onRedrawRequest(): IEvent { return this._onRedrawRequest.event; } + private _onSelectionChange = new EventEmitter(); + public get onSelectionChange(): IEvent { 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(event); + this._mouseUpListener = event => this._onMouseUp(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 index 0000000..2170a04 --- /dev/null +++ b/node_modules/xterm/src/browser/services/Services.ts @@ -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('CharSizeService'); +export interface ICharSizeService { + serviceBrand: any; + + readonly width: number; + readonly height: number; + readonly hasValidSize: boolean; + + readonly onCharSizeChange: IEvent; + + measure(): void; +} + +export const IMouseService = createDecorator('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('RenderService'); +export interface IRenderService extends IDisposable { + serviceBrand: any; + + onDimensionsChange: IEvent; + 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('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; + readonly onRedrawRequest: IEvent; + readonly onSelectionChange: IEvent; + + 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('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 index 0000000..1772c75 --- /dev/null +++ b/node_modules/xterm/src/browser/services/SoundService.ts @@ -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 = (window).AudioContext || (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 index 0000000..7465bbd --- /dev/null +++ b/node_modules/xterm/src/browser/tsconfig.json @@ -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 index 0000000..24f5345 --- /dev/null +++ b/node_modules/xterm/src/common/CharWidth.ts @@ -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 index 0000000..d4ad3fc --- /dev/null +++ b/node_modules/xterm/src/common/CircularList.ts @@ -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 implements ICircularList { + protected _array: (T | undefined)[]; + private _startIndex: number; + private _length: number; + + public onDeleteEmitter = new EventEmitter(); + public get onDelete(): IEvent { return this.onDeleteEmitter.event; } + public onInsertEmitter = new EventEmitter(); + public get onInsert(): IEvent { return this.onInsertEmitter.event; } + public onTrimEmitter = new EventEmitter(); + public get onTrim(): IEvent { return this.onTrimEmitter.event; } + + constructor( + private _maxLength: number + ) { + this._array = new Array(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(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 index 0000000..51c5aba --- /dev/null +++ b/node_modules/xterm/src/common/Clone.ts @@ -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(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 index 0000000..34ac190 --- /dev/null +++ b/node_modules/xterm/src/common/EventEmitter.ts @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/Types'; + +interface IListener { + (e: T): void; +} + +export interface IEvent { + (listener: (e: T) => any): IDisposable; +} + +export interface IEventEmitter { + event: IEvent; + fire(data: T): void; +} + +export class EventEmitter implements IEventEmitter { + private _listeners: IListener[] = []; + private _event?: IEvent; + + public get event(): IEvent { + 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[] = []; + 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 index 0000000..ad1afa1 --- /dev/null +++ b/node_modules/xterm/src/common/Lifecycle.ts @@ -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(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(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 index 0000000..aae06c7 --- /dev/null +++ b/node_modules/xterm/src/common/Platform.ts @@ -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 index 0000000..5469983 --- /dev/null +++ b/node_modules/xterm/src/common/TypedArrayUtils.ts @@ -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(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(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(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 index 0000000..2f74203 --- /dev/null +++ b/node_modules/xterm/src/common/Types.d.ts @@ -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 { + length: number; + maxLength: number; + isFull: boolean; + + onDeleteEmitter: IEventEmitter; + onDelete: IEvent; + onInsertEmitter: IEventEmitter; + onInsert: IEvent; + onTrimEmitter: IEventEmitter; + onTrim: IEvent; + + 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 index 0000000..0e7e270 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/AttributeData.ts @@ -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 index 0000000..152bab7 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Buffer.ts @@ -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; + 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(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(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 index 0000000..1e95e00 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/BufferLine.ts @@ -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 index 0000000..ece9a96 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/BufferReflow.ts @@ -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, 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, 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, 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 index 0000000..50e6e50 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/BufferSet.ts @@ -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 index 0000000..21ad2ee --- /dev/null +++ b/node_modules/xterm/src/common/buffer/CellData.ts @@ -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 index 0000000..276a5c5 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Constants.ts @@ -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 index 0000000..9a4256d --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Marker.ts @@ -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(); + public get onDispose(): IEvent { 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 index 0000000..e229d69 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Types.d.ts @@ -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; + 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 index 0000000..56ca679 --- /dev/null +++ b/node_modules/xterm/src/common/data/Charsets.ts @@ -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 index 0000000..e35f01d --- /dev/null +++ b/node_modules/xterm/src/common/data/EscapeSequences.ts @@ -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 index 0000000..1bf378c --- /dev/null +++ b/node_modules/xterm/src/common/input/Keyboard.ts @@ -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) { + // or + 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 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 index 0000000..397d25a --- /dev/null +++ b/node_modules/xterm/src/common/input/TextDecoder.ts @@ -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 index 0000000..c7d8245 --- /dev/null +++ b/node_modules/xterm/src/common/input/WriteBuffer.ts @@ -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 index 0000000..85156c3 --- /dev/null +++ b/node_modules/xterm/src/common/parser/Constants.ts @@ -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 index 0000000..4622c4a --- /dev/null +++ b/node_modules/xterm/src/common/parser/DcsParser.ts @@ -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 = 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 index 0000000..bc0b620 --- /dev/null +++ b/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts @@ -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; + protected _escHandlers: IHandlerCollection; + 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 index 0000000..e8c5a80 --- /dev/null +++ b/node_modules/xterm/src/common/parser/OscParser.ts @@ -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 = 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 index 0000000..47ee129 --- /dev/null +++ b/node_modules/xterm/src/common/parser/Params.ts @@ -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 index 0000000..e2fac89 --- /dev/null +++ b/node_modules/xterm/src/common/parser/Types.d.ts @@ -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 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 { + start(): void; + end(success: boolean): void; +} + +export interface IDcsParser extends ISubParser { + 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 { + [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 index 0000000..c7b6afc --- /dev/null +++ b/node_modules/xterm/src/common/services/BufferService.ts @@ -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 index 0000000..500655b --- /dev/null +++ b/node_modules/xterm/src/common/services/CoreMouseService.ts @@ -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(); + 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 { + 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 index 0000000..0e0ba60 --- /dev/null +++ b/node_modules/xterm/src/common/services/CoreService.ts @@ -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(); + public get onData(): IEvent { return this._onData.event; } + private _onUserInput = new EventEmitter(); + public get onUserInput(): IEvent { 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 index 0000000..0f2f14f --- /dev/null +++ b/node_modules/xterm/src/common/services/DirtyRowService.ts @@ -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 index 0000000..abce8ac --- /dev/null +++ b/node_modules/xterm/src/common/services/InstantiationService.ts @@ -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, any>(); + + constructor(...entries: [IServiceIdentifier, any][]) { + for (const [id, service] of entries) { + this.set(id, service); + } + } + + set(id: IServiceIdentifier, instance: T): T { + const result = this._entries.get(id); + this._entries.set(id, instance); + return result; + } + + forEach(callback: (id: IServiceIdentifier, instance: any) => any): void { + this._entries.forEach((value, key) => callback(key, value)); + } + + has(id: IServiceIdentifier): boolean { + return this._entries.has(id); + } + + get(id: IServiceIdentifier): 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(id: IServiceIdentifier, instance: T): void { + this._services.set(id, instance); + } + + public createInstance(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 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 index 0000000..4f48d8f --- /dev/null +++ b/node_modules/xterm/src/common/services/LogService.ts @@ -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 index 0000000..d9ea60d --- /dev/null +++ b/node_modules/xterm/src/common/services/OptionsService.ts @@ -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(); + public get onOptionChange(): IEvent { 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 index 0000000..450af49 --- /dev/null +++ b/node_modules/xterm/src/common/services/ServiceRegistry.ts @@ -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> = new Map(); + +export function getServiceDependencies(ctor: any): { id: IServiceIdentifier, index: number, optional: boolean }[] { + return ctor[DI_DEPENDENCIES] || []; +} + +export function createDecorator(id: string): IServiceIdentifier { + if (serviceRegistry.has(id)) { + return serviceRegistry.get(id)!; + } + + const decorator = 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 index 0000000..0872d3d --- /dev/null +++ b/node_modules/xterm/src/common/services/Services.ts @@ -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('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('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; + + /** + * Human readable version of mouse events. + */ + explainEvents(events: CoreMouseEventType): {[event: string]: boolean}; +} + +export const ICoreService = createDecorator('CoreService'); +export interface ICoreService { + serviceBrand: any; + + readonly decPrivateModes: IDecPrivateModes; + + readonly onData: IEvent; + readonly onUserInput: IEvent; + + 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('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 { + (...args: any[]): void; + type: T; +} + +export interface IConstructorSignature0 { + new(...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature1 { + new(first: A1, ...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature2 { + new(first: A1, second: A2, ...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature3 { + new(first: A1, second: A2, third: A3, ...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature4 { + new(first: A1, second: A2, third: A3, fourth: A4, ...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature5 { + new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature6 { + new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature7 { + new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { serviceBrand: any; }[]): T; +} + +export interface IConstructorSignature8 { + 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('InstantiationService'); +export interface IInstantiationService { + setService(id: IServiceIdentifier, instance: T): void; + + createInstance(ctor: IConstructorSignature0): T; + createInstance(ctor: IConstructorSignature1, first: A1): T; + createInstance(ctor: IConstructorSignature2, first: A1, second: A2): T; + createInstance(ctor: IConstructorSignature3, first: A1, second: A2, third: A3): T; + createInstance(ctor: IConstructorSignature4, first: A1, second: A2, third: A3, fourth: A4): T; + createInstance(ctor: IConstructorSignature5, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T; + createInstance(ctor: IConstructorSignature6, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T; + createInstance(ctor: IConstructorSignature7, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T; + createInstance(ctor: IConstructorSignature8, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T; +} + +export const ILogService = createDecorator('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('OptionsService'); +export interface IOptionsService { + serviceBrand: any; + + readonly options: ITerminalOptions; + + readonly onOptionChange: IEvent; + + setOption(key: string, value: T): void; + getOption(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 index 0000000..59050a0 --- /dev/null +++ b/node_modules/xterm/src/common/tsconfig.json @@ -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 index 0000000..0261fd6 --- /dev/null +++ b/node_modules/xterm/src/public/AddonManager.ts @@ -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(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 index 0000000..c167bed --- /dev/null +++ b/node_modules/xterm/src/public/Terminal.ts @@ -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 { return this._core.onCursorMove; } + public get onLineFeed(): IEvent { return this._core.onLineFeed; } + public get onSelectionChange(): IEvent { return this._core.onSelectionChange; } + public get onData(): IEvent { return this._core.onData; } + public get onTitleChange(): IEvent { return this._core.onTitleChange; } + public get onScroll(): IEvent { 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 { 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 index 0000000..1f2791f --- /dev/null +++ b/node_modules/xterm/src/renderer/CursorRenderLayer.ts @@ -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 = 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 = 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 index 0000000..d3977af --- /dev/null +++ b/node_modules/xterm/src/renderer/Renderer.ts @@ -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 index 0000000..ef927f2 --- /dev/null +++ b/node_modules/xterm/src/renderer/dom/DomRenderer.ts @@ -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 = (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 = 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 index 0000000..84d0c92 --- /dev/null +++ b/node_modules/xterm/src/tsconfig-base.json @@ -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 index 0000000..e08695d --- /dev/null +++ b/node_modules/xterm/src/tsconfig-library-base.json @@ -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 index 0000000..9757666 --- /dev/null +++ b/node_modules/xterm/src/tsconfig.json @@ -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 index 0000000..7ddf33d --- /dev/null +++ b/node_modules/xterm/tsconfig.all.json @@ -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 index 0000000..295a03b --- /dev/null +++ b/node_modules/xterm/typings/xterm.d.ts @@ -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. + */ + +/// + +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 { + (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; + + /** + * (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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * Adds an event listener for when a selection change occurs. + * @returns an `IDisposable` to stop listening. + */ + onSelectionChange: IEvent; + + /** + * 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; + + /** + * 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 index a2cfa34..0000000 --- a/npm-debug.log +++ /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 ] diff --git a/src/index.js b/src/index.js index 072e61e..e231888 100644 --- a/src/index.js +++ b/src/index.js @@ -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 diff --git a/src/views/starter.ejs b/src/views/starter.ejs index 01b8327..ead4f5f 100644 --- a/src/views/starter.ejs +++ b/src/views/starter.ejs @@ -3,7 +3,9 @@ - + + + <%include ../../partials/head%>