diff --git a/README.md b/README.md index 0e7df5ac..d5488125 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,9 @@ Xterm.js is used in several world-class applications to provide great terminal e - [**Intervue**](https://www.intervue.io): Pair programming for interviews. Multiple programming languages supported, with results displayed by xterm.js. - [**TRASA**](https://trasa.io): Zero trust access to Web, SSH, RDP and Database services. - [**Commas**](https://github.com/CyanSalt/commas): Commas is a hackable terminal and command runner. +- [**Devtron**](https://github.com/devtron-labs/devtron): Software Delivery Workflow For Kubernetes. +- [**NxShell**](https://github.com/nxshell/nxshell): An easy to use new terminal for SSH. +- [**gifcast**](https://dstein64.github.io/gifcast/): Converts an asciinema cast to an animated GIF. [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. diff --git a/addons/xterm-addon-attach/src/AttachAddon.ts b/addons/xterm-addon-attach/src/AttachAddon.ts index 279d1b2e..035807ae 100644 --- a/addons/xterm-addon-attach/src/AttachAddon.ts +++ b/addons/xterm-addon-attach/src/AttachAddon.ts @@ -41,7 +41,9 @@ export class AttachAddon implements ITerminalAddon { } public dispose(): void { - this._disposables.forEach(d => d.dispose()); + for (const d of this._disposables) { + d.dispose(); + } } private _sendData(data: string): void { diff --git a/addons/xterm-addon-attach/test/AttachAddon.api.ts b/addons/xterm-addon-attach/test/AttachAddon.api.ts index 41e579f5..2dea645f 100644 --- a/addons/xterm-addon-attach/test/AttachAddon.api.ts +++ b/addons/xterm-addon-attach/test/AttachAddon.api.ts @@ -18,7 +18,7 @@ describe('AttachAddon', () => { before(async function(): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ - headless: process.argv.indexOf('--headless') !== -1 + headless: process.argv.includes('--headless') }); page = await (await browser.newContext()).newPage(); await page.setViewportSize({ width, height }); diff --git a/addons/xterm-addon-fit/package.json b/addons/xterm-addon-fit/package.json index 859d6ebf..f9d96c4a 100644 --- a/addons/xterm-addon-fit/package.json +++ b/addons/xterm-addon-fit/package.json @@ -1,6 +1,6 @@ { "name": "xterm-addon-fit", - "version": "0.4.0", + "version": "0.5.0", "author": { "name": "The xterm.js authors", "url": "https://xtermjs.org/" diff --git a/addons/xterm-addon-fit/test/FitAddon.api.ts b/addons/xterm-addon-fit/test/FitAddon.api.ts index 1111dff0..5a5b3264 100644 --- a/addons/xterm-addon-fit/test/FitAddon.api.ts +++ b/addons/xterm-addon-fit/test/FitAddon.api.ts @@ -18,7 +18,7 @@ describe('FitAddon', () => { before(async function(): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ - headless: process.argv.indexOf('--headless') !== -1 + headless: process.argv.includes('--headless') }); page = await (await browser.newContext()).newPage(); await page.setViewportSize({ width, height }); @@ -45,7 +45,7 @@ describe('FitAddon', () => { describe('proposeDimensions', () => { afterEach(async () => { - return unloadFit(); + return await unloadFit(); }); it('default', async function(): Promise { @@ -84,7 +84,7 @@ describe('FitAddon', () => { describe('fit', () => { afterEach(async () => { - return unloadFit(); + return await unloadFit(); }); it('default', async function(): Promise { diff --git a/addons/xterm-addon-ligatures/package.json b/addons/xterm-addon-ligatures/package.json index a35cfc5c..4e2b4056 100644 --- a/addons/xterm-addon-ligatures/package.json +++ b/addons/xterm-addon-ligatures/package.json @@ -1,6 +1,6 @@ { "name": "xterm-addon-ligatures", - "version": "0.3.0", + "version": "0.4.0", "description": "Add support for programming ligatures to xterm.js", "author": { "name": "The xterm.js authors", diff --git a/addons/xterm-addon-ligatures/src/parse.ts b/addons/xterm-addon-ligatures/src/parse.ts index 5ad7747f..6289e468 100644 --- a/addons/xterm-addon-ligatures/src/parse.ts +++ b/addons/xterm-addon-ligatures/src/parse.ts @@ -68,7 +68,7 @@ function parseString(context: IParseContext, quoteChar: '\'' | '"'): string { while (context.offset < context.input.length) { const char = context.input[context.offset++]; if (escaped) { - if (/[0-9a-fA-F]/.test(char)) { + if (/[\dA-Fa-f]/.test(char)) { // Unicode escape context.offset--; str += parseUnicode(context); @@ -107,7 +107,7 @@ function parseIdentifier(context: IParseContext): string { while (context.offset < context.input.length) { const char = context.input[context.offset++]; if (escaped) { - if (/[0-9a-fA-F]/.test(char)) { + if (/[\dA-Fa-f]/.test(char)) { // Unicode escape context.offset--; str += parseUnicode(context); @@ -156,7 +156,7 @@ function parseUnicode(context: IParseContext): string { // of the escape and is swallowed. return unicodeToString(str); } - if (str.length >= 6 || !/[0-9a-fA-F]/.test(char)) { + if (str.length >= 6 || !/[\dA-Fa-f]/.test(char)) { // If the next character is not a valid hex digit or we have reached the // maximum of 6 digits in the escape, terminate the escape. context.offset--; diff --git a/addons/xterm-addon-search/package.json b/addons/xterm-addon-search/package.json index 711335cb..659bd834 100644 --- a/addons/xterm-addon-search/package.json +++ b/addons/xterm-addon-search/package.json @@ -1,6 +1,6 @@ { "name": "xterm-addon-search", - "version": "0.7.0", + "version": "0.8.0", "author": { "name": "The xterm.js authors", "url": "https://xtermjs.org/" diff --git a/addons/xterm-addon-search/src/SearchAddon.ts b/addons/xterm-addon-search/src/SearchAddon.ts index efc12662..64e89bb3 100644 --- a/addons/xterm-addon-search/src/SearchAddon.ts +++ b/addons/xterm-addon-search/src/SearchAddon.ts @@ -240,8 +240,8 @@ export class SearchAddon implements ITerminalAddon { * @param term the substring that starts at searchIndex */ private _isWholeWord(searchIndex: number, line: string, term: string): boolean { - return (((searchIndex === 0) || (NON_WORD_CHARACTERS.indexOf(line[searchIndex - 1]) !== -1)) && - (((searchIndex + term.length) === line.length) || (NON_WORD_CHARACTERS.indexOf(line[searchIndex + term.length]) !== -1))); + return ((searchIndex === 0) || (NON_WORD_CHARACTERS.includes(line[searchIndex - 1]))) && + (((searchIndex + term.length) === line.length) || (NON_WORD_CHARACTERS.includes(line[searchIndex + term.length]))); } /** @@ -262,7 +262,7 @@ export class SearchAddon implements ITerminalAddon { // Ignore wrapped lines, only consider on unwrapped line (first row of command string). const firstLine = terminal.buffer.active.getLine(row); - if (firstLine && firstLine.isWrapped) { + if (firstLine?.isWrapped) { if (isReverseSearch) { searchPosition.startCol += terminal.cols; return; diff --git a/addons/xterm-addon-search/test/SearchAddon.api.ts b/addons/xterm-addon-search/test/SearchAddon.api.ts index 3707aecd..b92dbc3a 100644 --- a/addons/xterm-addon-search/test/SearchAddon.api.ts +++ b/addons/xterm-addon-search/test/SearchAddon.api.ts @@ -20,7 +20,7 @@ describe('Search Tests', function(): void { before(async function(): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ - headless: process.argv.indexOf('--headless') !== -1 + headless: process.argv.includes('--headless') }); page = await (await browser.newContext()).newPage(); await page.setViewportSize({ width, height }); diff --git a/addons/xterm-addon-serialize/package.json b/addons/xterm-addon-serialize/package.json index bb799aec..770771c4 100644 --- a/addons/xterm-addon-serialize/package.json +++ b/addons/xterm-addon-serialize/package.json @@ -1,6 +1,6 @@ { "name": "xterm-addon-serialize", - "version": "0.4.0", + "version": "0.5.0", "author": { "name": "The xterm.js authors", "url": "https://xtermjs.org/" diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index dad6aa4f..0caaaa03 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -21,7 +21,7 @@ abstract class BaseSerializeHandler { const cell2 = this._buffer.getNullCell(); let oldCell = cell1; - this._beforeSerialize(endRow - startRow); + this._beforeSerialize(endRow - startRow, startRow, endRow); for (let row = startRow; row < endRow; row++) { const line = this._buffer.getLine(row); @@ -36,7 +36,7 @@ abstract class BaseSerializeHandler { oldCell = c; } } - this._rowEnd(row); + this._rowEnd(row, row === endRow - 1); } this._afterSerialize(); @@ -45,8 +45,8 @@ abstract class BaseSerializeHandler { } protected _nextCell(cell: IBufferCell, oldCell: IBufferCell, row: number, col: number): void { } - protected _rowEnd(row: number): void { } - protected _beforeSerialize(rows: number): void { } + protected _rowEnd(row: number, isLastRow: boolean): void { } + protected _beforeSerialize(rows: number, startRow: number, endRow: number): void { } protected _afterSerialize(): void { } protected _serializeString(): string { return ''; } } @@ -71,27 +71,152 @@ function equalFlags(cell1: IBufferCell, cell2: IBufferCell): boolean { && cell1.isDim() === cell2.isDim(); } + + class StringSerializeHandler extends BaseSerializeHandler { private _rowIndex: number = 0; private _allRows: string[] = new Array(); + private _allRowSeparators: string[] = new Array(); private _currentRow: string = ''; private _nullCellCount: number = 0; - constructor(buffer: IBuffer) { - super(buffer); + // we can see a full colored cell and a null cell that only have background the same style + // but the information isn't preserved by null cell itself + // so wee need to record it when required. + private _cursorStyle: IBufferCell = this._buffer1.getNullCell(); + + // where exact the cursor styles comes from + // because we can't copy the cell directly + // so we remember where the content comes from instead + private _cursorStyleRow: number = 0; + private _cursorStyleCol: number = 0; + + // this is a null cell for reference for checking whether background is empty or not + private _backgroundCell: IBufferCell = this._buffer1.getNullCell(); + + private _firstRow: number = 0; + private _lastCursorRow: number = 0; + private _lastCursorCol: number = 0; + private _lastContentCursorRow: number = 0; + private _lastContentCursorCol: number = 0; + + constructor(private _buffer1: IBuffer, private _terminal: Terminal) { + super(_buffer1); } - protected _beforeSerialize(rows: number): void { + protected _beforeSerialize(rows: number, start: number, end: number): void { this._allRows = new Array(rows); + this._lastContentCursorRow = start; + this._lastCursorRow = start; + this._firstRow = start; } - protected _rowEnd(row: number): void { - this._allRows[this._rowIndex++] = this._currentRow; + private _thisRowLastChar: IBufferCell = this._buffer1.getNullCell(); + private _thisRowLastSecondChar: IBufferCell = this._buffer1.getNullCell(); + private _nextRowFirstChar: IBufferCell = this._buffer1.getNullCell(); + protected _rowEnd(row: number, isLastRow: boolean): void { + // if there is colorful empty cell at line end, whe must pad it back, or the the color block will missing + if (this._nullCellCount > 0 && !equalBg(this._cursorStyle, this._backgroundCell)) { + // use clear right to set background. + this._currentRow += `\x1b[${this._nullCellCount}X`; + } + + let rowSeparator = ''; + + // handle row separator + if (!isLastRow) { + // Enable BCE + if (row - this._firstRow >= this._terminal.rows) { + this._buffer1.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol, this._backgroundCell); + } + + // Fetch current line + const currentLine = this._buffer1.getLine(row)!; + // Fetch next line + const nextLine = this._buffer1.getLine(row + 1)!; + + if (!nextLine.isWrapped) { + // just insert the line break + rowSeparator = '\r\n'; + // we sended the enter + this._lastCursorRow = row + 1; + this._lastCursorCol = 0; + } else { + rowSeparator = ''; + const thisRowLastChar = currentLine.getCell(currentLine.length - 1, this._thisRowLastChar)!; + const thisRowLastSecondChar = currentLine.getCell(currentLine.length - 2, this._thisRowLastSecondChar)!; + const nextRowFirstChar = nextLine.getCell(0, this._nextRowFirstChar)!; + const isNextRowFirstCharDoubleWidth = nextRowFirstChar.getWidth() > 1; + + // validate whether this line wrap is ever possible + // which mean whether cursor can placed at a overflow position (x === row) naturally + let isValid = false; + + if ( + // you must output character to cause overflow, control sequence can't do this + nextRowFirstChar.getChars() && + isNextRowFirstCharDoubleWidth ? this._nullCellCount <= 1 : this._nullCellCount <= 0 + ) { + if ( + // the last character can't be null, + // you can't use control sequence to move cursor to (x === row) + (thisRowLastChar.getChars() || thisRowLastChar.getWidth() === 0) && + // change background of the first wrapped cell also affects BCE + // so we mark it as invalid to simply the process to determine line separator + equalBg(thisRowLastChar, nextRowFirstChar) + ) { + isValid = true; + } + + if ( + // the second to last character can't be null if the next line starts with CJK, + // you can't use control sequence to move cursor to (x === row) + isNextRowFirstCharDoubleWidth && + (thisRowLastSecondChar.getChars() || thisRowLastSecondChar.getWidth() === 0) && + // change background of the first wrapped cell also affects BCE + // so we mark it as invalid to simply the process to determine line separator + equalBg(thisRowLastChar, nextRowFirstChar) && + equalBg(thisRowLastSecondChar, nextRowFirstChar) + ) { + isValid = true; + } + } + + if (!isValid) { + // force the wrap with magic + // insert enough character to force the wrap + rowSeparator = '-'.repeat(this._nullCellCount + 1); + // move back and erase next line head + rowSeparator += '\x1b[1D\x1b[1X'; + + if (this._nullCellCount > 0) { + // do these because we filled the last several null slot, which we shouldn't + rowSeparator += '\x1b[A'; + rowSeparator += `\x1b[${currentLine.length - this._nullCellCount}C`; + rowSeparator += `\x1b[${this._nullCellCount}X`; + rowSeparator += `\x1b[${currentLine.length - this._nullCellCount}D`; + rowSeparator += '\x1b[B'; + } + + // This is content and need the be serialized even it is invisible. + // without this, wrap will be missing from outputs. + this._lastContentCursorRow = row + 1; + this._lastContentCursorCol = 0; + + // force commit the cursor position + this._lastCursorRow = row + 1; + this._lastCursorCol = 0; + } + } + } + + this._allRows[this._rowIndex] = this._currentRow; + this._allRowSeparators[this._rowIndex++] = rowSeparator; this._currentRow = ''; this._nullCellCount = 0; } - protected _nextCell(cell: IBufferCell, oldCell: IBufferCell, row: number, col: number): void { + private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): number[] { const sgrSeq: number[] = []; const fgChanged = !equalFg(cell, oldCell); const bgChanged = !equalBg(cell, oldCell); @@ -99,7 +224,9 @@ class StringSerializeHandler extends BaseSerializeHandler { if (fgChanged || bgChanged || flagsChanged) { if (cell.isAttributeDefault()) { - this._currentRow += '\x1b[0m'; + if (!oldCell.isAttributeDefault()) { + sgrSeq.push(0); + } } else { if (fgChanged) { const color = cell.getFgColor(); @@ -131,30 +258,129 @@ class StringSerializeHandler extends BaseSerializeHandler { } } - if (sgrSeq.length) { + return sgrSeq; + } + + protected _nextCell(cell: IBufferCell, oldCell: IBufferCell, row: number, col: number): void { + // a width 0 cell don't need to be count because it is just a placeholder after a CJK character; + const isPlaceHolderCell = cell.getWidth() === 0; + + if (isPlaceHolderCell) { + return; + } + + // this cell don't have content + const isEmptyCell = cell.getChars() === ''; + + const sgrSeq = this._diffStyle(cell, this._cursorStyle); + + // the empty cell style is only assumed to be changed when background changed, because foreground is always 0. + const styleChanged = isEmptyCell ? !equalBg(this._cursorStyle, cell) : sgrSeq.length > 0; + + /** + * handles style change + */ + if (styleChanged) { + // before update the style, we need to fill empty cell back + if (this._nullCellCount > 0) { + // use clear right to set background. + if (!equalBg(this._cursorStyle, this._backgroundCell)) { + this._currentRow += `\x1b[${this._nullCellCount}X`; + } + // use move right to move cursor. + this._currentRow += `\x1b[${this._nullCellCount}C`; + this._nullCellCount = 0; + } + + this._lastContentCursorRow = this._lastCursorRow = row; + this._lastContentCursorCol = this._lastCursorCol = col; + this._currentRow += `\x1b[${sgrSeq.join(';')}m`; + + // update the last cursor style + const line = this._buffer1.getLine(row); + if (line !== undefined) { + line.getCell(col, this._cursorStyle); + this._cursorStyleRow = row; + this._cursorStyleCol = col; + } } - // Count number of null cells encountered after the last non-null cell and move the cursor - // if a non-null cell is found (eg. \t or cursor move) - if (cell.getChars() === '') { + /** + * handles actual content + */ + if (isEmptyCell) { this._nullCellCount += cell.getWidth(); - } else if (this._nullCellCount > 0) { - this._currentRow += `\x1b[${this._nullCellCount}C`; - this._nullCellCount = 0; - } + } else { + if (this._nullCellCount > 0) { + // we can just assume we have same style with previous one here + // because style change is handled by previous stage + // use move right when background is empty, use clear right when there is background. + if (equalBg(this._cursorStyle, this._backgroundCell)) { + this._currentRow += `\x1b[${this._nullCellCount}C`; + } else { + this._currentRow += `\x1b[${this._nullCellCount}X`; + this._currentRow += `\x1b[${this._nullCellCount}C`; + } + this._nullCellCount = 0; + } - this._currentRow += cell.getChars(); + this._currentRow += cell.getChars(); + + // update cursor + this._lastContentCursorRow = this._lastCursorRow = row; + this._lastContentCursorCol = this._lastCursorCol = col + cell.getWidth(); + } } protected _serializeString(): string { let rowEnd = this._allRows.length; - for (; rowEnd > 0; rowEnd--) { - if (this._allRows[rowEnd - 1]) { - break; + + // the fixup is only required for data without scrollback + // because it will always be placed at last line otherwise + if (this._buffer1.length - this._firstRow <= this._terminal.rows) { + rowEnd = this._lastContentCursorRow + 1 - this._firstRow; + this._lastCursorCol = this._lastContentCursorCol; + this._lastCursorRow = this._lastContentCursorRow; + } + + let content = ''; + + for (let i = 0; i < rowEnd; i++) { + content += this._allRows[i]; + if (i + 1 < rowEnd) { + content += this._allRowSeparators[i]; } } - return this._allRows.slice(0, rowEnd).join('\r\n'); + + // restore the cursor + const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY; + const realCursorCol = this._buffer1.cursorX; + + const cursorMoved = (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol); + + const moveRight = (offset: number): void => { + if (offset > 0) { + content += `\u001b[${offset}C`; + } else if (offset < 0) { + content += `\u001b[${-offset}D`; + } + }; + const moveDown = (offset: number): void => { + if (offset > 0) { + content += `\u001b[${offset}B`; + } else if (offset < 0) { + content += `\u001b[${-offset}A`; + } + }; + + if (cursorMoved) { + moveDown(realCursorRow - this._lastCursorRow); + moveRight(realCursorCol - this._lastCursorCol); + } + + + return content; } } @@ -167,20 +393,33 @@ export class SerializeAddon implements ITerminalAddon { this._terminal = terminal; } - public serialize(rows?: number): string { - // TODO: Add re-position cursor support - // TODO: Add word wrap mode support + private _getString(buffer: IBuffer, scrollback?: number): string { + const maxRows = buffer.length; + const handler = new StringSerializeHandler(buffer, this._terminal!); + + const correctRows = (scrollback === undefined) ? maxRows : constrain(scrollback + this!._terminal!.rows, 0, maxRows); + const result = handler.serialize(maxRows - correctRows, maxRows); + + return result; + } + + public serialize(scrollback?: number): string { // TODO: Add combinedData support if (!this._terminal) { throw new Error('Cannot use addon until it has been loaded'); } - const maxRows = this._terminal.buffer.active.length; - const handler = new StringSerializeHandler(this._terminal.buffer.active); + if (this._terminal.buffer.active.type === 'normal') { + return this._getString(this._terminal.buffer.active, scrollback); + } - rows = (rows === undefined) ? maxRows : constrain(rows, 0, maxRows); + const normalScreenContent = this._getString(this._terminal.buffer.normal, scrollback); + // alt screen don't have scrollback + const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, undefined); - return handler.serialize(maxRows - rows, maxRows); + return normalScreenContent + + '\u001b[?1049h\u001b[H' + + alternativeScreenContent; } public dispose(): void { } diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 5b615db1..d472d753 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -14,11 +14,27 @@ let page: Page; const width = 800; const height = 600; +const writeRawSync = (page: any, str: string): Promise => writeSync(page, '\' +' + JSON.stringify(str) + '+ \''); + +const testNormalScreenEqual = async (page: any, str: string): Promise => { + await writeRawSync(page, str); + const originalBuffer = await page.evaluate(`inspectBuffer(term.buffer.normal);`); + + const result = await page.evaluate(`serializeAddon.serialize();`) as string; + await page.evaluate(`term.reset();`); + await writeRawSync(page, result); + const newBuffer = await page.evaluate(`inspectBuffer(term.buffer.normal);`); + + // chai decides -0 and 0 are different number... + // and firefox have a bug that output -0 for unknown reason + assert.equal(JSON.stringify(originalBuffer), JSON.stringify(newBuffer)); +}; + describe('SerializeAddon', () => { before(async function(): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ - headless: process.argv.indexOf('--headless') !== -1 + headless: process.argv.includes('--headless') }); page = await (await browser.newContext()).newPage(); await page.setViewportSize({ width, height }); @@ -27,19 +43,74 @@ describe('SerializeAddon', () => { await page.evaluate(` window.serializeAddon = new SerializeAddon(); window.term.loadAddon(window.serializeAddon); + window.inspectBuffer = (buffer) => { + const lines = []; + for (let i = 0; i < buffer.length; i++) { + // Do this intentionally to get content of underlining source + const bufferLine = buffer.getLine(i)._line; + lines.push(JSON.stringify(bufferLine)); + } + return { + x: buffer.cursorX, + y: buffer.cursorY, + data: lines + }; + } `); }); after(async () => await browser.close()); beforeEach(async () => await page.evaluate(`window.term.reset()`)); + it('produce different output when we call test util with different text', async function(): Promise { + await writeRawSync(page, '12345'); + const buffer1 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); + + await page.evaluate(`term.reset();`); + await writeRawSync(page, '67890'); + const buffer2 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); + + assert.throw(() => { + assert.equal(JSON.stringify(buffer1), JSON.stringify(buffer2)); + }); + }); + + it('produce different output when we call test util with different line wrap', async function(): Promise { + await writeRawSync(page, '1234567890\r\n12345'); + const buffer3 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); + + await page.evaluate(`term.reset();`); + await writeRawSync(page, '1234567890n12345'); + const buffer4 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); + + assert.throw(() => { + assert.equal(JSON.stringify(buffer3), JSON.stringify(buffer4)); + }); + }); + it('empty content', async function(): Promise { const rows = 10; const cols = 10; assert.equal(await page.evaluate(`serializeAddon.serialize();`), ''); }); - it('trim last empty lines', async function(): Promise { + it('unwrap wrapped line', async function(): Promise { + const lines = ['123456789123456789']; + await writeSync(page, lines.join('\\r\\n')); + assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n')); + }); + + it('does not unwrap non-wrapped line', async function(): Promise { + const lines = [ + '123456789', + '123456789' + ]; + await writeSync(page, lines.join('\\r\\n')); + assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n')); + }); + + + it('preserve last empty lines', async function(): Promise { const cols = 10; const lines = [ '', @@ -55,7 +126,7 @@ describe('SerializeAddon', () => { '' ]; await writeSync(page, lines.join('\\r\\n')); - assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.slice(0, 8).join('\r\n')); + assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n')); }); it('digits content', async function(): Promise { @@ -67,21 +138,22 @@ describe('SerializeAddon', () => { assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n')); }); - it('serialize half rows of content', async function(): Promise { - const rows = 10; - const halfRows = rows >> 1; + it('serialize with half of scrollback', async function(): Promise { + const rows = 20; + const scrollback = rows - 10; + const halfScrollback = scrollback / 2; const cols = 10; const lines = newArray((index: number) => digitsString(cols, index), rows); await writeSync(page, lines.join('\\r\\n')); - assert.equal(await page.evaluate(`serializeAddon.serialize(${halfRows});`), lines.slice(halfRows, 2 * halfRows).join('\r\n')); + assert.equal(await page.evaluate(`serializeAddon.serialize(${halfScrollback});`), lines.slice(halfScrollback, rows).join('\r\n')); }); - it('serialize 0 rows of content', async function(): Promise { - const rows = 10; + it('serialize 0 rows of scrollback', async function(): Promise { + const rows = 20; const cols = 10; const lines = newArray((index: number) => digitsString(cols, index), rows); await writeSync(page, lines.join('\\r\\n')); - assert.equal(await page.evaluate(`serializeAddon.serialize(0);`), ''); + assert.equal(await page.evaluate(`serializeAddon.serialize(0);`), lines.slice(rows - 10, rows).join('\r\n')); }); it('serialize all rows of content with color16', async function(): Promise { @@ -276,17 +348,15 @@ describe('SerializeAddon', () => { '中文中文', '12中文', '中文12', - '1中文中文中' // this line is going to be wrapped at last character because it has line length of 11 (1+2*5) - ]; - const expected = [ - '中文中文', - '12中文', - '中文12', - '1中文中文', - '中' + // This line is going to be wrapped at last character + // because it has line length of 11 (1+2*5). + // We concat it back without the null cell currently. + // But this may be incorrect. + // see also #3097 + '1中文中文中' ]; await writeSync(page, lines.join('\\r\\n')); - assert.equal(await page.evaluate(`serializeAddon.serialize();`), expected.join('\r\n')); + assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n')); }); it('serialize CJK Mixed with tab correctly', async () => { @@ -299,6 +369,118 @@ describe('SerializeAddon', () => { await writeSync(page, lines.join('\\r\\n')); assert.equal(await page.evaluate(`serializeAddon.serialize();`), expected.join('\r\n')); }); + + it('serialize with alt screen correctly', async () => { + const SMCUP = '\u001b[?1049h'; + const CUP = '\u001b[H'; + + const lines = [ + `1${SMCUP}${CUP}2` + ]; + const expected = [ + `1${SMCUP}${CUP}2` + ]; + + await writeSync(page, lines.join('\\r\\n')); + assert.equal(await page.evaluate(`window.term.buffer.active.type`), 'alternate'); + assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize();`)), JSON.stringify(expected.join('\r\n'))); + }); + + it('serialize without alt screen correctly', async () => { + const SMCUP = '\u001b[?1049h'; + const RMCUP = '\u001b[?1049l'; + + const lines = [ + `1${SMCUP}2${RMCUP}` + ]; + const expected = [ + `1` + ]; + + await writeSync(page, lines.join('\\r\\n')); + assert.equal(await page.evaluate(`window.term.buffer.active.type`), 'normal'); + assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize();`)), JSON.stringify(expected.join('\r\n'))); + }); + + it('serialize with background', async () => { + const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`; + + const lines = [ + `1\u001b[44m${CLEAR_RIGHT(5)}`, + `2${CLEAR_RIGHT(9)}` + ]; + + await testNormalScreenEqual(page, lines.join('\r\n')); + }); + + it('cause the BCE on scroll', async () => { + const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`; + + const padLines = newArray( + (index: number) => digitsString(10, index), + 10 + ); + + const lines = [ + ...padLines, + `\u001b[44m${CLEAR_RIGHT(5)}1111111111111111` + ]; + + await testNormalScreenEqual(page, lines.join('\r\n')); + }); + + it('handle invalid wrap before scroll', async () => { + const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`; + const MOVE_UP = (l: number): string => `\u001b[${l}A`; + const MOVE_DOWN = (l: number): string => `\u001b[${l}B`; + const MOVE_LEFT = (l: number): string => `\u001b[${l}D`; + + // A line wrap happened after current line. + // But there is no content. + // so wrap shouldn't even be able to happen. + const segments = [ + `123456789012345`, + MOVE_UP(1), + CLEAR_RIGHT(5), + MOVE_DOWN(1), + MOVE_LEFT(5), + CLEAR_RIGHT(5), + MOVE_UP(1), + '1' + ]; + + await testNormalScreenEqual(page, segments.join('')); + }); + + it('handle invalid wrap after scroll', async () => { + const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`; + const MOVE_UP = (l: number): string => `\u001b[${l}A`; + const MOVE_DOWN = (l: number): string => `\u001b[${l}B`; + const MOVE_LEFT = (l: number): string => `\u001b[${l}D`; + + const padLines = newArray( + (index: number) => digitsString(10, index), + 10 + ); + + // A line wrap happened after current line. + // But there is no content. + // so wrap shouldn't even be able to happen. + const lines = [ + padLines.join('\r\n'), + '\r\n', + `123456789012345`, + MOVE_UP(1), + CLEAR_RIGHT(5), + MOVE_DOWN(1), + MOVE_LEFT(5), + CLEAR_RIGHT(5), + MOVE_UP(1), + '1' + ]; + + await testNormalScreenEqual(page, lines.join('')); + }); }); function newArray(initial: T | ((index: number) => T), count: number): T[] { diff --git a/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts b/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts index 9e7b500a..58be9a97 100644 --- a/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts +++ b/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts @@ -25,10 +25,10 @@ declare module 'xterm-addon-serialize' { * to restore the state. The cursor will also be positioned to the correct cell. * When restoring a terminal it is best to do before `Terminal.open` is called * to avoid wasting CPU cycles rendering incomplete frames. - * @param rows The number of rows to serialize, starting from the bottom of the - * terminal. This defaults to the number of rows in the viewport. + * @param scrollback The number of rows in scrollback buffer to serialize, starting from the bottom of the + * scrollback buffer. This defaults to the all available rows in the scrollback buffer. */ - public serialize(rows?: number): string; + public serialize(scrollback?: number): string; /** * Disposes the addon. diff --git a/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts b/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts index d0e09da2..7369eeaa 100644 --- a/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts +++ b/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts @@ -18,7 +18,7 @@ describe('Unicode11Addon', () => { before(async function(): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ - headless: process.argv.indexOf('--headless') !== -1 + headless: process.argv.includes('--headless') }); page = await (await browser.newContext()).newPage(); await page.setViewportSize({ width, height }); diff --git a/addons/xterm-addon-web-links/src/WebLinkProvider.ts b/addons/xterm-addon-web-links/src/WebLinkProvider.ts index af6ad7d3..f0caf974 100644 --- a/addons/xterm-addon-web-links/src/WebLinkProvider.ts +++ b/addons/xterm-addon-web-links/src/WebLinkProvider.ts @@ -3,25 +3,45 @@ * @license MIT */ -import { ILinkProvider, IBufferCellPosition, ILink, Terminal } from 'xterm'; +import { ILinkProvider, ILink, Terminal, IViewportRange } from 'xterm'; + +interface ILinkProviderOptions { + hover?(event: MouseEvent, text: string, location: IViewportRange): void; + leave?(event: MouseEvent, text: string): void; +} export class WebLinkProvider implements ILinkProvider { constructor( private readonly _terminal: Terminal, private readonly _regex: RegExp, - private readonly _handler: (event: MouseEvent, uri: string) => void + private readonly _handler: (event: MouseEvent, uri: string) => void, + private readonly _options: ILinkProviderOptions = {} ) { } public provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void { - callback(LinkComputer.computeLink(y, this._regex, this._terminal, this._handler)); + const links = LinkComputer.computeLink(y, this._regex, this._terminal, this._handler); + callback(this._addCallbacks(links)); + } + + private _addCallbacks(links: ILink[]): ILink[] { + return links.map(link => { + link.leave = this._options.leave; + link.hover = (event: MouseEvent, uri: string): void => { + if (this._options.hover) { + const { range } = link; + this._options.hover(event, uri, range); + } + }; + return link; + }); } } export class LinkComputer { - public static computeLink(y: number, regex: RegExp, terminal: Terminal, handler: (event: MouseEvent, uri: string) => void): ILink[] { + public static computeLink(y: number, regex: RegExp, terminal: Terminal, activate: (event: MouseEvent, uri: string) => void): ILink[] { const rex = new RegExp(regex.source, (regex.flags || '') + 'g'); const [line, startLineIndex] = LinkComputer._translateBufferLineToStringWithWrap(y - 1, false, terminal); @@ -69,7 +89,7 @@ export class LinkComputer { } }; - result.push({ range, text, activate: handler }); + result.push({ range, text, activate }); } return result; diff --git a/addons/xterm-addon-web-links/src/WebLinksAddon.ts b/addons/xterm-addon-web-links/src/WebLinksAddon.ts index dce405a5..46ddcf7b 100644 --- a/addons/xterm-addon-web-links/src/WebLinksAddon.ts +++ b/addons/xterm-addon-web-links/src/WebLinksAddon.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { Terminal, ILinkMatcherOptions, ITerminalAddon, IDisposable } from 'xterm'; +import { Terminal, ILinkMatcherOptions, ITerminalAddon, IDisposable, IViewportRange } from 'xterm'; import { WebLinkProvider } from './WebLinkProvider'; const protocolClause = '(https?:\\/\\/)'; @@ -36,6 +36,11 @@ function handleLink(event: MouseEvent, uri: string): void { } } +interface ILinkProviderOptions { + hover?(event: MouseEvent, text: string, location: IViewportRange): void; + leave?(event: MouseEvent, text: string): void; +} + export class WebLinksAddon implements ITerminalAddon { private _linkMatcherId: number | undefined; private _terminal: Terminal | undefined; @@ -43,20 +48,22 @@ export class WebLinksAddon implements ITerminalAddon { constructor( private _handler: (event: MouseEvent, uri: string) => void = handleLink, - private _options: ILinkMatcherOptions = {}, + private _options: ILinkMatcherOptions | ILinkProviderOptions = {}, private _useLinkProvider: boolean = false ) { - this._options.matchIndex = 1; } public activate(terminal: Terminal): void { this._terminal = terminal; if (this._useLinkProvider && 'registerLinkProvider' in this._terminal) { - this._linkProvider = this._terminal.registerLinkProvider(new WebLinkProvider(this._terminal, strictUrlRegex, this._handler)); + const options = this._options as ILinkProviderOptions; + this._linkProvider = this._terminal.registerLinkProvider(new WebLinkProvider(this._terminal, strictUrlRegex, this._handler, options)); } else { // TODO: This should be removed eventually - this._linkMatcherId = (this._terminal as Terminal).registerLinkMatcher(strictUrlRegex, this._handler, this._options); + const options = this._options as ILinkMatcherOptions; + options.matchIndex = 1; + this._linkMatcherId = (this._terminal as Terminal).registerLinkMatcher(strictUrlRegex, this._handler, options); } } diff --git a/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts b/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts index 6e42ff96..47fd7911 100644 --- a/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts +++ b/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts @@ -18,7 +18,7 @@ describe('WebLinksAddon', () => { before(async function(): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ - headless: process.argv.indexOf('--headless') !== -1 + headless: process.argv.includes('--headless') }); page = await (await browser.newContext()).newPage(); await page.setViewportSize({ width, height }); diff --git a/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts b/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts index f0564704..78a258e5 100644 --- a/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts +++ b/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts @@ -4,7 +4,7 @@ */ -import { Terminal, ILinkMatcherOptions, ITerminalAddon } from 'xterm'; +import { Terminal, ILinkMatcherOptions, ITerminalAddon, IViewportRange } from 'xterm'; declare module 'xterm-addon-web-links' { /** @@ -20,7 +20,7 @@ declare module 'xterm-addon-web-links' { * link provider (new) may cause issues. Link provider will eventually be * the default and only option. */ - constructor(handler?: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions, useLinkProvider?: boolean); + constructor(handler?: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions | ILinkProviderOptions, useLinkProvider?: boolean); /** * Activates the addon @@ -33,4 +33,21 @@ declare module 'xterm-addon-web-links' { */ public dispose(): void; } + + /** + * An object containing options for a link provider. + */ + export interface ILinkProviderOptions { + /** + * A callback that fires when the mouse hovers over a link for a period of + * time (defined by {@link ITerminalOptions.linkTooltipHoverDuration}). + */ + hover?(event: MouseEvent, text: string, location: IViewportRange): 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. + */ + leave?(event: MouseEvent, text: string): void; + } } diff --git a/addons/xterm-addon-webgl/README.md b/addons/xterm-addon-webgl/README.md index 026a738e..756999db 100644 --- a/addons/xterm-addon-webgl/README.md +++ b/addons/xterm-addon-webgl/README.md @@ -1,8 +1,6 @@ ## xterm-addon-webgl -An addon for [xterm.js](https://github.com/xtermjs/xterm.js) that enables a WebGL-based renderer. This addon requires xterm.js v4+. - -⚠️ This is an experimental addon that is [missing some features and may be unstable](https://github.com/xtermjs/xterm.js/issues?q=is%3Aopen+is%3Aissue+label%3Aarea%2Faddon%2Fwebgl) ⚠️ +An addon for [xterm.js](https://github.com/xtermjs/xterm.js) that enables a WebGL2-based renderer. This addon requires xterm.js v4+. ### Install diff --git a/addons/xterm-addon-webgl/package.json b/addons/xterm-addon-webgl/package.json index c0e91b37..28c6f5bc 100644 --- a/addons/xterm-addon-webgl/package.json +++ b/addons/xterm-addon-webgl/package.json @@ -1,6 +1,6 @@ { "name": "xterm-addon-webgl", - "version": "0.9.0", + "version": "0.10.0", "author": { "name": "The xterm.js authors", "url": "https://xtermjs.org/" diff --git a/addons/xterm-addon-webgl/src/WebglRenderer.ts b/addons/xterm-addon-webgl/src/WebglRenderer.ts index 9f982165..fecd5742 100644 --- a/addons/xterm-addon-webgl/src/WebglRenderer.ts +++ b/addons/xterm-addon-webgl/src/WebglRenderer.ts @@ -94,7 +94,9 @@ export class WebglRenderer extends Disposable implements IRenderer { } public dispose(): void { - this._renderLayers.forEach(l => l.dispose()); + for (const l of this._renderLayers) { + l.dispose(); + } this._core.screenElement!.removeChild(this._canvas); super.dispose(); } @@ -106,22 +108,18 @@ export class WebglRenderer extends Disposable implements IRenderer { public setColors(colors: IColorSet): void { this._colors = colors; // Clear layers and force a full render - this._renderLayers.forEach(l => { + for (const l of this._renderLayers) { l.setColors(this._terminal, this._colors); l.reset(this._terminal); - }); + } this._rectangleRenderer.setColors(); this._glyphRenderer.setColors(); this._refreshCharAtlas(); - this._rectangleRenderer.updateSelection(this._model.selection); - this._glyphRenderer.updateSelection(this._model); - // Force a full refresh this._model.clear(); - this._model.clearSelection(); } public onDevicePixelRatioChange(): void { @@ -138,10 +136,11 @@ export class WebglRenderer extends Disposable implements IRenderer { this._updateDimensions(); this._model.resize(this._terminal.cols, this._terminal.rows); - this._rectangleRenderer.onResize(); // Resize all render layers - this._renderLayers.forEach(l => l.resize(this._terminal, this.dimensions)); + for (const l of this._renderLayers) { + l.resize(this._terminal, this.dimensions); + } // Resize the canvas this._canvas.width = this.dimensions.scaledCanvasWidth; @@ -152,6 +151,13 @@ export class WebglRenderer extends Disposable implements IRenderer { // Resize the screen this._core.screenElement!.style.width = `${this.dimensions.canvasWidth}px`; this._core.screenElement!.style.height = `${this.dimensions.canvasHeight}px`; + + this._rectangleRenderer.onResize(); + if (this._model.selection.hasSelection) { + // Update selection as dimensions have changed + this._rectangleRenderer.updateSelection(this._model.selection); + } + this._glyphRenderer.setDimensions(this.dimensions); this._glyphRenderer.onResize(); @@ -159,7 +165,6 @@ export class WebglRenderer extends Disposable implements IRenderer { // Force a full refresh this._model.clear(); - this._model.clearSelection(); } public onCharSizeChanged(): void { @@ -167,30 +172,37 @@ export class WebglRenderer extends Disposable implements IRenderer { } public onBlur(): void { - this._renderLayers.forEach(l => l.onBlur(this._terminal)); + for (const l of this._renderLayers) { + l.onBlur(this._terminal); + } } public onFocus(): void { - this._renderLayers.forEach(l => l.onFocus(this._terminal)); + for (const l of this._renderLayers) { + l.onFocus(this._terminal); + } } public onSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void { - this._renderLayers.forEach(l => l.onSelectionChanged(this._terminal, start, end, columnSelectMode)); + for (const l of this._renderLayers) { + l.onSelectionChanged(this._terminal, start, end, columnSelectMode); + } this._updateSelectionModel(start, end, columnSelectMode); - this._rectangleRenderer.updateSelection(this._model.selection); - this._glyphRenderer.updateSelection(this._model); - this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1 }); } public onCursorMove(): void { - this._renderLayers.forEach(l => l.onCursorMove(this._terminal)); + for (const l of this._renderLayers) { + l.onCursorMove(this._terminal); + } } public onOptionsChanged(): void { - this._renderLayers.forEach(l => l.onOptionsChanged(this._terminal)); + for (const l of this._renderLayers) { + l.onOptionsChanged(this._terminal); + } this._updateDimensions(); this._refreshCharAtlas(); } @@ -220,12 +232,13 @@ export class WebglRenderer extends Disposable implements IRenderer { this._charAtlas?.clearTexture(); this._model.clear(); this._updateModel(0, this._terminal.rows - 1); - this._glyphRenderer.updateSelection(this._model); this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1 }); } public clear(): void { - this._renderLayers.forEach(l => l.reset(this._terminal)); + for (const l of this._renderLayers) { + l.reset(this._terminal); + } } public registerCharacterJoiner(handler: (text: string) => [number, number][]): number { @@ -248,12 +261,14 @@ export class WebglRenderer extends Disposable implements IRenderer { } // Update render layers - this._renderLayers.forEach(l => l.onGridChanged(this._terminal, start, end)); + for (const l of this._renderLayers) { + l.onGridChanged(this._terminal, start, end); + } // Tell renderer the frame is beginning if (this._glyphRenderer.beginFrame()) { this._model.clear(); - this._model.clearSelection(); + this._updateSelectionModel(undefined, undefined); } // Update model to reflect what's drawn @@ -303,14 +318,19 @@ export class WebglRenderer extends Disposable implements IRenderer { } } this._rectangleRenderer.updateBackgrounds(this._model); + if (this._model.selection.hasSelection) { + // Model could be updated but the selection is unchanged + this._glyphRenderer.updateSelection(this._model); + } } - private _updateSelectionModel(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void { + private _updateSelectionModel(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean = false): void { const terminal = this._terminal; // Selection does not exist if (!start || !end || (start[0] === end[0] && start[1] === end[1])) { this._model.clearSelection(); + this._rectangleRenderer.updateSelection(this._model.selection); return; } @@ -323,6 +343,7 @@ export class WebglRenderer extends Disposable implements IRenderer { // No need to draw the selection if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) { this._model.clearSelection(); + this._rectangleRenderer.updateSelection(this._model.selection); return; } @@ -334,6 +355,8 @@ export class WebglRenderer extends Disposable implements IRenderer { this._model.selection.viewportCappedEndRow = viewportCappedEndRow; this._model.selection.startCol = start[0]; this._model.selection.endCol = end[0]; + + this._rectangleRenderer.updateSelection(this._model.selection); } /** diff --git a/addons/xterm-addon-webgl/test/WebglRenderer.api.ts b/addons/xterm-addon-webgl/test/WebglRenderer.api.ts index 558605e2..e0aa68e7 100644 --- a/addons/xterm-addon-webgl/test/WebglRenderer.api.ts +++ b/addons/xterm-addon-webgl/test/WebglRenderer.api.ts @@ -18,7 +18,7 @@ const height = 600; describe('WebGL Renderer Integration Tests', async () => { const browserType = getBrowserType(); - const isHeadless = process.argv.indexOf('--headless') !== -1; + const isHeadless = process.argv.includes('--headless'); // Firefox works only in non-headless mode https://github.com/microsoft/playwright/issues/1032 const areTestsEnabled = browserType.name() === 'chromium' || (browserType.name() === 'firefox' && !isHeadless); const itWebgl = areTestsEnabled ? it : it.skip; @@ -893,7 +893,7 @@ async function getCellColor(col: number, row: number): Promise { async function setupBrowser(options: ITerminalOptions = { rendererType: 'dom' }): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ - headless: process.argv.indexOf('--headless') !== -1 + headless: process.argv.includes('--headless') }); page = await (await browser.newContext()).newPage(); await page.setViewportSize({ width, height }); diff --git a/package.json b/package.json index 59902931..9134a378 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "xterm", "description": "Full xterm terminal, in your browser", - "version": "4.9.0", + "version": "4.11.0", "main": "lib/xterm.js", "style": "css/xterm.css", "types": "typings/xterm.d.ts", @@ -11,6 +11,7 @@ "prepackage": "npm run build", "package": "webpack", "start": "node demo/start", + "start-debug": "node --inspect-brk demo/start", "lint": "eslint -c .eslintrc.json --max-warnings 0 --ext .ts src/ addons/", "test": "npm run test-unit", "posttest": "npm run lint", diff --git a/src/browser/Clipboard.ts b/src/browser/Clipboard.ts index b0b42022..29e865c8 100644 --- a/src/browser/Clipboard.ts +++ b/src/browser/Clipboard.ts @@ -89,8 +89,8 @@ export function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextA 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); + if (shouldSelectWord) { + selectionService.rightClickSelect(ev); } // Get textarea ready to copy from the context menu diff --git a/src/browser/Linkifier2.ts b/src/browser/Linkifier2.ts index 73ea0268..89542936 100644 --- a/src/browser/Linkifier2.ts +++ b/src/browser/Linkifier2.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { ILinkifier2, ILinkProvider, IBufferCellPosition, ILink, ILinkifierEvent, ILinkDecorations } from 'browser/Types'; +import { ILinkifier2, ILinkProvider, IBufferCellPosition, ILink, ILinkifierEvent, ILinkDecorations, ILinkWithState } from 'browser/Types'; import { IDisposable } from 'common/Types'; import { IMouseService, IRenderService } from './services/Services'; import { IBufferService } from 'common/services/Services'; @@ -11,21 +11,12 @@ import { EventEmitter, IEvent } from 'common/EventEmitter'; import { Disposable, getDisposeArrayDisposable, disposeArray } from 'common/Lifecycle'; import { addDisposableDomListener } from 'browser/Lifecycle'; -interface ILinkState { - decorations: ILinkDecorations; - isHovered: boolean; -} - -interface ILinkWithState { - link: ILink; - state?: ILinkState; -} - export class Linkifier2 extends Disposable implements ILinkifier2 { private _element: HTMLElement | undefined; private _mouseService: IMouseService | undefined; private _renderService: IRenderService | undefined; private _linkProviders: ILinkProvider[] = []; + public get currentLink(): ILinkWithState | undefined { return this._currentLink; } protected _currentLink: ILinkWithState | undefined; private _lastMouseEvent: MouseEvent | undefined; private _linkCacheDisposables: IDisposable[] = []; diff --git a/src/browser/MouseZoneManager.ts b/src/browser/MouseZoneManager.ts index 59b6b0f1..b6740157 100644 --- a/src/browser/MouseZoneManager.ts +++ b/src/browser/MouseZoneManager.ts @@ -156,9 +156,7 @@ export class MouseZoneManager extends Disposable implements IMouseZoneManager { private _onTooltip(e: MouseEvent): void { this._tooltipTimeout = undefined; const zone = this._findZoneEventAt(e); - if (zone && zone.tooltipCallback) { - zone.tooltipCallback(e); - } + zone?.tooltipCallback(e); } private _onMouseDown(e: MouseEvent): void { diff --git a/src/browser/Terminal.test.ts b/src/browser/Terminal.test.ts index 8626be09..5724715f 100644 --- a/src/browser/Terminal.test.ts +++ b/src/browser/Terminal.test.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { assert, expect } from 'chai'; +import { assert } from 'chai'; import { MockViewport, MockCompositionHelper, MockRenderer, TestTerminal } from 'browser/TestUtils.test'; import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine'; import { CellData } from 'common/buffer/CellData'; @@ -55,27 +55,35 @@ describe('Terminal', () => { // term.onData(() => done()); // term.handler('fake'); // }); - it('should fire the onCursorMove event', (done) => { - term.onCursorMove(() => done()); - term.writeSync('foo'); + it('should fire the onCursorMove event', () => { + return new Promise(async r => { + term.onCursorMove(() => r()); + await term.writeP('foo'); + }); }); - it('should fire the onLineFeed event', (done) => { - term.onLineFeed(() => done()); - term.writeSync('\n'); + it('should fire the onLineFeed event', () => { + return new Promise(async r => { + term.onLineFeed(() => r()); + await term.writeP('\n'); + }); }); - it('should fire a scroll event when scrollback is created', (done) => { - term.onScroll(() => done()); - term.writeSync('\n'.repeat(INIT_ROWS)); + it('should fire a scroll event when scrollback is created', () => { + return new Promise(async r => { + term.onScroll(() => r()); + await term.writeP('\n'.repeat(INIT_ROWS)); + }); }); - it('should fire a scroll event when scrollback is cleared', (done) => { - term.writeSync('\n'.repeat(INIT_ROWS)); - term.onScroll(() => done()); - term.clear(); + it('should fire a scroll event when scrollback is cleared', () => { + return new Promise(async r => { + await term.writeP('\n'.repeat(INIT_ROWS)); + term.onScroll(() => r()); + term.clear(); + }); }); it('should fire a key event after a keypress DOM event', (done) => { term.onKey(e => { assert.equal(typeof e.key, 'string'); - expect(e.domEvent).to.be.an.instanceof(Object); + assert.equal(e.domEvent instanceof Object, true); done(); }); const evKeyPress = { @@ -89,7 +97,7 @@ describe('Terminal', () => { it('should fire a key event after a keydown DOM event', (done) => { term.onKey(e => { assert.equal(typeof e.key, 'string'); - expect(e.domEvent).to.be.an.instanceof(Object); + assert.equal(e.domEvent instanceof Object, true); done(); }); (term).textarea = { value: '' }; @@ -103,7 +111,6 @@ describe('Terminal', () => { }); it('should fire the onResize event', (done) => { term.onResize(e => { - expect(e).to.have.keys(['cols', 'rows']); assert.equal(typeof e.cols, 'number'); assert.equal(typeof e.rows, 'number'); done(); @@ -178,10 +185,10 @@ describe('Terminal', () => { assert.deepEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA)); } }); - it('should clear a buffer larger than rows', () => { + it('should clear a buffer larger than rows', async () => { // Fill the buffer with dummy rows for (let i = 0; i < term.rows * 2; i++) { - term.writeSync('test\n'); + await term.writeP('test\n'); } const promptLine = term.buffer.lines.get(term.buffer.ybase + term.buffer.y); @@ -225,22 +232,24 @@ describe('Terminal', () => { }); term.paste('\r\nfoo\nbar\r'); }); - it('should respect bracketed paste mode', done => { - term.onData(e => { - assert.equal(e, '\x1b[200~foo\x1b[201~'); - done(); + it('should respect bracketed paste mode', () => { + return new Promise(async r => { + term.onData(e => { + assert.equal(e, '\x1b[200~foo\x1b[201~'); + r(); + }); + await term.writeP('\x1b[?2004h'); + term.paste('foo'); }); - term.writeSync('\x1b[?2004h'); - term.paste('foo'); }); }); describe('scroll', () => { describe('scrollLines', () => { let startYDisp: number; - beforeEach(() => { + beforeEach(async () => { for (let i = 0; i < INIT_ROWS * 2; i++) { - term.writeSync('test\r\n'); + await term.writeP('test\r\n'); } startYDisp = INIT_ROWS + 1; }); @@ -273,9 +282,9 @@ describe('Terminal', () => { describe('scrollPages', () => { let startYDisp: number; - beforeEach(() => { + beforeEach(async () => { for (let i = 0; i < term.rows * 3; i++) { - term.writeSync('test\r\n'); + await term.writeP('test\r\n'); } startYDisp = (term.rows * 2) + 1; }); @@ -296,9 +305,9 @@ describe('Terminal', () => { }); describe('scrollToTop', () => { - beforeEach(() => { + beforeEach(async () => { for (let i = 0; i < term.rows * 3; i++) { - term.writeSync('test\r\n'); + await term.writeP('test\r\n'); } }); it('should scroll to the top', () => { @@ -310,9 +319,9 @@ describe('Terminal', () => { describe('scrollToBottom', () => { let startYDisp: number; - beforeEach(() => { + beforeEach(async () => { for (let i = 0; i < term.rows * 3; i++) { - term.writeSync('test\r\n'); + await term.writeP('test\r\n'); } startYDisp = (term.rows * 2) + 1; }); @@ -331,9 +340,9 @@ describe('Terminal', () => { describe('scrollToLine', () => { let startYDisp: number; - beforeEach(() => { + beforeEach(async () => { for (let i = 0; i < term.rows * 3; i++) { - term.writeSync('test\r\n'); + await term.writeP('test\r\n'); } startYDisp = (term.rows * 2) + 1; }); @@ -375,10 +384,10 @@ describe('Terminal', () => { assert.equal(term.buffer.ydisp, term.buffer.ybase); }); - it('should not scroll down, when a custom keydown handler prevents the event', () => { + it('should not scroll down, when a custom keydown handler prevents the event', async () => { // Add some output to the terminal for (let i = 0; i < term.rows * 3; i++) { - term.writeSync('test\r\n'); + await term.writeP('test\r\n'); } const startYDisp = (term.rows * 2) + 1; term.attachCustomKeyEventHandler(() => { @@ -717,75 +726,77 @@ describe('Terminal', () => { }); describe('unicode - surrogates', () => { - it('2 characters per cell', function (): void { + it('2 characters per cell', async function (): Promise { this.timeout(10000); // This is needed because istanbul patches code and slows it down const high = String.fromCharCode(0xD800); const cell = new CellData(); for (let i = 0xDC00; i <= 0xDCFF; ++i) { - term.writeSync(high + String.fromCharCode(i)); + await term.writeP(high + String.fromCharCode(i)); const tchar = term.buffer.lines.get(0)!.loadCell(0, cell); - expect(tchar.getChars()).eql(high + String.fromCharCode(i)); - expect(tchar.getChars().length).eql(2); - expect(tchar.getWidth()).eql(1); - expect(term.buffer.lines.get(0)!.loadCell(1, cell).getChars()).eql(''); + assert.equal(tchar.getChars(), high + String.fromCharCode(i)); + assert.equal(tchar.getChars().length, 2); + assert.equal(tchar.getWidth(), 1); + assert.equal(term.buffer.lines.get(0)!.loadCell(1, cell).getChars(), ''); term.reset(); } }); - it('2 characters at last cell', () => { + it('2 characters at last cell', async () => { const high = String.fromCharCode(0xD800); const cell = new CellData(); for (let i = 0xDC00; i <= 0xDCFF; ++i) { term.buffer.x = term.cols - 1; - term.writeSync(high + String.fromCharCode(i)); - expect(term.buffer.lines.get(0)!.loadCell(term.buffer.x - 1, cell).getChars()).eql(high + String.fromCharCode(i)); - expect(term.buffer.lines.get(0)!.loadCell(term.buffer.x - 1, cell).getChars().length).eql(2); - expect(term.buffer.lines.get(1)!.loadCell(0, cell).getChars()).eql(''); + await term.writeP(high + String.fromCharCode(i)); + assert.equal(term.buffer.lines.get(0)!.loadCell(term.buffer.x - 1, cell).getChars(), high + String.fromCharCode(i)); + assert.equal(term.buffer.lines.get(0)!.loadCell(term.buffer.x - 1, cell).getChars().length, 2); + assert.equal(term.buffer.lines.get(1)!.loadCell(0, cell).getChars(), ''); term.reset(); } }); - it('2 characters per cell over line end with autowrap', () => { + it('2 characters per cell over line end with autowrap', async function (): Promise { + this.timeout(10000); const high = String.fromCharCode(0xD800); const cell = new CellData(); for (let i = 0xDC00; i <= 0xDCFF; ++i) { term.buffer.x = term.cols - 1; - term.writeSync('a' + high + String.fromCharCode(i)); - expect(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars()).eql('a'); - expect(term.buffer.lines.get(1)!.loadCell(0, cell).getChars()).eql(high + String.fromCharCode(i)); - expect(term.buffer.lines.get(1)!.loadCell(0, cell).getChars().length).eql(2); - expect(term.buffer.lines.get(1)!.loadCell(1, cell).getChars()).eql(''); + await term.writeP('a' + high + String.fromCharCode(i)); + assert.equal(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars(), 'a'); + assert.equal(term.buffer.lines.get(1)!.loadCell(0, cell).getChars(), high + String.fromCharCode(i)); + assert.equal(term.buffer.lines.get(1)!.loadCell(0, cell).getChars().length, 2); + assert.equal(term.buffer.lines.get(1)!.loadCell(1, cell).getChars(), ''); term.reset(); } }); - it('2 characters per cell over line end without autowrap', () => { + it('2 characters per cell over line end without autowrap', async function (): Promise { + this.timeout(10000); const high = String.fromCharCode(0xD800); const cell = new CellData(); for (let i = 0xDC00; i <= 0xDCFF; ++i) { term.buffer.x = term.cols - 1; - term.writeSync('\x1b[?7l'); // Disable wraparound mode + await term.writeP('\x1b[?7l'); // Disable wraparound mode const width = wcwidth((0xD800 - 0xD800) * 0x400 + i - 0xDC00 + 0x10000); if (width !== 1) { continue; } - term.writeSync('a' + high + String.fromCharCode(i)); + await term.writeP('a' + high + String.fromCharCode(i)); // auto wraparound mode should cut off the rest of the line - expect(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars()).eql(high + String.fromCharCode(i)); - expect(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars().length).eql(2); - expect(term.buffer.lines.get(1)!.loadCell(1, cell).getChars()).eql(''); + assert.equal(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars(), high + String.fromCharCode(i)); + assert.equal(term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell).getChars().length, 2); + assert.equal(term.buffer.lines.get(1)!.loadCell(1, cell).getChars(), ''); term.reset(); } }); - it('splitted surrogates', () => { + it('splitted surrogates', async function (): Promise { + this.timeout(10000); const high = String.fromCharCode(0xD800); const cell = new CellData(); for (let i = 0xDC00; i <= 0xDCFF; ++i) { - term.writeSync(high); - term.writeSync(String.fromCharCode(i)); + await term.writeP(high + String.fromCharCode(i)); const tchar = term.buffer.lines.get(0)!.loadCell(0, cell); - expect(tchar.getChars()).eql(high + String.fromCharCode(i)); - expect(tchar.getChars().length).eql(2); - expect(tchar.getWidth()).eql(1); - expect(term.buffer.lines.get(0)!.loadCell(1, cell).getChars()).eql(''); + assert.equal(tchar.getChars(), high + String.fromCharCode(i)); + assert.equal(tchar.getChars().length, 2); + assert.equal(tchar.getWidth(), 1); + assert.equal(term.buffer.lines.get(0)!.loadCell(1, cell).getChars(), ''); term.reset(); } }); @@ -793,239 +804,239 @@ describe('Terminal', () => { describe('unicode - combining characters', () => { const cell = new CellData(); - it('café', () => { - term.writeSync('cafe\u0301'); + it('café', async () => { + await term.writeP('cafe\u0301'); term.buffer.lines.get(0)!.loadCell(3, cell); - expect(cell.getChars()).eql('e\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), 'e\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 1); }); - it('café - end of line', () => { + it('café - end of line', async () => { term.buffer.x = term.cols - 1 - 3; - term.writeSync('cafe\u0301'); + await term.writeP('cafe\u0301'); term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell); - expect(cell.getChars()).eql('e\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), 'e\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 1); term.buffer.lines.get(0)!.loadCell(1, cell); - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 1); }); - it('multiple combined é', () => { - term.writeSync(Array(100).join('e\u0301')); + it('multiple combined é', async () => { + await term.writeP(Array(100).join('e\u0301')); for (let i = 0; i < term.cols; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); - expect(cell.getChars()).eql('e\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), 'e\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 1); } term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('e\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), 'e\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 1); }); - it('multiple surrogate with combined', () => { - term.writeSync(Array(100).join('\uD800\uDC00\u0301')); + it('multiple surrogate with combined', async () => { + await term.writeP(Array(100).join('\uD800\uDC00\u0301')); for (let i = 0; i < term.cols; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); - expect(cell.getChars()).eql('\uD800\uDC00\u0301'); - expect(cell.getChars().length).eql(3); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), '\uD800\uDC00\u0301'); + assert.equal(cell.getChars().length, 3); + assert.equal(cell.getWidth(), 1); } term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('\uD800\uDC00\u0301'); - expect(cell.getChars().length).eql(3); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), '\uD800\uDC00\u0301'); + assert.equal(cell.getChars().length, 3); + assert.equal(cell.getWidth(), 1); }); }); describe('unicode - fullwidth characters', () => { const cell = new CellData(); - it('cursor movement even', () => { - expect(term.buffer.x).eql(0); - term.writeSync('¥'); - expect(term.buffer.x).eql(2); + it('cursor movement even', async () => { + assert.equal(term.buffer.x, 0); + await term.writeP('¥'); + assert.equal(term.buffer.x, 2); }); - it('cursor movement odd', () => { + it('cursor movement odd', async () => { term.buffer.x = 1; - expect(term.buffer.x).eql(1); - term.writeSync('¥'); - expect(term.buffer.x).eql(3); + assert.equal(term.buffer.x, 1); + await term.writeP('¥'); + assert.equal(term.buffer.x, 3); }); - it('line of ¥ even', () => { - term.writeSync(Array(50).join('¥')); + it('line of ¥ even', async () => { + await term.writeP(Array(50).join('¥')); for (let i = 0; i < term.cols; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); if (i % 2) { - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(0); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 0); } else { - expect(cell.getChars()).eql('¥'); - expect(cell.getChars().length).eql(1); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥'); + assert.equal(cell.getChars().length, 1); + assert.equal(cell.getWidth(), 2); } } term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('¥'); - expect(cell.getChars().length).eql(1); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥'); + assert.equal(cell.getChars().length, 1); + assert.equal(cell.getWidth(), 2); }); - it('line of ¥ odd', () => { + it('line of ¥ odd', async () => { term.buffer.x = 1; - term.writeSync(Array(50).join('¥')); + await term.writeP(Array(50).join('¥')); for (let i = 1; i < term.cols - 1; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); if (!(i % 2)) { - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(0); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 0); } else { - expect(cell.getChars()).eql('¥'); - expect(cell.getChars().length).eql(1); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥'); + assert.equal(cell.getChars().length, 1); + assert.equal(cell.getWidth(), 2); } } term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell); - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 1); term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('¥'); - expect(cell.getChars().length).eql(1); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥'); + assert.equal(cell.getChars().length, 1); + assert.equal(cell.getWidth(), 2); }); - it('line of ¥ with combining odd', () => { + it('line of ¥ with combining odd', async () => { term.buffer.x = 1; - term.writeSync(Array(50).join('¥\u0301')); + await term.writeP(Array(50).join('¥\u0301')); for (let i = 1; i < term.cols - 1; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); if (!(i % 2)) { - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(0); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 0); } else { - expect(cell.getChars()).eql('¥\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 2); } } term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell); - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 1); term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('¥\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 2); }); - it('line of ¥ with combining even', () => { - term.writeSync(Array(50).join('¥\u0301')); + it('line of ¥ with combining even', async () => { + await term.writeP(Array(50).join('¥\u0301')); for (let i = 0; i < term.cols; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); if (i % 2) { - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(0); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 0); } else { - expect(cell.getChars()).eql('¥\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 2); } } term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('¥\u0301'); - expect(cell.getChars().length).eql(2); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '¥\u0301'); + assert.equal(cell.getChars().length, 2); + assert.equal(cell.getWidth(), 2); }); - it('line of surrogate fullwidth with combining odd', () => { + it('line of surrogate fullwidth with combining odd', async () => { term.buffer.x = 1; - term.writeSync(Array(50).join('\ud843\ude6d\u0301')); + await term.writeP(Array(50).join('\ud843\ude6d\u0301')); for (let i = 1; i < term.cols - 1; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); if (!(i % 2)) { - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(0); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 0); } else { - expect(cell.getChars()).eql('\ud843\ude6d\u0301'); - expect(cell.getChars().length).eql(3); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '\ud843\ude6d\u0301'); + assert.equal(cell.getChars().length, 3); + assert.equal(cell.getWidth(), 2); } } term.buffer.lines.get(0)!.loadCell(term.cols - 1, cell); - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(1); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 1); term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('\ud843\ude6d\u0301'); - expect(cell.getChars().length).eql(3); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '\ud843\ude6d\u0301'); + assert.equal(cell.getChars().length, 3); + assert.equal(cell.getWidth(), 2); }); - it('line of surrogate fullwidth with combining even', () => { - term.writeSync(Array(50).join('\ud843\ude6d\u0301')); + it('line of surrogate fullwidth with combining even', async () => { + await term.writeP(Array(50).join('\ud843\ude6d\u0301')); for (let i = 0; i < term.cols; ++i) { term.buffer.lines.get(0)!.loadCell(i, cell); if (i % 2) { - expect(cell.getChars()).eql(''); - expect(cell.getChars().length).eql(0); - expect(cell.getWidth()).eql(0); + assert.equal(cell.getChars(), ''); + assert.equal(cell.getChars().length, 0); + assert.equal(cell.getWidth(), 0); } else { - expect(cell.getChars()).eql('\ud843\ude6d\u0301'); - expect(cell.getChars().length).eql(3); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '\ud843\ude6d\u0301'); + assert.equal(cell.getChars().length, 3); + assert.equal(cell.getWidth(), 2); } } term.buffer.lines.get(1)!.loadCell(0, cell); - expect(cell.getChars()).eql('\ud843\ude6d\u0301'); - expect(cell.getChars().length).eql(3); - expect(cell.getWidth()).eql(2); + assert.equal(cell.getChars(), '\ud843\ude6d\u0301'); + assert.equal(cell.getChars().length, 3); + assert.equal(cell.getWidth(), 2); }); }); describe('insert mode', () => { const cell = new CellData(); - it('halfwidth - all', () => { - term.writeSync(Array(9).join('0123456789').slice(-80)); + it('halfwidth - all', async () => { + await term.writeP(Array(9).join('0123456789').slice(-80)); term.buffer.x = 10; term.buffer.y = 0; term.write('\x1b[4h'); - term.writeSync('abcde'); - expect(term.buffer.lines.get(0)!.length).eql(term.cols); - expect(term.buffer.lines.get(0)!.loadCell(10, cell).getChars()).eql('a'); - expect(term.buffer.lines.get(0)!.loadCell(14, cell).getChars()).eql('e'); - expect(term.buffer.lines.get(0)!.loadCell(15, cell).getChars()).eql('0'); - expect(term.buffer.lines.get(0)!.loadCell(79, cell).getChars()).eql('4'); + await term.writeP('abcde'); + assert.equal(term.buffer.lines.get(0)!.length, term.cols); + assert.equal(term.buffer.lines.get(0)!.loadCell(10, cell).getChars(), 'a'); + assert.equal(term.buffer.lines.get(0)!.loadCell(14, cell).getChars(), 'e'); + assert.equal(term.buffer.lines.get(0)!.loadCell(15, cell).getChars(), '0'); + assert.equal(term.buffer.lines.get(0)!.loadCell(79, cell).getChars(), '4'); }); - it('fullwidth - insert', () => { - term.writeSync(Array(9).join('0123456789').slice(-80)); + it('fullwidth - insert', async () => { + await term.writeP(Array(9).join('0123456789').slice(-80)); term.buffer.x = 10; term.buffer.y = 0; term.write('\x1b[4h'); - term.writeSync('¥¥¥'); - expect(term.buffer.lines.get(0)!.length).eql(term.cols); - expect(term.buffer.lines.get(0)!.loadCell(10, cell).getChars()).eql('¥'); - expect(term.buffer.lines.get(0)!.loadCell(11, cell).getChars()).eql(''); - expect(term.buffer.lines.get(0)!.loadCell(14, cell).getChars()).eql('¥'); - expect(term.buffer.lines.get(0)!.loadCell(15, cell).getChars()).eql(''); - expect(term.buffer.lines.get(0)!.loadCell(79, cell).getChars()).eql('3'); + await term.writeP('¥¥¥'); + assert.equal(term.buffer.lines.get(0)!.length, term.cols); + assert.equal(term.buffer.lines.get(0)!.loadCell(10, cell).getChars(), '¥'); + assert.equal(term.buffer.lines.get(0)!.loadCell(11, cell).getChars(), ''); + assert.equal(term.buffer.lines.get(0)!.loadCell(14, cell).getChars(), '¥'); + assert.equal(term.buffer.lines.get(0)!.loadCell(15, cell).getChars(), ''); + assert.equal(term.buffer.lines.get(0)!.loadCell(79, cell).getChars(), '3'); }); - it('fullwidth - right border', () => { - term.writeSync(Array(41).join('¥')); + it('fullwidth - right border', async () => { + await term.writeP(Array(41).join('¥')); term.buffer.x = 10; term.buffer.y = 0; term.write('\x1b[4h'); - term.writeSync('a'); - expect(term.buffer.lines.get(0)!.length).eql(term.cols); - expect(term.buffer.lines.get(0)!.loadCell(10, cell).getChars()).eql('a'); - expect(term.buffer.lines.get(0)!.loadCell(11, cell).getChars()).eql('¥'); - expect(term.buffer.lines.get(0)!.loadCell(79, cell).getChars()).eql(''); // fullwidth char got replaced - term.writeSync('b'); - expect(term.buffer.lines.get(0)!.length).eql(term.cols); - expect(term.buffer.lines.get(0)!.loadCell(11, cell).getChars()).eql('b'); - expect(term.buffer.lines.get(0)!.loadCell(12, cell).getChars()).eql('¥'); - expect(term.buffer.lines.get(0)!.loadCell(79, cell).getChars()).eql(''); // empty cell after fullwidth + await term.writeP('a'); + assert.equal(term.buffer.lines.get(0)!.length, term.cols); + assert.equal(term.buffer.lines.get(0)!.loadCell(10, cell).getChars(), 'a'); + assert.equal(term.buffer.lines.get(0)!.loadCell(11, cell).getChars(), '¥'); + assert.equal(term.buffer.lines.get(0)!.loadCell(79, cell).getChars(), ''); // fullwidth char got replaced + await term.writeP('b'); + assert.equal(term.buffer.lines.get(0)!.length, term.cols); + assert.equal(term.buffer.lines.get(0)!.loadCell(11, cell).getChars(), 'b'); + assert.equal(term.buffer.lines.get(0)!.loadCell(12, cell).getChars(), '¥'); + assert.equal(term.buffer.lines.get(0)!.loadCell(79, cell).getChars(), ''); // empty cell after fullwidth }); }); @@ -1043,85 +1054,87 @@ describe('Terminal', () => { linkifier.attachToDom({} as any, mouseZoneManager); }); - function assertLinkifiesInTerminal(rowText: string, linkMatcherRegex: RegExp, links: {x1: number, y1: number, x2: number, y2: number}[], done: Mocha.Done): void { - terminal.writeSync(rowText); - linkifier.registerLinkMatcher(linkMatcherRegex, () => {}); - linkifier.linkifyRows(); - // Allow linkify to happen - setTimeout(() => { - assert.equal(mouseZoneManager.zones.length, links.length); - links.forEach((l, i) => { - assert.equal(mouseZoneManager.zones[i].x1, l.x1 + 1); - assert.equal(mouseZoneManager.zones[i].x2, l.x2 + 1); - assert.equal(mouseZoneManager.zones[i].y1, l.y1 + 1); - assert.equal(mouseZoneManager.zones[i].y2, l.y2 + 1); - }); - done(); - }, 0); + function assertLinkifiesInTerminal(rowText: string, linkMatcherRegex: RegExp, links: {x1: number, y1: number, x2: number, y2: number}[]): Promise { + return new Promise(async r => { + await terminal.writeP(rowText); + linkifier.registerLinkMatcher(linkMatcherRegex, () => {}); + linkifier.linkifyRows(); + // Allow linkify to happen + setTimeout(() => { + assert.equal(mouseZoneManager.zones.length, links.length); + links.forEach((l, i) => { + assert.equal(mouseZoneManager.zones[i].x1, l.x1 + 1); + assert.equal(mouseZoneManager.zones[i].x2, l.x2 + 1); + assert.equal(mouseZoneManager.zones[i].y1, l.y1 + 1); + assert.equal(mouseZoneManager.zones[i].y2, l.y2 + 1); + }); + r(); + }, 0); + }); } describe('unicode before the match', () => { - it('combining - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('e\u0301e\u0301e\u0301 foo', /foo/, [{x1: 4, x2: 7, y1: 0, y2: 0}], done); + it('combining - match within one line', () => { + return assertLinkifiesInTerminal('e\u0301e\u0301e\u0301 foo', /foo/, [{x1: 4, x2: 7, y1: 0, y2: 0}]); }); - it('combining - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('e\u0301e\u0301e\u0301 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}], done); + it('combining - match over two lines', () => { + return assertLinkifiesInTerminal('e\u0301e\u0301e\u0301 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}]); }); - it('surrogate - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('𝄞𝄞𝄞 foo', /foo/, [{x1: 4, x2: 7, y1: 0, y2: 0}], done); + it('surrogate - match within one line', () => { + return assertLinkifiesInTerminal('𝄞𝄞𝄞 foo', /foo/, [{x1: 4, x2: 7, y1: 0, y2: 0}]); }); - it('surrogate - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('𝄞𝄞𝄞 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}], done); + it('surrogate - match over two lines', () => { + return assertLinkifiesInTerminal('𝄞𝄞𝄞 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}]); }); - it('combining surrogate - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('𓂀\u0301𓂀\u0301𓂀\u0301 foo', /foo/, [{x1: 4, x2: 7, y1: 0, y2: 0}], done); + it('combining surrogate - match within one line', () => { + return assertLinkifiesInTerminal('𓂀\u0301𓂀\u0301𓂀\u0301 foo', /foo/, [{x1: 4, x2: 7, y1: 0, y2: 0}]); }); - it('combining surrogate - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('𓂀\u0301𓂀\u0301𓂀\u0301 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}], done); + it('combining surrogate - match over two lines', () => { + return assertLinkifiesInTerminal('𓂀\u0301𓂀\u0301𓂀\u0301 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}]); }); - it('fullwidth - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('12 foo', /foo/, [{x1: 5, x2: 8, y1: 0, y2: 0}], done); + it('fullwidth - match within one line', () => { + return assertLinkifiesInTerminal('12 foo', /foo/, [{x1: 5, x2: 8, y1: 0, y2: 0}]); }); - it('fullwidth - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('12 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}], done); + it('fullwidth - match over two lines', () => { + return assertLinkifiesInTerminal('12 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}]); }); - it('combining fullwidth - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('¥\u0301¥\u0301 foo', /foo/, [{x1: 5, x2: 8, y1: 0, y2: 0}], done); + it('combining fullwidth - match within one line', () => { + return assertLinkifiesInTerminal('¥\u0301¥\u0301 foo', /foo/, [{x1: 5, x2: 8, y1: 0, y2: 0}]); }); - it('combining fullwidth - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('¥\u0301¥\u0301 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}], done); + it('combining fullwidth - match over two lines', () => { + return assertLinkifiesInTerminal('¥\u0301¥\u0301 foo', /foo/, [{x1: 8, x2: 1, y1: 0, y2: 1}]); }); }); describe('unicode within the match', () => { - it('combining - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('test cafe\u0301', /cafe\u0301/, [{x1: 5, x2: 9, y1: 0, y2: 0}], done); + it('combining - match within one line', () => { + return assertLinkifiesInTerminal('test cafe\u0301', /cafe\u0301/, [{x1: 5, x2: 9, y1: 0, y2: 0}]); }); - it('combining - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('testtest cafe\u0301', /cafe\u0301/, [{x1: 9, x2: 3, y1: 0, y2: 1}], done); + it('combining - match over two lines', () => { + return assertLinkifiesInTerminal('testtest cafe\u0301', /cafe\u0301/, [{x1: 9, x2: 3, y1: 0, y2: 1}]); }); - it('surrogate - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('test a𝄞b', /a𝄞b/, [{x1: 5, x2: 8, y1: 0, y2: 0}], done); + it('surrogate - match within one line', () => { + return assertLinkifiesInTerminal('test a𝄞b', /a𝄞b/, [{x1: 5, x2: 8, y1: 0, y2: 0}]); }); - it('surrogate - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('testtest a𝄞b', /a𝄞b/, [{x1: 9, x2: 2, y1: 0, y2: 1}], done); + it('surrogate - match over two lines', () => { + return assertLinkifiesInTerminal('testtest a𝄞b', /a𝄞b/, [{x1: 9, x2: 2, y1: 0, y2: 1}]); }); - it('combining surrogate - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('test a𓂀\u0301b', /a𓂀\u0301b/, [{x1: 5, x2: 8, y1: 0, y2: 0}], done); + it('combining surrogate - match within one line', () => { + return assertLinkifiesInTerminal('test a𓂀\u0301b', /a𓂀\u0301b/, [{x1: 5, x2: 8, y1: 0, y2: 0}]); }); - it('combining surrogate - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('testtest a𓂀\u0301b', /a𓂀\u0301b/, [{x1: 9, x2: 2, y1: 0, y2: 1}], done); + it('combining surrogate - match over two lines', () => { + return assertLinkifiesInTerminal('testtest a𓂀\u0301b', /a𓂀\u0301b/, [{x1: 9, x2: 2, y1: 0, y2: 1}]); }); - it('fullwidth - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('test a1b', /a1b/, [{x1: 5, x2: 9, y1: 0, y2: 0}], done); + it('fullwidth - match within one line', () => { + return assertLinkifiesInTerminal('test a1b', /a1b/, [{x1: 5, x2: 9, y1: 0, y2: 0}]); }); - it('fullwidth - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('testtest a1b', /a1b/, [{x1: 9, x2: 3, y1: 0, y2: 1}], done); + it('fullwidth - match over two lines', () => { + return assertLinkifiesInTerminal('testtest a1b', /a1b/, [{x1: 9, x2: 3, y1: 0, y2: 1}]); }); - it('combining fullwidth - match within one line', function(done: () => void): void { - assertLinkifiesInTerminal('test a¥\u0301b', /a¥\u0301b/, [{x1: 5, x2: 9, y1: 0, y2: 0}], done); + it('combining fullwidth - match within one line', () => { + return assertLinkifiesInTerminal('test a¥\u0301b', /a¥\u0301b/, [{x1: 5, x2: 9, y1: 0, y2: 0}]); }); - it('combining fullwidth - match over two lines', function(done: () => void): void { - assertLinkifiesInTerminal('testtest a¥\u0301b', /a¥\u0301b/, [{x1: 9, x2: 3, y1: 0, y2: 1}], done); + it('combining fullwidth - match over two lines', () => { + return assertLinkifiesInTerminal('testtest a¥\u0301b', /a¥\u0301b/, [{x1: 9, x2: 3, y1: 0, y2: 1}]); }); }); }); @@ -1133,9 +1146,9 @@ describe('Terminal', () => { terminal = new TestTerminal({rows: 5, cols: 10, scrollback: 5}); }); - it('multiline ascii', () => { + it('multiline ascii', async () => { const input = 'This is ASCII text spanning multiple lines.'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 0; i < input.length; ++i) { @@ -1144,9 +1157,9 @@ describe('Terminal', () => { } }); - it('combining e\u0301 in a sentence', () => { + it('combining e\u0301 in a sentence', async () => { const input = 'Sitting in the cafe\u0301 drinking coffee.'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 0; i < 19; ++i) { @@ -1164,9 +1177,9 @@ describe('Terminal', () => { } }); - it('multiline combining e\u0301', () => { + it('multiline combining e\u0301', async () => { const input = 'e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301e\u0301'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); // every buffer cell index contains 2 string indices @@ -1176,9 +1189,9 @@ describe('Terminal', () => { } }); - it('surrogate char in a sentence', () => { + it('surrogate char in a sentence', async () => { const input = 'The 𝄞 is a clef widely used in modern notation.'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 0; i < 5; ++i) { @@ -1196,9 +1209,9 @@ describe('Terminal', () => { } }); - it('multiline surrogate char', () => { + it('multiline surrogate char', async () => { const input = '𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞𝄞'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); // every buffer cell index contains 2 string indices @@ -1208,10 +1221,10 @@ describe('Terminal', () => { } }); - it('surrogate char with combining', () => { + it('surrogate char with combining', async () => { // eye of Ra with acute accent - string length of 3 const input = '𓂀\u0301 - the eye hiroglyph with an acute accent.'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); // index 0..2 should map to 0 @@ -1223,9 +1236,9 @@ describe('Terminal', () => { } }); - it('multiline surrogate with combining', () => { + it('multiline surrogate with combining', async () => { const input = '𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301𓂀\u0301'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); // every buffer cell index contains 3 string indices @@ -1235,9 +1248,9 @@ describe('Terminal', () => { } }); - it('fullwidth chars', () => { + it('fullwidth chars', async () => { const input = 'These 123 are some fat numbers.'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 0; i < 6; ++i) { @@ -1254,9 +1267,9 @@ describe('Terminal', () => { } }); - it('multiline fullwidth chars', () => { + it('multiline fullwidth chars', async () => { const input = '12345678901234567890'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 9; i < input.length; ++i) { @@ -1265,9 +1278,9 @@ describe('Terminal', () => { } }); - it('fullwidth combining with emoji - match emoji cell', () => { + it('fullwidth combining with emoji - match emoji cell', async () => { const input = 'Lots of ¥\u0301 make me 😃.'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); const stringIndex = s.match(/😃/)!.index!; @@ -1275,14 +1288,14 @@ describe('Terminal', () => { assert(terminal.buffer.lines.get(bufferIndex[0])!.loadCell(bufferIndex[1], new CellData()).getChars(), '😃'); }); - it('multiline fullwidth chars with offset 1 (currently tests for broken behavior)', () => { + it('multiline fullwidth chars with offset 1 (currently tests for broken behavior)', async () => { const input = 'a12345678901234567890'; // the 'a' at the beginning moves all fullwidth chars one to the right // now the end of the line contains a dangling empty cell since // the next fullwidth char has to wrap early // the dangling last cell is wrongly added in the string // --> fixable after resolving #1685 - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 10; i < input.length; ++i) { @@ -1292,9 +1305,9 @@ describe('Terminal', () => { } }); - it('test fully wrapped buffer up to last char', () => { + it('test fully wrapped buffer up to last char', async () => { const input = Array(6).join('1234567890'); - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 0; i < input.length; ++i) { @@ -1303,10 +1316,10 @@ describe('Terminal', () => { } }); - it('test fully wrapped buffer up to last char with full width odd', () => { + it('test fully wrapped buffer up to last char with full width odd', async () => { const input = 'a¥\u0301a¥\u0301a¥\u0301a¥\u0301a¥\u0301a¥\u0301a¥\u0301a¥\u0301' + 'a¥\u0301a¥\u0301a¥\u0301a¥\u0301a¥\u0301a¥\u0301a¥\u0301'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(input, s); for (let i = 0; i < input.length; ++i) { @@ -1321,16 +1334,16 @@ describe('Terminal', () => { } }); - it('should handle \t in lines correctly', () => { + it('should handle \t in lines correctly', async () => { const input = '\thttps://google.de'; - terminal.writeSync(input); + await terminal.writeP(input); const s = terminal.buffer.iterator(true).next().content; assert.equal(s, Array(terminal.optionsService.options.tabStopWidth + 1).join(' ') + 'https://google.de'); }); }); describe('BufferStringIterator', function(): void { - it('iterator does not overflow buffer limits', function(): void { + it('iterator does not overflow buffer limits', async () => { const terminal = new TestTerminal({rows: 5, cols: 10, scrollback: 5}); const data = [ 'aaaaaaaaaa', @@ -1344,9 +1357,9 @@ describe('Terminal', () => { 'aaaaaaaaaa', 'aaaaaaaaaa' ]; - terminal.writeSync(data.join('')); + await terminal.writeP(data.join('')); // brute force test with insane values - expect(() => { + assert.doesNotThrow(() => { for (let overscan = 0; overscan < 20; ++overscan) { for (let start = -10; start < 20; ++start) { for (let end = -10; end < 20; ++end) { @@ -1357,12 +1370,12 @@ describe('Terminal', () => { } } } - }).to.not.throw(); + }); }); }); describe('Windows Mode', () => { - it('should mark lines as wrapped when the line ends in a non-null character after a LF', () => { + it('should mark lines as wrapped when the line ends in a non-null character after a LF', async () => { const data = [ 'aaaaaaaaaa\n\r', // cannot wrap as it's the first 'aaaaaaaaa\n\r', // wrapped (windows mode only) @@ -1370,19 +1383,19 @@ describe('Terminal', () => { ]; const normalTerminal = new TestTerminal({rows: 5, cols: 10, windowsMode: false}); - normalTerminal.writeSync(data.join('')); + await normalTerminal.writeP(data.join('')); assert.equal(normalTerminal.buffer.lines.get(0)!.isWrapped, false); assert.equal(normalTerminal.buffer.lines.get(1)!.isWrapped, false); assert.equal(normalTerminal.buffer.lines.get(2)!.isWrapped, false); const windowsModeTerminal = new TestTerminal({rows: 5, cols: 10, windowsMode: true}); - windowsModeTerminal.writeSync(data.join('')); + await windowsModeTerminal.writeP(data.join('')); assert.equal(windowsModeTerminal.buffer.lines.get(0)!.isWrapped, false); assert.equal(windowsModeTerminal.buffer.lines.get(1)!.isWrapped, true, 'This line should wrap in Windows mode as the previous line ends in a non-null character'); assert.equal(windowsModeTerminal.buffer.lines.get(2)!.isWrapped, false); }); - it('should mark lines as wrapped when the line ends in a non-null character after a CUP', () => { + it('should mark lines as wrapped when the line ends in a non-null character after a CUP', async () => { const data = [ 'aaaaaaaaaa\x1b[2;1H', // cannot wrap as it's the first 'aaaaaaaaa\x1b[3;1H', // wrapped (windows mode only) @@ -1390,34 +1403,34 @@ describe('Terminal', () => { ]; const normalTerminal = new TestTerminal({rows: 5, cols: 10, windowsMode: false}); - normalTerminal.writeSync(data.join('')); + await normalTerminal.writeP(data.join('')); assert.equal(normalTerminal.buffer.lines.get(0)!.isWrapped, false); assert.equal(normalTerminal.buffer.lines.get(1)!.isWrapped, false); assert.equal(normalTerminal.buffer.lines.get(2)!.isWrapped, false); const windowsModeTerminal = new TestTerminal({rows: 5, cols: 10, windowsMode: true}); - windowsModeTerminal.writeSync(data.join('')); + await windowsModeTerminal.writeP(data.join('')); assert.equal(windowsModeTerminal.buffer.lines.get(0)!.isWrapped, false); assert.equal(windowsModeTerminal.buffer.lines.get(1)!.isWrapped, true, 'This line should wrap in Windows mode as the previous line ends in a non-null character'); assert.equal(windowsModeTerminal.buffer.lines.get(2)!.isWrapped, false); }); }); - it('convertEol setting', function(): void { + it('convertEol setting', async () => { // not converting const termNotConverting = new TestTerminal({cols: 15, rows: 10}); - termNotConverting.writeSync('Hello\nWorld'); - expect(termNotConverting.buffer.lines.get(0)!.translateToString(false)).equals('Hello '); - expect(termNotConverting.buffer.lines.get(1)!.translateToString(false)).equals(' World '); - expect(termNotConverting.buffer.lines.get(0)!.translateToString(true)).equals('Hello'); - expect(termNotConverting.buffer.lines.get(1)!.translateToString(true)).equals(' World'); + await termNotConverting.writeP('Hello\nWorld'); + assert.equal(termNotConverting.buffer.lines.get(0)!.translateToString(false), 'Hello '); + assert.equal(termNotConverting.buffer.lines.get(1)!.translateToString(false), ' World '); + assert.equal(termNotConverting.buffer.lines.get(0)!.translateToString(true), 'Hello'); + assert.equal(termNotConverting.buffer.lines.get(1)!.translateToString(true), ' World'); // converting const termConverting = new TestTerminal({cols: 15, rows: 10, convertEol: true}); - termConverting.writeSync('Hello\nWorld'); - expect(termConverting.buffer.lines.get(0)!.translateToString(false)).equals('Hello '); - expect(termConverting.buffer.lines.get(1)!.translateToString(false)).equals('World '); - expect(termConverting.buffer.lines.get(0)!.translateToString(true)).equals('Hello'); - expect(termConverting.buffer.lines.get(1)!.translateToString(true)).equals('World'); + await termConverting.writeP('Hello\nWorld'); + assert.equal(termConverting.buffer.lines.get(0)!.translateToString(false), 'Hello '); + assert.equal(termConverting.buffer.lines.get(1)!.translateToString(false), 'World '); + assert.equal(termConverting.buffer.lines.get(0)!.translateToString(true), 'Hello'); + assert.equal(termConverting.buffer.lines.get(1)!.translateToString(true), 'World'); }); describe('Terminal InputHandler integration', () => { function getLines(term: TestTerminal, limit: number = term.rows): string[] { @@ -1434,54 +1447,54 @@ describe('Terminal', () => { beforeEach(() => { term = new TestTerminal({cols: 5, rows: 5, scrollback: 1}); }); - it('SL (scrollLeft)', () => { - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[ @'); + it('SL (scrollLeft)', async () => { + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[ @'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '2345', '2345', '2345', '2345', '2345']); - term.writeSync('\x1b[0 @'); + await term.writeP('\x1b[0 @'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '345', '345', '345', '345', '345']); - term.writeSync('\x1b[2 @'); + await term.writeP('\x1b[2 @'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '5', '5', '5', '5', '5']); }); - it('SR (scrollRight)', () => { - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[ A'); + it('SR (scrollRight)', async () => { + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[ A'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', ' 1234', ' 1234', ' 1234', ' 1234', ' 1234']); - term.writeSync('\x1b[0 A'); + await term.writeP('\x1b[0 A'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', ' 123', ' 123', ' 123', ' 123', ' 123']); - term.writeSync('\x1b[2 A'); + await term.writeP('\x1b[2 A'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', ' 1', ' 1', ' 1', ' 1', ' 1']); }); - it('insertColumns (DECIC)', () => { - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[3;3H'); - term.writeSync('\x1b[\'}'); + it('insertColumns (DECIC)', async () => { + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[3;3H'); + await term.writeP('\x1b[\'}'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '12 34', '12 34', '12 34', '12 34', '12 34']); term.reset(); - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[3;3H'); - term.writeSync('\x1b[1\'}'); + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[3;3H'); + await term.writeP('\x1b[1\'}'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '12 34', '12 34', '12 34', '12 34', '12 34']); term.reset(); - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[3;3H'); - term.writeSync('\x1b[2\'}'); + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[3;3H'); + await term.writeP('\x1b[2\'}'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '12 3', '12 3', '12 3', '12 3', '12 3']); }); - it('deleteColumns (DECDC)', () => { - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[3;3H'); - term.writeSync('\x1b[\'~'); + it('deleteColumns (DECDC)', async () => { + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[3;3H'); + await term.writeP('\x1b[\'~'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '1245', '1245', '1245', '1245', '1245']); term.reset(); - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[3;3H'); - term.writeSync('\x1b[1\'~'); + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[3;3H'); + await term.writeP('\x1b[1\'~'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '1245', '1245', '1245', '1245', '1245']); term.reset(); - term.writeSync('12345'.repeat(6)); - term.writeSync('\x1b[3;3H'); - term.writeSync('\x1b[2\'~'); + await term.writeP('12345'.repeat(6)); + await term.writeP('\x1b[3;3H'); + await term.writeP('\x1b[2\'~'); assert.deepEqual(getLines(term, term.rows + 1), ['12345', '125', '125', '125', '125', '125']); }); }); @@ -1494,41 +1507,41 @@ describe('Terminal', () => { }); describe('reverseWraparound set', () => { - it('should not reverse outside of scroll margins', () => { + it('should not reverse outside of scroll margins', async () => { // prepare buffer content - term.writeSync('#####abcdefghijklmnopqrstuvwxy'); + await term.writeP('#####abcdefghijklmnopqrstuvwxy'); assert.deepEqual(getLines(term, 6), ['#####', 'abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']); assert.equal(term.buffer.ydisp, 1); assert.equal(term.buffer.x, 5); assert.equal(term.buffer.y, 4); - term.writeSync(ttyBS.repeat(100)); + await term.writeP(ttyBS.repeat(100)); assert.deepEqual(getLines(term, 6), ['#####', 'abcde', 'fghij', 'klmno', 'pqrst', ' y']); - term.writeSync('\x1b[?45h'); - term.writeSync('uvwxy'); + await term.writeP('\x1b[?45h'); + await term.writeP('uvwxy'); // set top/bottom to 1/3 (0-based) - term.writeSync('\x1b[2;4r'); + await term.writeP('\x1b[2;4r'); // place cursor below scroll bottom term.buffer.x = 5; term.buffer.y = 4; - term.writeSync(ttyBS.repeat(100)); + await term.writeP(ttyBS.repeat(100)); assert.deepEqual(getLines(term, 6), ['#####', 'abcde', 'fghij', 'klmno', 'pqrst', ' ']); - term.writeSync('uvwxy'); + await term.writeP('uvwxy'); // place cursor within scroll margins term.buffer.x = 5; term.buffer.y = 3; - term.writeSync(ttyBS.repeat(100)); + await term.writeP(ttyBS.repeat(100)); assert.deepEqual(getLines(term, 6), ['#####', 'abcde', ' ', ' ', ' ', 'uvwxy']); assert.equal(term.buffer.x, 0); assert.equal(term.buffer.y, term.buffer.scrollTop); // stops at 0, scrollTop - term.writeSync('fghijklmnopqrst'); + await term.writeP('fghijklmnopqrst'); // place cursor above scroll top term.buffer.x = 5; term.buffer.y = 0; - term.writeSync(ttyBS.repeat(100)); + await term.writeP(ttyBS.repeat(100)); assert.deepEqual(getLines(term, 6), ['#####', ' ', 'fghij', 'klmno', 'pqrst', 'uvwxy']); }); }); @@ -1542,22 +1555,22 @@ describe('Terminal', () => { let markers: IMarker[]; let disposeStack: IMarker[]; let term: TestTerminal; - beforeEach(() => { + beforeEach(async () => { term = new TestTerminal({}); markers = []; disposeStack = []; term.optionsService.setOption('scrollback', 1); term.resize(10, 5); markers.push(term.buffers.active.addMarker(term.buffers.active.y)); - term.writeSync('\x1b[r0\r\n'); + await term.writeP('\x1b[r0\r\n'); markers.push(term.buffers.active.addMarker(term.buffers.active.y)); - term.writeSync('1\r\n'); + await term.writeP('1\r\n'); markers.push(term.buffers.active.addMarker(term.buffers.active.y)); - term.writeSync('2\r\n'); + await term.writeP('2\r\n'); markers.push(term.buffers.active.addMarker(term.buffers.active.y)); - term.writeSync('3\r\n'); + await term.writeP('3\r\n'); markers.push(term.buffers.active.addMarker(term.buffers.active.y)); - term.writeSync('4'); + await term.writeP('4'); for (let i = 0; i < markers.length; ++i) { const marker = markers[i]; marker.onDispose(() => disposeStack.push(marker)); @@ -1566,15 +1579,15 @@ describe('Terminal', () => { it('initial', () => { assert.deepEqual(markers.map(m => m.line), [0, 1, 2, 3, 4]); }); - it('should dispose on normal trim off the top', () => { + it('should dispose on normal trim off the top', async () => { // moves top line into scrollback - term.writeSync('\n'); + await term.writeP('\n'); assert.deepEqual(disposeStack, []); // trims first marker - term.writeSync('\n'); + await term.writeP('\n'); assert.deepEqual(disposeStack, [markers[0]]); // trims second marker - term.writeSync('\n'); + await term.writeP('\n'); assert.deepEqual(disposeStack, [markers[0], markers[1]]); // trimmed marker objs should be disposed assert.deepEqual(disposeStack.map(el => el.isDisposed), [true, true]); @@ -1582,14 +1595,14 @@ describe('Terminal', () => { // trimmed markers should contain line -1 assert.deepEqual(disposeStack.map(el => el.line), [-1, -1]); }); - it('should dispose on DL', () => { - term.writeSync('\x1b[3;1H'); // move cursor to 0, 2 - term.writeSync('\x1b[2M'); // delete 2 lines + it('should dispose on DL', async () => { + await term.writeP('\x1b[3;1H'); // move cursor to 0, 2 + await term.writeP('\x1b[2M'); // delete 2 lines assert.deepEqual(disposeStack, [markers[2], markers[3]]); }); - it('should dispose on IL', () => { - term.writeSync('\x1b[3;1H'); // move cursor to 0, 2 - term.writeSync('\x1b[2L'); // insert 2 lines + it('should dispose on IL', async () => { + await term.writeP('\x1b[3;1H'); // move cursor to 0, 2 + await term.writeP('\x1b[2L'); // insert 2 lines assert.deepEqual(disposeStack, [markers[4], markers[3]]); assert.deepEqual(markers.map(el => el.line), [0, 1, 4, -1, -1]); }); diff --git a/src/browser/Terminal.ts b/src/browser/Terminal.ts index c8fb9203..44ea9eb0 100644 --- a/src/browser/Terminal.ts +++ b/src/browser/Terminal.ts @@ -162,11 +162,11 @@ export class Terminal extends CoreTerminal implements ITerminal { private _changeAnsiColor(event: IAnsiColorChangeEvent): void { if (!this._colorManager) { return; } - event.colors.forEach(ansiColor => { + for (const ansiColor of event.colors) { const color = rgba.toColor(ansiColor.red, ansiColor.green, ansiColor.blue); this._colorManager!.colors.ansi[ansiColor.colorIndex] = color; - }); + } this._renderService?.setColors(this._colorManager!.colors); this.viewport?.onThemeChange(this._colorManager!.colors); @@ -297,19 +297,26 @@ export class Terminal extends CoreTerminal implements ITerminal { } private _syncTextArea(): void { - if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper!.isComposing) { + if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper!.isComposing || !this._renderService) { return; } - - 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; + const cursorY = this.buffer.ybase + this.buffer.y; + const bufferLine = this.buffer.lines.get(cursorY); + if (!bufferLine) { + return; + } + const cursorX = Math.min(this.buffer.x, this.cols - 1); + const cellHeight = this._renderService.dimensions.actualCellHeight; + const width = bufferLine.getWidth(cursorX); + const cellWidth = this._renderService.dimensions.actualCellWidth * width; + const cursorTop = this.buffer.y * this._renderService.dimensions.actualCellHeight; + const cursorLeft = cursorX * this._renderService.dimensions.actualCellWidth; // Sync the textarea to the exact position of the composition view so the IME knows where the // text is. this.textarea.style.left = cursorLeft + 'px'; this.textarea.style.top = cursorTop + 'px'; - this.textarea.style.width = this._charSizeService!.width + 'px'; + this.textarea.style.width = cellWidth + 'px'; this.textarea.style.height = cellHeight + 'px'; this.textarea.style.lineHeight = cellHeight + 'px'; this.textarea.style.zIndex = '-5'; @@ -386,7 +393,7 @@ export class Terminal extends CoreTerminal implements ITerminal { throw new Error('Terminal requires a parent element.'); } - if (!document.body.contains(parent)) { + if (!parent.isConnected) { this._logService.debug('Terminal.open was called on an element that was not attached to the DOM'); } @@ -438,14 +445,6 @@ export class Terminal extends CoreTerminal implements ITerminal { 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._colorManager = new ColorManager(document, this.options.allowTransparency); this.register(this.optionsService.onOptionChange(e => this._colorManager!.onOptionsChange(e))); @@ -457,6 +456,14 @@ export class Terminal extends CoreTerminal implements ITerminal { this.register(this._renderService.onRenderedBufferChange(e => this._onRender.fire(e))); this.onResize(e => this._renderService!.resize(e.cols, e.rows)); + 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._soundService = this._instantiationService.createInstance(SoundService); this._instantiationService.setService(ISoundService, this._soundService); this._mouseService = this._instantiationService.createInstance(MouseService); @@ -482,7 +489,9 @@ export class Terminal extends CoreTerminal implements ITerminal { this._selectionService = this.register(this._instantiationService.createInstance(SelectionService, this.element, - this.screenElement)); + this.screenElement, + this.linkifier2 + )); this._instantiationService.setService(ISelectionService, this._selectionService); this.register(this._selectionService.onRequestScrollLines(e => this.scrollLines(e.amount, e.suppressScrollEvent))); this.register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire())); @@ -836,7 +845,7 @@ export class Terminal extends CoreTerminal implements ITerminal { * Change the cursor style for different selection modes */ public updateCursorStyle(ev: KeyboardEvent): void { - if (this._selectionService && this._selectionService.shouldColumnSelect(ev)) { + if (this._selectionService?.shouldColumnSelect(ev)) { this.element!.classList.add('column-select'); } else { this.element!.classList.remove('column-select'); diff --git a/src/browser/Terminal2.test.ts b/src/browser/Terminal2.test.ts index 7d3fe851..1ad0e905 100644 --- a/src/browser/Terminal2.test.ts +++ b/src/browser/Terminal2.test.ts @@ -74,7 +74,7 @@ describe('Escape Sequence Files', function(): void { let content = ''; const OSC_CODE = 12345; await new Promise(resolve => { - customHandler = term.addOscHandler(OSC_CODE, () => { + customHandler = term.registerOscHandler(OSC_CODE, () => { // grab terminal viewport content content = terminalToString(term); resolve(); diff --git a/src/browser/TestUtils.test.ts b/src/browser/TestUtils.test.ts index 6a4b4a0d..a2140aa5 100644 --- a/src/browser/TestUtils.test.ts +++ b/src/browser/TestUtils.test.ts @@ -21,6 +21,9 @@ export class TestTerminal extends Terminal { public get curAttrData(): IAttributeData { return (this as any)._inputHandler._curAttrData; } public keyDown(ev: any): boolean | undefined { return this._keyDown(ev); } public keyPress(ev: any): boolean { return this._keyPress(ev); } + public writeP(data: string | Uint8Array): Promise { + return new Promise(r => this.write(data, r)); + } } export class MockTerminal implements ITerminal { @@ -75,16 +78,16 @@ export class MockTerminal implements ITerminal { public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void { throw new Error('Method not implemented.'); } - public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable { + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable { throw new Error('Method not implemented.'); } - public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable { + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable { throw new Error('Method not implemented.'); } - public addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable { + public registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable { throw new Error('Method not implemented.'); } - public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable { + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { throw new Error('Method not implemented.'); } public registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => boolean | void, options?: ILinkMatcherOptions): number { diff --git a/src/browser/Types.d.ts b/src/browser/Types.d.ts index e8e0cabd..f743934e 100644 --- a/src/browser/Types.d.ts +++ b/src/browser/Types.d.ts @@ -52,10 +52,10 @@ export interface IPublicTerminal extends IDisposable { 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; + registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable; + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable; + registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable; + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable; registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number; deregisterLinkMatcher(matcherId: number): void; registerLinkProvider(linkProvider: ILinkProvider): IDisposable; @@ -205,9 +205,19 @@ export interface ILinkifier { deregisterLinkMatcher(matcherId: number): boolean; } +interface ILinkState { + decorations: ILinkDecorations; + isHovered: boolean; +} +export interface ILinkWithState { + link: ILink; + state?: ILinkState; +} + export interface ILinkifier2 { onShowLinkUnderline: IEvent; onHideLinkUnderline: IEvent; + readonly currentLink: ILinkWithState | undefined; attachToDom(element: HTMLElement, mouseService: IMouseService, renderService: IRenderService): void; registerLinkProvider(linkProvider: ILinkProvider): IDisposable; diff --git a/src/browser/input/CompositionHelper.test.ts b/src/browser/input/CompositionHelper.test.ts index b9a4f668..c722570b 100644 --- a/src/browser/input/CompositionHelper.test.ts +++ b/src/browser/input/CompositionHelper.test.ts @@ -5,7 +5,7 @@ import { assert } from 'chai'; import { CompositionHelper } from 'browser/input/CompositionHelper'; -import { MockCharSizeService } from 'browser/TestUtils.test'; +import { MockRenderService } from 'browser/TestUtils.test'; import { MockCoreService, MockBufferService, MockOptionsService } from 'common/TestUtils.test'; describe('CompositionHelper', () => { @@ -42,7 +42,7 @@ describe('CompositionHelper', () => { }; handledText = ''; const bufferService = new MockBufferService(10, 5); - compositionHelper = new CompositionHelper(textarea, compositionView, bufferService, new MockOptionsService(), new MockCharSizeService(10, 10), coreService); + compositionHelper = new CompositionHelper(textarea, compositionView, bufferService, new MockOptionsService(), coreService, new MockRenderService()); }); describe('Input', () => { diff --git a/src/browser/input/CompositionHelper.ts b/src/browser/input/CompositionHelper.ts index f93483d3..8a204831 100644 --- a/src/browser/input/CompositionHelper.ts +++ b/src/browser/input/CompositionHelper.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { ICharSizeService } from 'browser/services/Services'; +import { IRenderService } from 'browser/services/Services'; import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services'; interface IPosition { @@ -45,8 +45,8 @@ export class CompositionHelper { private readonly _compositionView: HTMLElement, @IBufferService private readonly _bufferService: IBufferService, @IOptionsService private readonly _optionsService: IOptionsService, - @ICharSizeService private readonly _charSizeService: ICharSizeService, - @ICoreService private readonly _coreService: ICoreService + @ICoreService private readonly _coreService: ICoreService, + @IRenderService private readonly _renderService: IRenderService ) { this._isComposing = false; this._isSendingComposition = false; @@ -207,9 +207,11 @@ export class CompositionHelper { } 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; + const cursorX = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1); + + const cellHeight = this._renderService.dimensions.actualCellHeight; + const cursorTop = this._bufferService.buffer.y * this._renderService.dimensions.actualCellHeight; + const cursorLeft = cursorX * this._renderService.dimensions.actualCellWidth; this._compositionView.style.left = cursorLeft + 'px'; this._compositionView.style.top = cursorTop + 'px'; @@ -222,8 +224,9 @@ export class CompositionHelper { 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'; + // Ensure the text area is at least 1x1, otherwise certain IMEs may break + this._textarea.style.width = Math.max(compositionViewBounds.width, 1) + 'px'; + this._textarea.style.height = Math.max(compositionViewBounds.height, 1) + 'px'; this._textarea.style.lineHeight = compositionViewBounds.height + 'px'; } diff --git a/src/browser/public/Terminal.ts b/src/browser/public/Terminal.ts index 70247f88..bd0b78f9 100644 --- a/src/browser/public/Terminal.ts +++ b/src/browser/public/Terminal.ts @@ -292,28 +292,28 @@ class BufferLineApiView implements IBufferLineApi { class ParserApi implements IParser { constructor(private _core: ITerminal) { } - public registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable { - return this._core.addCsiHandler(id, (params: IParams) => callback(params.toArray())); + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable { + return this._core.registerCsiHandler(id, (params: IParams) => callback(params.toArray())); } - public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable { + public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable { return this.registerCsiHandler(id, callback); } - public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable { - return this._core.addDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray())); + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable { + return this._core.registerDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray())); } - public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable { + public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable { return this.registerDcsHandler(id, callback); } - public registerEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable { - return this._core.addEscHandler(id, handler); + public registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable { + return this._core.registerEscHandler(id, handler); } - public addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable { + public addEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable { return this.registerEscHandler(id, handler); } - public registerOscHandler(ident: number, callback: (data: string) => boolean): IDisposable { - return this._core.addOscHandler(ident, callback); + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { + return this._core.registerOscHandler(ident, callback); } - public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable { + public addOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { return this.registerOscHandler(ident, callback); } } diff --git a/src/browser/services/RenderService.ts b/src/browser/services/RenderService.ts index 174a1272..51971091 100644 --- a/src/browser/services/RenderService.ts +++ b/src/browser/services/RenderService.ts @@ -174,6 +174,10 @@ export class RenderService extends Disposable implements IRenderService { } public onDevicePixelRatioChange(): void { + // Force char size measurement as DomMeasureStrategy(getBoundingClientRect) is not stable + // when devicePixelRatio changes + this._charSizeService.measure(); + this._renderer.onDevicePixelRatioChange(); this.refreshRows(0, this._rowCount - 1); } diff --git a/src/browser/services/SelectionService.test.ts b/src/browser/services/SelectionService.test.ts index eb90ba44..514d5803 100644 --- a/src/browser/services/SelectionService.test.ts +++ b/src/browser/services/SelectionService.test.ts @@ -21,7 +21,7 @@ class TestSelectionService extends SelectionService { optionsService: IOptionsService, renderService: IRenderService ) { - super(null!, null!, bufferService, new MockCoreService(), new MockMouseService(), optionsService, renderService); + super(null!, null!, null!, bufferService, new MockCoreService(), new MockMouseService(), optionsService, renderService); } public get model(): SelectionModel { return this._model; } diff --git a/src/browser/services/SelectionService.ts b/src/browser/services/SelectionService.ts index a3d8d12c..4806ef91 100644 --- a/src/browser/services/SelectionService.ts +++ b/src/browser/services/SelectionService.ts @@ -11,6 +11,7 @@ import { SelectionModel } from 'browser/selection/SelectionModel'; import { CellData } from 'common/buffer/CellData'; import { EventEmitter, IEvent } from 'common/EventEmitter'; import { ICharSizeService, IMouseService, ISelectionService, IRenderService } from 'browser/services/Services'; +import { ILinkifier2 } from 'browser/Types'; import { IBufferService, IOptionsService, ICoreService } from 'common/services/Services'; import { getCoordsRelativeToElement } from 'browser/input/Mouse'; import { moveToCellSequence } from 'browser/input/MoveToCell'; @@ -105,6 +106,9 @@ export class SelectionService extends Disposable implements ISelectionService { private _workCell: CellData = new CellData(); private _mouseDownTimeStamp: number = 0; + private _oldHasSelection: boolean = false; + private _oldSelectionStart: [number, number] | undefined = undefined; + private _oldSelectionEnd: [number, number] | undefined = undefined; private _onLinuxMouseSelection = this.register(new EventEmitter()); public get onLinuxMouseSelection(): IEvent { return this._onLinuxMouseSelection.event; } @@ -118,6 +122,7 @@ export class SelectionService extends Disposable implements ISelectionService { constructor( private readonly _element: HTMLElement, private readonly _screenElement: HTMLElement, + private readonly _linkifier: ILinkifier2, @IBufferService private readonly _bufferService: IBufferService, @ICoreService private readonly _coreService: ICoreService, @IMouseService private readonly _mouseService: IMouseService, @@ -290,7 +295,7 @@ export class SelectionService extends Disposable implements ISelectionService { * Checks if the current click was inside the current selection * @param event The mouse event */ - public isClickInSelection(event: MouseEvent): boolean { + private _isClickInSelection(event: MouseEvent): boolean { const coords = this._getMouseBufferCoords(event); const start = this._model.finalSelectionStart; const end = this._model.finalSelectionEnd; @@ -313,13 +318,22 @@ export class SelectionService extends Disposable implements ISelectionService { * Selects word at the current mouse event coordinates. * @param event The mouse event. */ - public selectWordAtCursor(event: MouseEvent): void { + private _selectWordAtCursor(event: MouseEvent, allowWhitespaceOnlySelection: boolean): boolean { + // Check if there is a link under the cursor first and select that if so + const range = this._linkifier.currentLink?.link?.range; + if (range) { + this._model.selectionStart = [range.start.x - 1, range.start.y - 1]; + this._model.selectionEnd = [range.end.x, range.end.y - 1]; + return true; + } + const coords = this._getMouseBufferCoords(event); if (coords) { - this._selectWordAt(coords, false); + this._selectWordAt(coords, allowWhitespaceOnlySelection); this._model.selectionEnd = undefined; - this.refresh(true); + return true; } + return false; } /** @@ -524,14 +538,12 @@ export class SelectionService extends Disposable implements ISelectionService { } /** - * Performs a double click, selecting the current work. + * Performs a double click, selecting the current word. * @param event The mouse event. */ private _onDoubleClick(event: MouseEvent): void { - const coords = this._getMouseBufferCoords(event); - if (coords) { + if (this._selectWordAtCursor(event, true)) { this._activeSelectionMode = SelectionMode.WORD; - this._selectWordAt(coords, true); } } @@ -681,11 +693,43 @@ export class SelectionService extends Disposable implements ISelectionService { this._coreService.triggerDataEvent(sequence, true); } } - } else if (this.hasSelection) { - this._onSelectionChange.fire(); + } else { + this._fireEventIfSelectionChanged(); } } + private _fireEventIfSelectionChanged(): void { + const start = this._model.finalSelectionStart; + const end = this._model.finalSelectionEnd; + const hasSelection = !!start && !!end && (start[0] !== end[0] || start[1] !== end[1]); + + if (!hasSelection) { + if (this._oldHasSelection) { + this._fireOnSelectionChange(start, end, hasSelection); + } + return; + } + + // Sanity check, these should not be undefined as there is a selection + if (!start || !end) { + return; + } + + if (!this._oldSelectionStart || !this._oldSelectionEnd || ( + start[0] !== this._oldSelectionStart[0] || start[1] !== this._oldSelectionStart[1] || + end[0] !== this._oldSelectionEnd[0] || end[1] !== this._oldSelectionEnd[1])) { + + this._fireOnSelectionChange(start, end, hasSelection); + } + } + + private _fireOnSelectionChange(start: [number, number] | undefined, end: [number, number] | undefined, hasSelection: boolean): void { + this._oldSelectionStart = start; + this._oldSelectionEnd = end; + this._oldHasSelection = 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 @@ -727,6 +771,15 @@ export class SelectionService extends Disposable implements ISelectionService { this.refresh(); } + public rightClickSelect(ev: MouseEvent): void { + if (!this._isClickInSelection(ev)) { + if (this._selectWordAtCursor(ev, false)) { + this.refresh(true); + } + this._fireEventIfSelectionChanged(); + } + } + /** * Gets positional information for the word at the coordinated specified. * @param coords The coordinates to get the word at. diff --git a/src/browser/services/Services.ts b/src/browser/services/Services.ts index 1c71d387..f06e320b 100644 --- a/src/browser/services/Services.ts +++ b/src/browser/services/Services.ts @@ -91,8 +91,7 @@ export interface ISelectionService { selectAll(): void; selectLines(start: number, end: number): void; clearSelection(): void; - isClickInSelection(event: MouseEvent): boolean; - selectWordAtCursor(event: MouseEvent): void; + rightClickSelect(event: MouseEvent): void; shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean; shouldForceSelection(event: MouseEvent): boolean; refresh(isLinuxMouseSelection?: boolean): void; diff --git a/src/common/Clone.test.ts b/src/common/Clone.test.ts index 370538ea..5fbe4bf9 100644 --- a/src/common/Clone.test.ts +++ b/src/common/Clone.test.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { assert, expect } from 'chai'; +import { assert } from 'chai'; import { clone } from 'common/Clone'; describe('clone', () => { @@ -124,6 +124,6 @@ describe('clone', () => { test.a.b.c = test; - expect(() => clone(test)).to.not.throw(); + assert.doesNotThrow(() => clone(test)); }); }); diff --git a/src/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index 86492ab3..253cd4c1 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -22,7 +22,7 @@ */ import { Disposable } from 'common/Lifecycle'; -import { IInstantiationService, IOptionsService, IBufferService, ILogService, ICharsetService, ICoreService, ICoreMouseService, IUnicodeService, IDirtyRowService } from 'common/services/Services'; +import { IInstantiationService, IOptionsService, IBufferService, ILogService, ICharsetService, ICoreService, ICoreMouseService, IUnicodeService, IDirtyRowService, LogLevelEnum } from 'common/services/Services'; import { InstantiationService } from 'common/services/InstantiationService'; import { LogService } from 'common/services/LogService'; import { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService'; @@ -40,6 +40,9 @@ import { IBufferSet } from 'common/buffer/Types'; import { InputHandler } from 'common/InputHandler'; import { WriteBuffer } from 'common/input/WriteBuffer'; +// Only trigger this warning a single time per session +let hasWriteSyncWarnHappened = false; + export abstract class CoreTerminal extends Disposable implements ICoreTerminal { protected readonly _instantiationService: IInstantiationService; protected readonly _bufferService: IBufferService; @@ -113,7 +116,7 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { this.register(this.optionsService.onOptionChange(key => this._updateOptions(key))); // Setup WriteBuffer - this._writeBuffer = new WriteBuffer(data => this._inputHandler.parse(data)); + this._writeBuffer = new WriteBuffer((data, promiseResult) => this._inputHandler.parse(data, promiseResult)); } public dispose(): void { @@ -129,8 +132,21 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { this._writeBuffer.write(data, callback); } - public writeSync(data: string | Uint8Array): void { - this._writeBuffer.writeSync(data); + /** + * Write data to terminal synchonously. + * + * This method is unreliable with async parser handlers, thus should not + * be used anymore. If you need blocking semantics on data input consider + * `write` with a callback instead. + * + * @deprecated Unreliable, will be removed soon. + */ + public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void { + if (this._logService.logLevel <= LogLevelEnum.WARN && !hasWriteSyncWarnHappened) { + this._logService.warn('writeSync is unreliable and will be removed soon.'); + hasWriteSyncWarnHappened = true; + } + this._writeBuffer.writeSync(data, maxSubsequentCalls); } public resize(x: number, y: number): void { @@ -282,23 +298,23 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { } /** 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); + public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable { + return this._inputHandler.registerEscHandler(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); + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable { + return this._inputHandler.registerDcsHandler(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); + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable { + return this._inputHandler.registerCsiHandler(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); + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { + return this._inputHandler.registerOscHandler(ident, callback); } protected _setup(): void { @@ -336,7 +352,7 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { if (!this._windowsMode) { const disposables: IDisposable[] = []; disposables.push(this.onLineFeed(updateWindowsModeWrappedState.bind(null, this._bufferService))); - disposables.push(this.addCsiHandler({ final: 'H' }, () => { + disposables.push(this.registerCsiHandler({ final: 'H' }, () => { updateWindowsModeWrappedState(this._bufferService); return false; })); diff --git a/src/common/InputHandler.test.ts b/src/common/InputHandler.test.ts index 4c0d8559..b5067193 100644 --- a/src/common/InputHandler.test.ts +++ b/src/common/InputHandler.test.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { assert, expect } from 'chai'; +import { assert } from 'chai'; import { InputHandler } from 'common/InputHandler'; import { IBufferLine, IAttributeData, IAnsiColorChangeEvent } from 'common/Types'; import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine'; @@ -17,6 +17,7 @@ import { DEFAULT_OPTIONS } from 'common/services/OptionsService'; import { clone } from 'common/Clone'; import { BufferService } from 'common/services/BufferService'; import { CoreService } from 'common/services/CoreService'; +import { OscHandler } from 'common/parser/OscParser'; function getCursor(bufferService: IBufferService): number[] { return [ @@ -41,6 +42,18 @@ class TestInputHandler extends InputHandler { public get windowTitleStack(): string[] { return this._windowTitleStack; } public get iconNameStack(): string[] { return this._iconNameStack; } public parseAnsiColorChange(data: string): IAnsiColorChangeEvent | null { return this._parseAnsiColorChange(data); } + + /** + * Promise based parse call to await the full resolve of given input data. + * This is useful to test async handlers in inputhandler directly. + */ + public async parseP(data: string | Uint8Array): Promise { + let result: Promise | void; + let prev: boolean | undefined; + while (result = this.parse(data, prev)) { + prev = await result; + } + } } describe('InputHandler', () => { @@ -118,7 +131,7 @@ describe('InputHandler', () => { describe('setMode', () => { it('should toggle bracketedPasteMode', () => { const coreService = new MockCoreService(); - const inputHandler = new InputHandler(new MockBufferService(80, 30), new MockCharsetService(), coreService, new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); + const inputHandler = new TestInputHandler(new MockBufferService(80, 30), new MockCharsetService(), coreService, new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); // Set bracketed paste mode inputHandler.setModePrivate(Params.fromArray([2004])); assert.equal(coreService.decPrivateModes.bracketedPasteMode, true); @@ -134,123 +147,160 @@ describe('InputHandler', () => { return result; } - it('insertChars', function(): void { + it('insertChars', async () => { const bufferService = new MockBufferService(80, 30); - const inputHandler = new InputHandler(bufferService, new MockCharsetService(), new MockCoreService(), new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); + const inputHandler = new TestInputHandler( + bufferService, + new MockCharsetService(), + new MockCoreService(), + new MockDirtyRowService(), + new MockLogService(), + new MockOptionsService(), + new MockCoreMouseService(), + new MockUnicodeService() + ); // insert some data in first and second line - inputHandler.parse(Array(bufferService.cols - 9).join('a')); - inputHandler.parse('1234567890'); - inputHandler.parse(Array(bufferService.cols - 9).join('a')); - inputHandler.parse('1234567890'); + await inputHandler.parseP(Array(bufferService.cols - 9).join('a')); + await inputHandler.parseP('1234567890'); + await inputHandler.parseP(Array(bufferService.cols - 9).join('a')); + await inputHandler.parseP('1234567890'); const line1: IBufferLine = bufferService.buffer.lines.get(0)!; - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + '1234567890'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + '1234567890'); // insert one char from params = [0] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.insertChars(Params.fromArray([0])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + ' 123456789'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + ' 123456789'); // insert one char from params = [1] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.insertChars(Params.fromArray([1])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + ' 12345678'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + ' 12345678'); // insert two chars from params = [2] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.insertChars(Params.fromArray([2])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + ' 123456'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + ' 123456'); // insert 10 chars from params = [10] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.insertChars(Params.fromArray([10])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + ' '); - expect(line1.translateToString(true)).equals(Array(bufferService.cols - 9).join('a')); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + ' '); + assert.equal(line1.translateToString(true), Array(bufferService.cols - 9).join('a')); }); - it('deleteChars', function(): void { + it('deleteChars', async () => { const bufferService = new MockBufferService(80, 30); - const inputHandler = new InputHandler(bufferService, new MockCharsetService(), new MockCoreService(), new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); + const inputHandler = new TestInputHandler( + bufferService, + new MockCharsetService(), + new MockCoreService(), + new MockDirtyRowService(), + new MockLogService(), + new MockOptionsService(), + new MockCoreMouseService(), + new MockUnicodeService() + ); // insert some data in first and second line - inputHandler.parse(Array(bufferService.cols - 9).join('a')); - inputHandler.parse('1234567890'); - inputHandler.parse(Array(bufferService.cols - 9).join('a')); - inputHandler.parse('1234567890'); + await inputHandler.parseP(Array(bufferService.cols - 9).join('a')); + await inputHandler.parseP('1234567890'); + await inputHandler.parseP(Array(bufferService.cols - 9).join('a')); + await inputHandler.parseP('1234567890'); const line1: IBufferLine = bufferService.buffer.lines.get(0)!; - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + '1234567890'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + '1234567890'); // delete one char from params = [0] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.deleteChars(Params.fromArray([0])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + '234567890 '); - expect(line1.translateToString(true)).equals(Array(bufferService.cols - 9).join('a') + '234567890'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + '234567890 '); + assert.equal(line1.translateToString(true), Array(bufferService.cols - 9).join('a') + '234567890'); // insert one char from params = [1] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.deleteChars(Params.fromArray([1])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + '34567890 '); - expect(line1.translateToString(true)).equals(Array(bufferService.cols - 9).join('a') + '34567890'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + '34567890 '); + assert.equal(line1.translateToString(true), Array(bufferService.cols - 9).join('a') + '34567890'); // insert two chars from params = [2] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.deleteChars(Params.fromArray([2])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + '567890 '); - expect(line1.translateToString(true)).equals(Array(bufferService.cols - 9).join('a') + '567890'); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + '567890 '); + assert.equal(line1.translateToString(true), Array(bufferService.cols - 9).join('a') + '567890'); + // insert 10 chars from params = [10] bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.deleteChars(Params.fromArray([10])); - expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + ' '); - expect(line1.translateToString(true)).equals(Array(bufferService.cols - 9).join('a')); + assert.equal(line1.translateToString(false), Array(bufferService.cols - 9).join('a') + ' '); + assert.equal(line1.translateToString(true), Array(bufferService.cols - 9).join('a')); }); - it('eraseInLine', function(): void { + it('eraseInLine', async () => { const bufferService = new MockBufferService(80, 30); - const inputHandler = new InputHandler(bufferService, new MockCharsetService(), new MockCoreService(), new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); + const inputHandler = new TestInputHandler( + bufferService, + new MockCharsetService(), + new MockCoreService(), + new MockDirtyRowService(), + new MockLogService(), + new MockOptionsService(), + new MockCoreMouseService(), + new MockUnicodeService() + ); // fill 6 lines to test 3 different states - inputHandler.parse(Array(bufferService.cols + 1).join('a')); - inputHandler.parse(Array(bufferService.cols + 1).join('a')); - inputHandler.parse(Array(bufferService.cols + 1).join('a')); + await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); + await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); + await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // params[0] - right erase bufferService.buffer.y = 0; bufferService.buffer.x = 70; inputHandler.eraseInLine(Params.fromArray([0])); - expect(bufferService.buffer.lines.get(0)!.translateToString(false)).equals(Array(71).join('a') + ' '); + assert.equal(bufferService.buffer.lines.get(0)!.translateToString(false), Array(71).join('a') + ' '); // params[1] - left erase bufferService.buffer.y = 1; bufferService.buffer.x = 70; inputHandler.eraseInLine(Params.fromArray([1])); - expect(bufferService.buffer.lines.get(1)!.translateToString(false)).equals(Array(71).join(' ') + ' aaaaaaaaa'); + assert.equal(bufferService.buffer.lines.get(1)!.translateToString(false), Array(71).join(' ') + ' aaaaaaaaa'); // params[1] - left erase bufferService.buffer.y = 2; bufferService.buffer.x = 70; inputHandler.eraseInLine(Params.fromArray([2])); - expect(bufferService.buffer.lines.get(2)!.translateToString(false)).equals(Array(bufferService.cols + 1).join(' ')); + assert.equal(bufferService.buffer.lines.get(2)!.translateToString(false), Array(bufferService.cols + 1).join(' ')); }); - it('eraseInDisplay', function(): void { + it('eraseInDisplay', async () => { const bufferService = new MockBufferService(80, 7); - const inputHandler = new InputHandler(bufferService, new MockCharsetService(), new MockCoreService(), new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); + const inputHandler = new TestInputHandler( + bufferService, + new MockCharsetService(), + new MockCoreService(), + new MockDirtyRowService(), + new MockLogService(), + new MockOptionsService(), + new MockCoreMouseService(), + new MockUnicodeService() + ); // fill display with a's - for (let i = 0; i < bufferService.rows; ++i) inputHandler.parse(Array(bufferService.cols + 1).join('a')); + for (let i = 0; i < bufferService.rows; ++i) await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // params [0] - right and below erase bufferService.buffer.y = 5; bufferService.buffer.x = 40; inputHandler.eraseInDisplay(Params.fromArray([0])); - expect(termContent(bufferService, false)).eql([ + assert.deepEqual(termContent(bufferService, false), [ Array(bufferService.cols + 1).join('a'), Array(bufferService.cols + 1).join('a'), Array(bufferService.cols + 1).join('a'), @@ -259,7 +309,7 @@ describe('InputHandler', () => { Array(40 + 1).join('a') + Array(bufferService.cols - 40 + 1).join(' '), Array(bufferService.cols + 1).join(' ') ]); - expect(termContent(bufferService, true)).eql([ + assert.deepEqual(termContent(bufferService, true), [ Array(bufferService.cols + 1).join('a'), Array(bufferService.cols + 1).join('a'), Array(bufferService.cols + 1).join('a'), @@ -272,13 +322,13 @@ describe('InputHandler', () => { // reset bufferService.buffer.y = 0; bufferService.buffer.x = 0; - for (let i = 0; i < bufferService.rows; ++i) inputHandler.parse(Array(bufferService.cols + 1).join('a')); + for (let i = 0; i < bufferService.rows; ++i) await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // params [1] - left and above bufferService.buffer.y = 5; bufferService.buffer.x = 40; inputHandler.eraseInDisplay(Params.fromArray([1])); - expect(termContent(bufferService, false)).eql([ + assert.deepEqual(termContent(bufferService, false), [ Array(bufferService.cols + 1).join(' '), Array(bufferService.cols + 1).join(' '), Array(bufferService.cols + 1).join(' '), @@ -287,7 +337,7 @@ describe('InputHandler', () => { Array(41 + 1).join(' ') + Array(bufferService.cols - 41 + 1).join('a'), Array(bufferService.cols + 1).join('a') ]); - expect(termContent(bufferService, true)).eql([ + assert.deepEqual(termContent(bufferService, true), [ '', '', '', @@ -300,13 +350,13 @@ describe('InputHandler', () => { // reset bufferService.buffer.y = 0; bufferService.buffer.x = 0; - for (let i = 0; i < bufferService.rows; ++i) inputHandler.parse(Array(bufferService.cols + 1).join('a')); + for (let i = 0; i < bufferService.rows; ++i) await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // params [2] - whole screen bufferService.buffer.y = 5; bufferService.buffer.x = 40; inputHandler.eraseInDisplay(Params.fromArray([2])); - expect(termContent(bufferService, false)).eql([ + assert.deepEqual(termContent(bufferService, false), [ Array(bufferService.cols + 1).join(' '), Array(bufferService.cols + 1).join(' '), Array(bufferService.cols + 1).join(' '), @@ -315,7 +365,7 @@ describe('InputHandler', () => { Array(bufferService.cols + 1).join(' '), Array(bufferService.cols + 1).join(' ') ]); - expect(termContent(bufferService, true)).eql([ + assert.deepEqual(termContent(bufferService, true), [ '', '', '', @@ -328,242 +378,251 @@ describe('InputHandler', () => { // reset and add a wrapped line bufferService.buffer.y = 0; bufferService.buffer.x = 0; - inputHandler.parse(Array(bufferService.cols + 1).join('a')); // line 0 - inputHandler.parse(Array(bufferService.cols + 10).join('a')); // line 1 and 2 - for (let i = 3; i < bufferService.rows; ++i) inputHandler.parse(Array(bufferService.cols + 1).join('a')); + await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // line 0 + await inputHandler.parseP(Array(bufferService.cols + 10).join('a')); // line 1 and 2 + for (let i = 3; i < bufferService.rows; ++i) await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // params[1] left and above with wrap // confirm precondition that line 2 is wrapped - expect(bufferService.buffer.lines.get(2)!.isWrapped).true; + assert.equal(bufferService.buffer.lines.get(2)!.isWrapped, true); bufferService.buffer.y = 2; bufferService.buffer.x = 40; inputHandler.eraseInDisplay(Params.fromArray([1])); - expect(bufferService.buffer.lines.get(2)!.isWrapped).false; + assert.equal(bufferService.buffer.lines.get(2)!.isWrapped, false); // reset and add a wrapped line bufferService.buffer.y = 0; bufferService.buffer.x = 0; - inputHandler.parse(Array(bufferService.cols + 1).join('a')); // line 0 - inputHandler.parse(Array(bufferService.cols + 10).join('a')); // line 1 and 2 - for (let i = 3; i < bufferService.rows; ++i) inputHandler.parse(Array(bufferService.cols + 1).join('a')); + await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // line 0 + await inputHandler.parseP(Array(bufferService.cols + 10).join('a')); // line 1 and 2 + for (let i = 3; i < bufferService.rows; ++i) await inputHandler.parseP(Array(bufferService.cols + 1).join('a')); // params[1] left and above with wrap // confirm precondition that line 2 is wrapped - expect(bufferService.buffer.lines.get(2)!.isWrapped).true; + assert.equal(bufferService.buffer.lines.get(2)!.isWrapped, true); bufferService.buffer.y = 1; bufferService.buffer.x = 90; // Cursor is beyond last column inputHandler.eraseInDisplay(Params.fromArray([1])); - expect(bufferService.buffer.lines.get(2)!.isWrapped).false; + assert.equal(bufferService.buffer.lines.get(2)!.isWrapped, false); }); }); describe('print', () => { it('should not cause an infinite loop (regression test)', () => { - const inputHandler = new InputHandler(new MockBufferService(80, 30), new MockCharsetService(), new MockCoreService(), new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); + const inputHandler = new TestInputHandler( + new MockBufferService(80, 30), + new MockCharsetService(), + new MockCoreService(), + new MockDirtyRowService(), + new MockLogService(), + new MockOptionsService(), + new MockCoreMouseService(), + new MockUnicodeService() + ); const container = new Uint32Array(10); container[0] = 0x200B; inputHandler.print(container, 0, 1); }); - it('should clear cells to the right on early wrap-around', () => { + it('should clear cells to the right on early wrap-around', async () => { bufferService.resize(5, 5); optionsService.options.scrollback = 1; - inputHandler.parse('12345'); + await inputHandler.parseP('12345'); bufferService.buffer.x = 0; - inputHandler.parse('¥¥¥'); + await inputHandler.parseP('¥¥¥'); assert.deepEqual(getLines(bufferService, 2), ['¥¥', '¥']); }); }); describe('alt screen', () => { let bufferService: IBufferService; - let handler: InputHandler; + let handler: TestInputHandler; beforeEach(() => { bufferService = new MockBufferService(80, 30); - handler = new InputHandler(bufferService, new MockCharsetService(), new MockCoreService(), new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); + handler = new TestInputHandler(bufferService, new MockCharsetService(), new MockCoreService(), new MockDirtyRowService(), new MockLogService(), new MockOptionsService(), new MockCoreMouseService(), new MockUnicodeService()); }); - it('should handle DECSET/DECRST 47 (alt screen buffer)', () => { - handler.parse('\x1b[?47h\r\n\x1b[31mJUNK\x1b[?47lTEST'); - expect(bufferService.buffer.translateBufferLineToString(0, true)).to.equal(''); - expect(bufferService.buffer.translateBufferLineToString(1, true)).to.equal(' TEST'); + it('should handle DECSET/DECRST 47 (alt screen buffer)', async () => { + await handler.parseP('\x1b[?47h\r\n\x1b[31mJUNK\x1b[?47lTEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(0, true), ''); + assert.equal(bufferService.buffer.translateBufferLineToString(1, true), ' TEST'); // Text color of 'TEST' should be red - expect((bufferService.buffer.lines.get(1)!.loadCell(4, new CellData()).getFgColor())).to.equal(1); + assert.equal((bufferService.buffer.lines.get(1)!.loadCell(4, new CellData()).getFgColor()), 1); }); - it('should handle DECSET/DECRST 1047 (alt screen buffer)', () => { - handler.parse('\x1b[?1047h\r\n\x1b[31mJUNK\x1b[?1047lTEST'); - expect(bufferService.buffer.translateBufferLineToString(0, true)).to.equal(''); - expect(bufferService.buffer.translateBufferLineToString(1, true)).to.equal(' TEST'); + it('should handle DECSET/DECRST 1047 (alt screen buffer)', async () => { + await handler.parseP('\x1b[?1047h\r\n\x1b[31mJUNK\x1b[?1047lTEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(0, true), ''); + assert.equal(bufferService.buffer.translateBufferLineToString(1, true), ' TEST'); // Text color of 'TEST' should be red - expect((bufferService.buffer.lines.get(1)!.loadCell(4, new CellData()).getFgColor())).to.equal(1); + assert.equal((bufferService.buffer.lines.get(1)!.loadCell(4, new CellData()).getFgColor()), 1); }); - it('should handle DECSET/DECRST 1048 (alt screen cursor)', () => { - handler.parse('\x1b[?1048h\r\n\x1b[31mJUNK\x1b[?1048lTEST'); - expect(bufferService.buffer.translateBufferLineToString(0, true)).to.equal('TEST'); - expect(bufferService.buffer.translateBufferLineToString(1, true)).to.equal('JUNK'); + it('should handle DECSET/DECRST 1048 (alt screen cursor)', async () => { + await handler.parseP('\x1b[?1048h\r\n\x1b[31mJUNK\x1b[?1048lTEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(0, true), 'TEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(1, true), 'JUNK'); // Text color of 'TEST' should be default - expect(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg).to.equal(DEFAULT_ATTR_DATA.fg); + assert.equal(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg, DEFAULT_ATTR_DATA.fg); // Text color of 'JUNK' should be red - expect((bufferService.buffer.lines.get(1)!.loadCell(0, new CellData()).getFgColor())).to.equal(1); + assert.equal((bufferService.buffer.lines.get(1)!.loadCell(0, new CellData()).getFgColor()), 1); }); - it('should handle DECSET/DECRST 1049 (alt screen buffer+cursor)', () => { - handler.parse('\x1b[?1049h\r\n\x1b[31mJUNK\x1b[?1049lTEST'); - expect(bufferService.buffer.translateBufferLineToString(0, true)).to.equal('TEST'); - expect(bufferService.buffer.translateBufferLineToString(1, true)).to.equal(''); + it('should handle DECSET/DECRST 1049 (alt screen buffer+cursor)', async () => { + await handler.parseP('\x1b[?1049h\r\n\x1b[31mJUNK\x1b[?1049lTEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(0, true), 'TEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(1, true), ''); // Text color of 'TEST' should be default - expect(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg).to.equal(DEFAULT_ATTR_DATA.fg); + assert.equal(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg, DEFAULT_ATTR_DATA.fg); }); - it('should handle DECSET/DECRST 1049 - maintains saved cursor for alt buffer', () => { - handler.parse('\x1b[?1049h\r\n\x1b[31m\x1b[s\x1b[?1049lTEST'); - expect(bufferService.buffer.translateBufferLineToString(0, true)).to.equal('TEST'); + it('should handle DECSET/DECRST 1049 - maintains saved cursor for alt buffer', async () => { + await handler.parseP('\x1b[?1049h\r\n\x1b[31m\x1b[s\x1b[?1049lTEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(0, true), 'TEST'); // Text color of 'TEST' should be default - expect(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg).to.equal(DEFAULT_ATTR_DATA.fg); - handler.parse('\x1b[?1049h\x1b[uTEST'); - expect(bufferService.buffer.translateBufferLineToString(1, true)).to.equal('TEST'); + assert.equal(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg, DEFAULT_ATTR_DATA.fg); + await handler.parseP('\x1b[?1049h\x1b[uTEST'); + assert.equal(bufferService.buffer.translateBufferLineToString(1, true), 'TEST'); // Text color of 'TEST' should be red - expect((bufferService.buffer.lines.get(1)!.loadCell(0, new CellData()).getFgColor())).to.equal(1); + assert.equal((bufferService.buffer.lines.get(1)!.loadCell(0, new CellData()).getFgColor()), 1); }); - it('should handle DECSET/DECRST 1049 - clears alt buffer with erase attributes', () => { - handler.parse('\x1b[42m\x1b[?1049h'); + it('should handle DECSET/DECRST 1049 - clears alt buffer with erase attributes', async () => { + await handler.parseP('\x1b[42m\x1b[?1049h'); // Buffer should be filled with green background - expect(bufferService.buffer.lines.get(20)!.loadCell(10, new CellData()).getBgColor()).to.equal(2); + assert.equal(bufferService.buffer.lines.get(20)!.loadCell(10, new CellData()).getBgColor(), 2); }); }); describe('text attributes', () => { - it('bold', () => { - inputHandler.parse('\x1b[1m'); + it('bold', async () => { + await inputHandler.parseP('\x1b[1m'); assert.equal(!!inputHandler.curAttrData.isBold(), true); - inputHandler.parse('\x1b[22m'); + await inputHandler.parseP('\x1b[22m'); assert.equal(!!inputHandler.curAttrData.isBold(), false); }); - it('dim', () => { - inputHandler.parse('\x1b[2m'); + it('dim', async () => { + await inputHandler.parseP('\x1b[2m'); assert.equal(!!inputHandler.curAttrData.isDim(), true); - inputHandler.parse('\x1b[22m'); + await inputHandler.parseP('\x1b[22m'); assert.equal(!!inputHandler.curAttrData.isDim(), false); }); - it('italic', () => { - inputHandler.parse('\x1b[3m'); + it('italic', async () => { + await inputHandler.parseP('\x1b[3m'); assert.equal(!!inputHandler.curAttrData.isItalic(), true); - inputHandler.parse('\x1b[23m'); + await inputHandler.parseP('\x1b[23m'); assert.equal(!!inputHandler.curAttrData.isItalic(), false); }); - it('underline', () => { - inputHandler.parse('\x1b[4m'); + it('underline', async () => { + await inputHandler.parseP('\x1b[4m'); assert.equal(!!inputHandler.curAttrData.isUnderline(), true); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(!!inputHandler.curAttrData.isUnderline(), false); }); - it('blink', () => { - inputHandler.parse('\x1b[5m'); + it('blink', async () => { + await inputHandler.parseP('\x1b[5m'); assert.equal(!!inputHandler.curAttrData.isBlink(), true); - inputHandler.parse('\x1b[25m'); + await inputHandler.parseP('\x1b[25m'); assert.equal(!!inputHandler.curAttrData.isBlink(), false); }); - it('inverse', () => { - inputHandler.parse('\x1b[7m'); + it('inverse', async () => { + await inputHandler.parseP('\x1b[7m'); assert.equal(!!inputHandler.curAttrData.isInverse(), true); - inputHandler.parse('\x1b[27m'); + await inputHandler.parseP('\x1b[27m'); assert.equal(!!inputHandler.curAttrData.isInverse(), false); }); - it('invisible', () => { - inputHandler.parse('\x1b[8m'); + it('invisible', async () => { + await inputHandler.parseP('\x1b[8m'); assert.equal(!!inputHandler.curAttrData.isInvisible(), true); - inputHandler.parse('\x1b[28m'); + await inputHandler.parseP('\x1b[28m'); assert.equal(!!inputHandler.curAttrData.isInvisible(), false); }); - it('colormode palette 16', () => { + it('colormode palette 16', async () => { assert.equal(inputHandler.curAttrData.getFgColorMode(), 0); // DEFAULT assert.equal(inputHandler.curAttrData.getBgColorMode(), 0); // DEFAULT // lower 8 colors for (let i = 0; i < 8; ++i) { - inputHandler.parse(`\x1b[${i + 30};${i + 40}m`); + await inputHandler.parseP(`\x1b[${i + 30};${i + 40}m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), Attributes.CM_P16); assert.equal(inputHandler.curAttrData.getFgColor(), i); assert.equal(inputHandler.curAttrData.getBgColorMode(), Attributes.CM_P16); assert.equal(inputHandler.curAttrData.getBgColor(), i); } // reset to DEFAULT - inputHandler.parse(`\x1b[39;49m`); + await inputHandler.parseP(`\x1b[39;49m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), 0); assert.equal(inputHandler.curAttrData.getBgColorMode(), 0); }); - it('colormode palette 256', () => { + it('colormode palette 256', async () => { assert.equal(inputHandler.curAttrData.getFgColorMode(), 0); // DEFAULT assert.equal(inputHandler.curAttrData.getBgColorMode(), 0); // DEFAULT // lower 8 colors for (let i = 0; i < 256; ++i) { - inputHandler.parse(`\x1b[38;5;${i};48;5;${i}m`); + await inputHandler.parseP(`\x1b[38;5;${i};48;5;${i}m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.getFgColor(), i); assert.equal(inputHandler.curAttrData.getBgColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.getBgColor(), i); } // reset to DEFAULT - inputHandler.parse(`\x1b[39;49m`); + await inputHandler.parseP(`\x1b[39;49m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), 0); assert.equal(inputHandler.curAttrData.getFgColor(), -1); assert.equal(inputHandler.curAttrData.getBgColorMode(), 0); assert.equal(inputHandler.curAttrData.getBgColor(), -1); }); - it('colormode RGB', () => { + it('colormode RGB', async () => { assert.equal(inputHandler.curAttrData.getFgColorMode(), 0); // DEFAULT assert.equal(inputHandler.curAttrData.getBgColorMode(), 0); // DEFAULT - inputHandler.parse(`\x1b[38;2;1;2;3;48;2;4;5;6m`); + await inputHandler.parseP(`\x1b[38;2;1;2;3;48;2;4;5;6m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), Attributes.CM_RGB); assert.equal(inputHandler.curAttrData.getFgColor(), 1 << 16 | 2 << 8 | 3); assert.deepEqual(AttributeData.toColorRGB(inputHandler.curAttrData.getFgColor()), [1, 2, 3]); assert.equal(inputHandler.curAttrData.getBgColorMode(), Attributes.CM_RGB); assert.deepEqual(AttributeData.toColorRGB(inputHandler.curAttrData.getBgColor()), [4, 5, 6]); // reset to DEFAULT - inputHandler.parse(`\x1b[39;49m`); + await inputHandler.parseP(`\x1b[39;49m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), 0); assert.equal(inputHandler.curAttrData.getFgColor(), -1); assert.equal(inputHandler.curAttrData.getBgColorMode(), 0); assert.equal(inputHandler.curAttrData.getBgColor(), -1); }); - it('colormode transition RGB to 256', () => { + it('colormode transition RGB to 256', async () => { // enter RGB for FG and BG - inputHandler.parse(`\x1b[38;2;1;2;3;48;2;4;5;6m`); + await inputHandler.parseP(`\x1b[38;2;1;2;3;48;2;4;5;6m`); // enter 256 for FG and BG - inputHandler.parse(`\x1b[38;5;255;48;5;255m`); + await inputHandler.parseP(`\x1b[38;5;255;48;5;255m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.getFgColor(), 255); assert.equal(inputHandler.curAttrData.getBgColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.getBgColor(), 255); }); - it('colormode transition RGB to 16', () => { + it('colormode transition RGB to 16', async () => { // enter RGB for FG and BG - inputHandler.parse(`\x1b[38;2;1;2;3;48;2;4;5;6m`); + await inputHandler.parseP(`\x1b[38;2;1;2;3;48;2;4;5;6m`); // enter 16 for FG and BG - inputHandler.parse(`\x1b[37;47m`); + await inputHandler.parseP(`\x1b[37;47m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), Attributes.CM_P16); assert.equal(inputHandler.curAttrData.getFgColor(), 7); assert.equal(inputHandler.curAttrData.getBgColorMode(), Attributes.CM_P16); assert.equal(inputHandler.curAttrData.getBgColor(), 7); }); - it('colormode transition 16 to 256', () => { + it('colormode transition 16 to 256', async () => { // enter 16 for FG and BG - inputHandler.parse(`\x1b[37;47m`); + await inputHandler.parseP(`\x1b[37;47m`); // enter 256 for FG and BG - inputHandler.parse(`\x1b[38;5;255;48;5;255m`); + await inputHandler.parseP(`\x1b[38;5;255;48;5;255m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.getFgColor(), 255); assert.equal(inputHandler.curAttrData.getBgColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.getBgColor(), 255); }); - it('colormode transition 256 to 16', () => { + it('colormode transition 256 to 16', async () => { // enter 256 for FG and BG - inputHandler.parse(`\x1b[38;5;255;48;5;255m`); + await inputHandler.parseP(`\x1b[38;5;255;48;5;255m`); // enter 16 for FG and BG - inputHandler.parse(`\x1b[37;47m`); + await inputHandler.parseP(`\x1b[37;47m`); assert.equal(inputHandler.curAttrData.getFgColorMode(), Attributes.CM_P16); assert.equal(inputHandler.curAttrData.getFgColor(), 7); assert.equal(inputHandler.curAttrData.getBgColorMode(), Attributes.CM_P16); assert.equal(inputHandler.curAttrData.getBgColor(), 7); }); - it('should zero missing RGB values', () => { - inputHandler.parse(`\x1b[38;2;1;2;3m`); - inputHandler.parse(`\x1b[38;2;5m`); + it('should zero missing RGB values', async () => { + await inputHandler.parseP(`\x1b[38;2;1;2;3m`); + await inputHandler.parseP(`\x1b[38;2;5m`); assert.deepEqual(AttributeData.toColorRGB(inputHandler.curAttrData.getFgColor()), [5, 0, 0]); }); }); @@ -573,141 +632,141 @@ describe('InputHandler', () => { inputHandler2 = new TestInputHandler(bufferService, new MockCharsetService(), coreService, new MockDirtyRowService(), new MockLogService(), optionsService, new MockCoreMouseService(), new MockUnicodeService()); }); describe('should equal to semicolon', () => { - it('CSI 38:2::50:100:150 m', () => { + it('CSI 38:2::50:100:150 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2;50;100;150m'); - inputHandler.parse('\x1b[38:2::50:100:150m'); + await inputHandler2.parseP('\x1b[38;2;50;100;150m'); + await inputHandler.parseP('\x1b[38:2::50:100:150m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 150); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38:2::50:100: m', () => { + it('CSI 38:2::50:100: m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2;50;100;m'); - inputHandler.parse('\x1b[38:2::50:100:m'); + await inputHandler2.parseP('\x1b[38;2;50;100;m'); + await inputHandler.parseP('\x1b[38:2::50:100:m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38:2::50:: m', () => { + it('CSI 38:2::50:: m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2;50;;m'); - inputHandler.parse('\x1b[38:2::50::m'); + await inputHandler2.parseP('\x1b[38;2;50;;m'); + await inputHandler.parseP('\x1b[38:2::50::m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 0 << 8 | 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38:2:::: m', () => { + it('CSI 38:2:::: m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2;;;m'); - inputHandler.parse('\x1b[38:2::::m'); + await inputHandler2.parseP('\x1b[38;2;;;m'); + await inputHandler.parseP('\x1b[38:2::::m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 0 << 16 | 0 << 8 | 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38;2::50:100:150 m', () => { + it('CSI 38;2::50:100:150 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2;50;100;150m'); - inputHandler.parse('\x1b[38;2::50:100:150m'); + await inputHandler2.parseP('\x1b[38;2;50;100;150m'); + await inputHandler.parseP('\x1b[38;2::50:100:150m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 150); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38;2;50:100:150 m', () => { + it('CSI 38;2;50:100:150 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2;50;100;150m'); - inputHandler.parse('\x1b[38;2;50:100:150m'); + await inputHandler2.parseP('\x1b[38;2;50;100;150m'); + await inputHandler.parseP('\x1b[38;2;50:100:150m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 150); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38;2;50;100:150 m', () => { + it('CSI 38;2;50;100:150 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2;50;100;150m'); - inputHandler.parse('\x1b[38;2;50;100:150m'); + await inputHandler2.parseP('\x1b[38;2;50;100;150m'); + await inputHandler.parseP('\x1b[38;2;50;100:150m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 150); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38:5:50 m', () => { + it('CSI 38:5:50 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;5;50m'); - inputHandler.parse('\x1b[38:5:50m'); + await inputHandler2.parseP('\x1b[38;5;50m'); + await inputHandler.parseP('\x1b[38:5:50m'); assert.equal(inputHandler2.curAttrData.fg & 0xFF, 50); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38:5: m', () => { + it('CSI 38:5: m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;5;m'); - inputHandler.parse('\x1b[38:5:m'); + await inputHandler2.parseP('\x1b[38;5;m'); + await inputHandler.parseP('\x1b[38:5:m'); assert.equal(inputHandler2.curAttrData.fg & 0xFF, 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38;5:50 m', () => { + it('CSI 38;5:50 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;5;50m'); - inputHandler.parse('\x1b[38;5:50m'); + await inputHandler2.parseP('\x1b[38;5;50m'); + await inputHandler.parseP('\x1b[38;5:50m'); assert.equal(inputHandler2.curAttrData.fg & 0xFF, 50); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); }); describe('should fill early sequence end with default of 0', () => { - it('CSI 38:2 m', () => { + it('CSI 38:2 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;2m'); - inputHandler.parse('\x1b[38:2m'); + await inputHandler2.parseP('\x1b[38;2m'); + await inputHandler.parseP('\x1b[38:2m'); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 0 << 16 | 0 << 8 | 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 38:5 m', () => { + it('CSI 38:5 m', async () => { inputHandler.curAttrData.fg = 0xFFFFFFFF; inputHandler2.curAttrData.fg = 0xFFFFFFFF; - inputHandler2.parse('\x1b[38;5m'); - inputHandler.parse('\x1b[38:5m'); + await inputHandler2.parseP('\x1b[38;5m'); + await inputHandler.parseP('\x1b[38:5m'); assert.equal(inputHandler2.curAttrData.fg & 0xFF, 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); }); describe('should not interfere with leading/following SGR attrs', () => { - it('CSI 1 ; 38:2::50:100:150 ; 4 m', () => { - inputHandler2.parse('\x1b[1;38;2;50;100;150;4m'); - inputHandler.parse('\x1b[1;38:2::50:100:150;4m'); + it('CSI 1 ; 38:2::50:100:150 ; 4 m', async () => { + await inputHandler2.parseP('\x1b[1;38;2;50;100;150;4m'); + await inputHandler.parseP('\x1b[1;38:2::50:100:150;4m'); assert.equal(!!inputHandler2.curAttrData.isBold(), true); assert.equal(!!inputHandler2.curAttrData.isUnderline(), true); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 150); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 1 ; 38:2::50:100: ; 4 m', () => { - inputHandler2.parse('\x1b[1;38;2;50;100;;4m'); - inputHandler.parse('\x1b[1;38:2::50:100:;4m'); + it('CSI 1 ; 38:2::50:100: ; 4 m', async () => { + await inputHandler2.parseP('\x1b[1;38;2;50;100;;4m'); + await inputHandler.parseP('\x1b[1;38:2::50:100:;4m'); assert.equal(!!inputHandler2.curAttrData.isBold(), true); assert.equal(!!inputHandler2.curAttrData.isUnderline(), true); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 1 ; 38:2::50:100 ; 4 m', () => { - inputHandler2.parse('\x1b[1;38;2;50;100;;4m'); - inputHandler.parse('\x1b[1;38:2::50:100;4m'); + it('CSI 1 ; 38:2::50:100 ; 4 m', async () => { + await inputHandler2.parseP('\x1b[1;38;2;50;100;;4m'); + await inputHandler.parseP('\x1b[1;38:2::50:100;4m'); assert.equal(!!inputHandler2.curAttrData.isBold(), true); assert.equal(!!inputHandler2.curAttrData.isUnderline(), true); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 50 << 16 | 100 << 8 | 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 1 ; 38:2:: ; 4 m', () => { - inputHandler2.parse('\x1b[1;38;2;;;;4m'); - inputHandler.parse('\x1b[1;38:2::;4m'); + it('CSI 1 ; 38:2:: ; 4 m', async () => { + await inputHandler2.parseP('\x1b[1;38;2;;;;4m'); + await inputHandler.parseP('\x1b[1;38:2::;4m'); assert.equal(!!inputHandler2.curAttrData.isBold(), true); assert.equal(!!inputHandler2.curAttrData.isUnderline(), true); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 0); assert.equal(inputHandler.curAttrData.fg, inputHandler2.curAttrData.fg); }); - it('CSI 1 ; 38;2:: ; 4 m', () => { - inputHandler2.parse('\x1b[1;38;2;;;;4m'); - inputHandler.parse('\x1b[1;38;2::;4m'); + it('CSI 1 ; 38;2:: ; 4 m', async () => { + await inputHandler2.parseP('\x1b[1;38;2;;;;4m'); + await inputHandler.parseP('\x1b[1;38;2::;4m'); assert.equal(!!inputHandler2.curAttrData.isBold(), true); assert.equal(!!inputHandler2.curAttrData.isUnderline(), true); assert.equal(inputHandler2.curAttrData.fg & 0xFFFFFF, 0); @@ -719,372 +778,372 @@ describe('InputHandler', () => { beforeEach(() => { bufferService.resize(10, 10); }); - it('cursor forward (CUF)', () => { - inputHandler.parse('\x1b[C'); + it('cursor forward (CUF)', async () => { + await inputHandler.parseP('\x1b[C'); assert.deepEqual(getCursor(bufferService), [1, 0]); - inputHandler.parse('\x1b[1C'); + await inputHandler.parseP('\x1b[1C'); assert.deepEqual(getCursor(bufferService), [2, 0]); - inputHandler.parse('\x1b[4C'); + await inputHandler.parseP('\x1b[4C'); assert.deepEqual(getCursor(bufferService), [6, 0]); - inputHandler.parse('\x1b[100C'); + await inputHandler.parseP('\x1b[100C'); assert.deepEqual(getCursor(bufferService), [9, 0]); // should not change y bufferService.buffer.x = 8; bufferService.buffer.y = 4; - inputHandler.parse('\x1b[C'); + await inputHandler.parseP('\x1b[C'); assert.deepEqual(getCursor(bufferService), [9, 4]); }); - it('cursor backward (CUB)', () => { - inputHandler.parse('\x1b[D'); + it('cursor backward (CUB)', async () => { + await inputHandler.parseP('\x1b[D'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[1D'); + await inputHandler.parseP('\x1b[1D'); assert.deepEqual(getCursor(bufferService), [0, 0]); // place cursor at end of first line - inputHandler.parse('\x1b[100C'); - inputHandler.parse('\x1b[D'); + await inputHandler.parseP('\x1b[100C'); + await inputHandler.parseP('\x1b[D'); assert.deepEqual(getCursor(bufferService), [8, 0]); - inputHandler.parse('\x1b[1D'); + await inputHandler.parseP('\x1b[1D'); assert.deepEqual(getCursor(bufferService), [7, 0]); - inputHandler.parse('\x1b[4D'); + await inputHandler.parseP('\x1b[4D'); assert.deepEqual(getCursor(bufferService), [3, 0]); - inputHandler.parse('\x1b[100D'); + await inputHandler.parseP('\x1b[100D'); assert.deepEqual(getCursor(bufferService), [0, 0]); // should not change y bufferService.buffer.x = 4; bufferService.buffer.y = 4; - inputHandler.parse('\x1b[D'); + await inputHandler.parseP('\x1b[D'); assert.deepEqual(getCursor(bufferService), [3, 4]); }); - it('cursor down (CUD)', () => { - inputHandler.parse('\x1b[B'); + it('cursor down (CUD)', async () => { + await inputHandler.parseP('\x1b[B'); assert.deepEqual(getCursor(bufferService), [0, 1]); - inputHandler.parse('\x1b[1B'); + await inputHandler.parseP('\x1b[1B'); assert.deepEqual(getCursor(bufferService), [0, 2]); - inputHandler.parse('\x1b[4B'); + await inputHandler.parseP('\x1b[4B'); assert.deepEqual(getCursor(bufferService), [0, 6]); - inputHandler.parse('\x1b[100B'); + await inputHandler.parseP('\x1b[100B'); assert.deepEqual(getCursor(bufferService), [0, 9]); // should not change x bufferService.buffer.x = 8; bufferService.buffer.y = 0; - inputHandler.parse('\x1b[B'); + await inputHandler.parseP('\x1b[B'); assert.deepEqual(getCursor(bufferService), [8, 1]); }); - it('cursor up (CUU)', () => { - inputHandler.parse('\x1b[A'); + it('cursor up (CUU)', async () => { + await inputHandler.parseP('\x1b[A'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[1A'); + await inputHandler.parseP('\x1b[1A'); assert.deepEqual(getCursor(bufferService), [0, 0]); // place cursor at beginning of last row - inputHandler.parse('\x1b[100B'); - inputHandler.parse('\x1b[A'); + await inputHandler.parseP('\x1b[100B'); + await inputHandler.parseP('\x1b[A'); assert.deepEqual(getCursor(bufferService), [0, 8]); - inputHandler.parse('\x1b[1A'); + await inputHandler.parseP('\x1b[1A'); assert.deepEqual(getCursor(bufferService), [0, 7]); - inputHandler.parse('\x1b[4A'); + await inputHandler.parseP('\x1b[4A'); assert.deepEqual(getCursor(bufferService), [0, 3]); - inputHandler.parse('\x1b[100A'); + await inputHandler.parseP('\x1b[100A'); assert.deepEqual(getCursor(bufferService), [0, 0]); // should not change x bufferService.buffer.x = 8; bufferService.buffer.y = 9; - inputHandler.parse('\x1b[A'); + await inputHandler.parseP('\x1b[A'); assert.deepEqual(getCursor(bufferService), [8, 8]); }); - it('cursor next line (CNL)', () => { - inputHandler.parse('\x1b[E'); + it('cursor next line (CNL)', async () => { + await inputHandler.parseP('\x1b[E'); assert.deepEqual(getCursor(bufferService), [0, 1]); - inputHandler.parse('\x1b[1E'); + await inputHandler.parseP('\x1b[1E'); assert.deepEqual(getCursor(bufferService), [0, 2]); - inputHandler.parse('\x1b[4E'); + await inputHandler.parseP('\x1b[4E'); assert.deepEqual(getCursor(bufferService), [0, 6]); - inputHandler.parse('\x1b[100E'); + await inputHandler.parseP('\x1b[100E'); assert.deepEqual(getCursor(bufferService), [0, 9]); // should reset x to zero bufferService.buffer.x = 8; bufferService.buffer.y = 0; - inputHandler.parse('\x1b[E'); + await inputHandler.parseP('\x1b[E'); assert.deepEqual(getCursor(bufferService), [0, 1]); }); - it('cursor previous line (CPL)', () => { - inputHandler.parse('\x1b[F'); + it('cursor previous line (CPL)', async () => { + await inputHandler.parseP('\x1b[F'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[1F'); + await inputHandler.parseP('\x1b[1F'); assert.deepEqual(getCursor(bufferService), [0, 0]); // place cursor at beginning of last row - inputHandler.parse('\x1b[100E'); - inputHandler.parse('\x1b[F'); + await inputHandler.parseP('\x1b[100E'); + await inputHandler.parseP('\x1b[F'); assert.deepEqual(getCursor(bufferService), [0, 8]); - inputHandler.parse('\x1b[1F'); + await inputHandler.parseP('\x1b[1F'); assert.deepEqual(getCursor(bufferService), [0, 7]); - inputHandler.parse('\x1b[4F'); + await inputHandler.parseP('\x1b[4F'); assert.deepEqual(getCursor(bufferService), [0, 3]); - inputHandler.parse('\x1b[100F'); + await inputHandler.parseP('\x1b[100F'); assert.deepEqual(getCursor(bufferService), [0, 0]); // should reset x to zero bufferService.buffer.x = 8; bufferService.buffer.y = 9; - inputHandler.parse('\x1b[F'); + await inputHandler.parseP('\x1b[F'); assert.deepEqual(getCursor(bufferService), [0, 8]); }); - it('cursor character absolute (CHA)', () => { - inputHandler.parse('\x1b[G'); + it('cursor character absolute (CHA)', async () => { + await inputHandler.parseP('\x1b[G'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[1G'); + await inputHandler.parseP('\x1b[1G'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[2G'); + await inputHandler.parseP('\x1b[2G'); assert.deepEqual(getCursor(bufferService), [1, 0]); - inputHandler.parse('\x1b[5G'); + await inputHandler.parseP('\x1b[5G'); assert.deepEqual(getCursor(bufferService), [4, 0]); - inputHandler.parse('\x1b[100G'); + await inputHandler.parseP('\x1b[100G'); assert.deepEqual(getCursor(bufferService), [9, 0]); }); - it('cursor position (CUP)', () => { + it('cursor position (CUP)', async () => { bufferService.buffer.x = 5; bufferService.buffer.y = 5; - inputHandler.parse('\x1b[H'); + await inputHandler.parseP('\x1b[H'); assert.deepEqual(getCursor(bufferService), [0, 0]); bufferService.buffer.x = 5; bufferService.buffer.y = 5; - inputHandler.parse('\x1b[1H'); + await inputHandler.parseP('\x1b[1H'); assert.deepEqual(getCursor(bufferService), [0, 0]); bufferService.buffer.x = 5; bufferService.buffer.y = 5; - inputHandler.parse('\x1b[1;1H'); + await inputHandler.parseP('\x1b[1;1H'); assert.deepEqual(getCursor(bufferService), [0, 0]); bufferService.buffer.x = 5; bufferService.buffer.y = 5; - inputHandler.parse('\x1b[8H'); + await inputHandler.parseP('\x1b[8H'); assert.deepEqual(getCursor(bufferService), [0, 7]); bufferService.buffer.x = 5; bufferService.buffer.y = 5; - inputHandler.parse('\x1b[;8H'); + await inputHandler.parseP('\x1b[;8H'); assert.deepEqual(getCursor(bufferService), [7, 0]); bufferService.buffer.x = 5; bufferService.buffer.y = 5; - inputHandler.parse('\x1b[100;100H'); + await inputHandler.parseP('\x1b[100;100H'); assert.deepEqual(getCursor(bufferService), [9, 9]); }); - it('horizontal position absolute (HPA)', () => { - inputHandler.parse('\x1b[`'); + it('horizontal position absolute (HPA)', async () => { + await inputHandler.parseP('\x1b[`'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[1`'); + await inputHandler.parseP('\x1b[1`'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[2`'); + await inputHandler.parseP('\x1b[2`'); assert.deepEqual(getCursor(bufferService), [1, 0]); - inputHandler.parse('\x1b[5`'); + await inputHandler.parseP('\x1b[5`'); assert.deepEqual(getCursor(bufferService), [4, 0]); - inputHandler.parse('\x1b[100`'); + await inputHandler.parseP('\x1b[100`'); assert.deepEqual(getCursor(bufferService), [9, 0]); }); - it('horizontal position relative (HPR)', () => { - inputHandler.parse('\x1b[a'); + it('horizontal position relative (HPR)', async () => { + await inputHandler.parseP('\x1b[a'); assert.deepEqual(getCursor(bufferService), [1, 0]); - inputHandler.parse('\x1b[1a'); + await inputHandler.parseP('\x1b[1a'); assert.deepEqual(getCursor(bufferService), [2, 0]); - inputHandler.parse('\x1b[4a'); + await inputHandler.parseP('\x1b[4a'); assert.deepEqual(getCursor(bufferService), [6, 0]); - inputHandler.parse('\x1b[100a'); + await inputHandler.parseP('\x1b[100a'); assert.deepEqual(getCursor(bufferService), [9, 0]); // should not change y bufferService.buffer.x = 8; bufferService.buffer.y = 4; - inputHandler.parse('\x1b[a'); + await inputHandler.parseP('\x1b[a'); assert.deepEqual(getCursor(bufferService), [9, 4]); }); - it('vertical position absolute (VPA)', () => { - inputHandler.parse('\x1b[d'); + it('vertical position absolute (VPA)', async () => { + await inputHandler.parseP('\x1b[d'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[1d'); + await inputHandler.parseP('\x1b[1d'); assert.deepEqual(getCursor(bufferService), [0, 0]); - inputHandler.parse('\x1b[2d'); + await inputHandler.parseP('\x1b[2d'); assert.deepEqual(getCursor(bufferService), [0, 1]); - inputHandler.parse('\x1b[5d'); + await inputHandler.parseP('\x1b[5d'); assert.deepEqual(getCursor(bufferService), [0, 4]); - inputHandler.parse('\x1b[100d'); + await inputHandler.parseP('\x1b[100d'); assert.deepEqual(getCursor(bufferService), [0, 9]); // should not change x bufferService.buffer.x = 8; bufferService.buffer.y = 4; - inputHandler.parse('\x1b[d'); + await inputHandler.parseP('\x1b[d'); assert.deepEqual(getCursor(bufferService), [8, 0]); }); - it('vertical position relative (VPR)', () => { - inputHandler.parse('\x1b[e'); + it('vertical position relative (VPR)', async () => { + await inputHandler.parseP('\x1b[e'); assert.deepEqual(getCursor(bufferService), [0, 1]); - inputHandler.parse('\x1b[1e'); + await inputHandler.parseP('\x1b[1e'); assert.deepEqual(getCursor(bufferService), [0, 2]); - inputHandler.parse('\x1b[4e'); + await inputHandler.parseP('\x1b[4e'); assert.deepEqual(getCursor(bufferService), [0, 6]); - inputHandler.parse('\x1b[100e'); + await inputHandler.parseP('\x1b[100e'); assert.deepEqual(getCursor(bufferService), [0, 9]); // should not change x bufferService.buffer.x = 8; bufferService.buffer.y = 4; - inputHandler.parse('\x1b[e'); + await inputHandler.parseP('\x1b[e'); assert.deepEqual(getCursor(bufferService), [8, 5]); }); describe('should clamp cursor into addressible range', () => { - it('CUF', () => { + it('CUF', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[C'); + await inputHandler.parseP('\x1b[C'); assert.deepEqual(getCursor(bufferService), [9, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[C'); + await inputHandler.parseP('\x1b[C'); assert.deepEqual(getCursor(bufferService), [1, 0]); }); - it('CUB', () => { + it('CUB', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[D'); + await inputHandler.parseP('\x1b[D'); assert.deepEqual(getCursor(bufferService), [8, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[D'); + await inputHandler.parseP('\x1b[D'); assert.deepEqual(getCursor(bufferService), [0, 0]); }); - it('CUD', () => { + it('CUD', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[B'); + await inputHandler.parseP('\x1b[B'); assert.deepEqual(getCursor(bufferService), [9, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[B'); + await inputHandler.parseP('\x1b[B'); assert.deepEqual(getCursor(bufferService), [0, 1]); }); - it('CUU', () => { + it('CUU', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[A'); + await inputHandler.parseP('\x1b[A'); assert.deepEqual(getCursor(bufferService), [9, 8]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[A'); + await inputHandler.parseP('\x1b[A'); assert.deepEqual(getCursor(bufferService), [0, 0]); }); - it('CNL', () => { + it('CNL', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[E'); + await inputHandler.parseP('\x1b[E'); assert.deepEqual(getCursor(bufferService), [0, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[E'); + await inputHandler.parseP('\x1b[E'); assert.deepEqual(getCursor(bufferService), [0, 1]); }); - it('CPL', () => { + it('CPL', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[F'); + await inputHandler.parseP('\x1b[F'); assert.deepEqual(getCursor(bufferService), [0, 8]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[F'); + await inputHandler.parseP('\x1b[F'); assert.deepEqual(getCursor(bufferService), [0, 0]); }); - it('CHA', () => { + it('CHA', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[5G'); + await inputHandler.parseP('\x1b[5G'); assert.deepEqual(getCursor(bufferService), [4, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[5G'); + await inputHandler.parseP('\x1b[5G'); assert.deepEqual(getCursor(bufferService), [4, 0]); }); - it('CUP', () => { + it('CUP', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[5;5H'); + await inputHandler.parseP('\x1b[5;5H'); assert.deepEqual(getCursor(bufferService), [4, 4]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[5;5H'); + await inputHandler.parseP('\x1b[5;5H'); assert.deepEqual(getCursor(bufferService), [4, 4]); }); - it('HPA', () => { + it('HPA', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[5`'); + await inputHandler.parseP('\x1b[5`'); assert.deepEqual(getCursor(bufferService), [4, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[5`'); + await inputHandler.parseP('\x1b[5`'); assert.deepEqual(getCursor(bufferService), [4, 0]); }); - it('HPR', () => { + it('HPR', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[a'); + await inputHandler.parseP('\x1b[a'); assert.deepEqual(getCursor(bufferService), [9, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[a'); + await inputHandler.parseP('\x1b[a'); assert.deepEqual(getCursor(bufferService), [1, 0]); }); - it('VPA', () => { + it('VPA', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[5d'); + await inputHandler.parseP('\x1b[5d'); assert.deepEqual(getCursor(bufferService), [9, 4]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[5d'); + await inputHandler.parseP('\x1b[5d'); assert.deepEqual(getCursor(bufferService), [0, 4]); }); - it('VPR', () => { + it('VPR', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[e'); + await inputHandler.parseP('\x1b[e'); assert.deepEqual(getCursor(bufferService), [9, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[e'); + await inputHandler.parseP('\x1b[e'); assert.deepEqual(getCursor(bufferService), [0, 1]); }); - it('DCH', () => { + it('DCH', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[P'); + await inputHandler.parseP('\x1b[P'); assert.deepEqual(getCursor(bufferService), [9, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[P'); + await inputHandler.parseP('\x1b[P'); assert.deepEqual(getCursor(bufferService), [0, 0]); }); - it('DCH - should delete last cell', () => { - inputHandler.parse('0123456789\x1b[P'); + it('DCH - should delete last cell', async () => { + await inputHandler.parseP('0123456789\x1b[P'); assert.equal(bufferService.buffer.lines.get(0)!.translateToString(false), '012345678 '); }); - it('ECH', () => { + it('ECH', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[X'); + await inputHandler.parseP('\x1b[X'); assert.deepEqual(getCursor(bufferService), [9, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[X'); + await inputHandler.parseP('\x1b[X'); assert.deepEqual(getCursor(bufferService), [0, 0]); }); - it('ECH - should delete last cell', () => { - inputHandler.parse('0123456789\x1b[X'); + it('ECH - should delete last cell', async () => { + await inputHandler.parseP('0123456789\x1b[X'); assert.equal(bufferService.buffer.lines.get(0)!.translateToString(false), '012345678 '); }); - it('ICH', () => { + it('ICH', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[@'); + await inputHandler.parseP('\x1b[@'); assert.deepEqual(getCursor(bufferService), [9, 9]); bufferService.buffer.x = -10000; bufferService.buffer.y = -10000; - inputHandler.parse('\x1b[@'); + await inputHandler.parseP('\x1b[@'); assert.deepEqual(getCursor(bufferService), [0, 0]); }); - it('ICH - should delete last cell', () => { - inputHandler.parse('0123456789\x1b[@'); + it('ICH - should delete last cell', async () => { + await inputHandler.parseP('0123456789\x1b[@'); assert.equal(bufferService.buffer.lines.get(0)!.translateToString(false), '012345678 '); }); }); @@ -1093,31 +1152,31 @@ describe('InputHandler', () => { beforeEach(() => { bufferService.resize(10, 10); }); - it('should default to whole viewport', () => { - inputHandler.parse('\x1b[r'); + it('should default to whole viewport', async () => { + await inputHandler.parseP('\x1b[r'); assert.equal(bufferService.buffer.scrollTop, 0); assert.equal(bufferService.buffer.scrollBottom, 9); - inputHandler.parse('\x1b[3;7r'); + await inputHandler.parseP('\x1b[3;7r'); assert.equal(bufferService.buffer.scrollTop, 2); assert.equal(bufferService.buffer.scrollBottom, 6); - inputHandler.parse('\x1b[0;0r'); + await inputHandler.parseP('\x1b[0;0r'); assert.equal(bufferService.buffer.scrollTop, 0); assert.equal(bufferService.buffer.scrollBottom, 9); }); - it('should clamp bottom', () => { - inputHandler.parse('\x1b[3;1000r'); + it('should clamp bottom', async () => { + await inputHandler.parseP('\x1b[3;1000r'); assert.equal(bufferService.buffer.scrollTop, 2); assert.equal(bufferService.buffer.scrollBottom, 9); }); - it('should only apply for top < bottom', () => { - inputHandler.parse('\x1b[7;2r'); + it('should only apply for top < bottom', async () => { + await inputHandler.parseP('\x1b[7;2r'); assert.equal(bufferService.buffer.scrollTop, 0); assert.equal(bufferService.buffer.scrollBottom, 9); }); - it('should home cursor', () => { + it('should home cursor', async () => { bufferService.buffer.x = 10000; bufferService.buffer.y = 10000; - inputHandler.parse('\x1b[2;7r'); + await inputHandler.parseP('\x1b[2;7r'); assert.deepEqual(getCursor(bufferService), [0, 0]); }); }); @@ -1125,76 +1184,76 @@ describe('InputHandler', () => { beforeEach(() => { bufferService.resize(10, 10); }); - it('scrollUp', () => { - inputHandler.parse('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[2;4r\x1b[2Sm'); + it('scrollUp', async () => { + await inputHandler.parseP('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[2;4r\x1b[2Sm'); assert.deepEqual(getLines(bufferService), ['m', '3', '', '', '4', '5', '6', '7', '8', '9']); }); - it('scrollDown', () => { - inputHandler.parse('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[2;4r\x1b[2Tm'); + it('scrollDown', async () => { + await inputHandler.parseP('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[2;4r\x1b[2Tm'); assert.deepEqual(getLines(bufferService), ['m', '', '', '1', '4', '5', '6', '7', '8', '9']); }); - it('insertLines - out of margins', () => { - inputHandler.parse('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); + it('insertLines - out of margins', async () => { + await inputHandler.parseP('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); assert.equal(bufferService.buffer.scrollTop, 2); assert.equal(bufferService.buffer.scrollBottom, 5); - inputHandler.parse('\x1b[2Lm'); + await inputHandler.parseP('\x1b[2Lm'); assert.deepEqual(getLines(bufferService), ['m', '1', '2', '3', '4', '5', '6', '7', '8', '9']); - inputHandler.parse('\x1b[2H\x1b[2Ln'); + await inputHandler.parseP('\x1b[2H\x1b[2Ln'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', '6', '7', '8', '9']); // skip below scrollbottom - inputHandler.parse('\x1b[7H\x1b[2Lo'); + await inputHandler.parseP('\x1b[7H\x1b[2Lo'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', 'o', '7', '8', '9']); - inputHandler.parse('\x1b[8H\x1b[2Lp'); + await inputHandler.parseP('\x1b[8H\x1b[2Lp'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', 'o', 'p', '8', '9']); - inputHandler.parse('\x1b[100H\x1b[2Lq'); + await inputHandler.parseP('\x1b[100H\x1b[2Lq'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', 'o', 'p', '8', 'q']); }); - it('insertLines - within margins', () => { - inputHandler.parse('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); + it('insertLines - within margins', async () => { + await inputHandler.parseP('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); assert.equal(bufferService.buffer.scrollTop, 2); assert.equal(bufferService.buffer.scrollBottom, 5); - inputHandler.parse('\x1b[3H\x1b[2Lm'); + await inputHandler.parseP('\x1b[3H\x1b[2Lm'); assert.deepEqual(getLines(bufferService), ['0', '1', 'm', '', '2', '3', '6', '7', '8', '9']); - inputHandler.parse('\x1b[6H\x1b[2Ln'); + await inputHandler.parseP('\x1b[6H\x1b[2Ln'); assert.deepEqual(getLines(bufferService), ['0', '1', 'm', '', '2', 'n', '6', '7', '8', '9']); }); - it('deleteLines - out of margins', () => { - inputHandler.parse('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); + it('deleteLines - out of margins', async () => { + await inputHandler.parseP('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); assert.equal(bufferService.buffer.scrollTop, 2); assert.equal(bufferService.buffer.scrollBottom, 5); - inputHandler.parse('\x1b[2Mm'); + await inputHandler.parseP('\x1b[2Mm'); assert.deepEqual(getLines(bufferService), ['m', '1', '2', '3', '4', '5', '6', '7', '8', '9']); - inputHandler.parse('\x1b[2H\x1b[2Mn'); + await inputHandler.parseP('\x1b[2H\x1b[2Mn'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', '6', '7', '8', '9']); // skip below scrollbottom - inputHandler.parse('\x1b[7H\x1b[2Mo'); + await inputHandler.parseP('\x1b[7H\x1b[2Mo'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', 'o', '7', '8', '9']); - inputHandler.parse('\x1b[8H\x1b[2Mp'); + await inputHandler.parseP('\x1b[8H\x1b[2Mp'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', 'o', 'p', '8', '9']); - inputHandler.parse('\x1b[100H\x1b[2Mq'); + await inputHandler.parseP('\x1b[100H\x1b[2Mq'); assert.deepEqual(getLines(bufferService), ['m', 'n', '2', '3', '4', '5', 'o', 'p', '8', 'q']); }); - it('deleteLines - within margins', () => { - inputHandler.parse('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); + it('deleteLines - within margins', async () => { + await inputHandler.parseP('0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\x1b[3;6r'); assert.equal(bufferService.buffer.scrollTop, 2); assert.equal(bufferService.buffer.scrollBottom, 5); - inputHandler.parse('\x1b[6H\x1b[2Mm'); + await inputHandler.parseP('\x1b[6H\x1b[2Mm'); assert.deepEqual(getLines(bufferService), ['0', '1', '2', '3', '4', 'm', '6', '7', '8', '9']); - inputHandler.parse('\x1b[3H\x1b[2Mn'); + await inputHandler.parseP('\x1b[3H\x1b[2Mn'); assert.deepEqual(getLines(bufferService), ['0', '1', 'n', 'm', '', '', '6', '7', '8', '9']); }); }); - it('should parse big chunks in smaller subchunks', () => { + it('should parse big chunks in smaller subchunks', async () => { // max single chunk size is hardcoded as 131072 const calls: any[] = []; bufferService.resize(10, 10); (inputHandler as any)._parser.parse = (data: Uint32Array, length: number) => { calls.push([data.length, length]); }; - inputHandler.parse('12345'); - inputHandler.parse('a'.repeat(10000)); - inputHandler.parse('a'.repeat(200000)); - inputHandler.parse('a'.repeat(300000)); + await inputHandler.parseP('12345'); + await inputHandler.parseP('a'.repeat(10000)); + await inputHandler.parseP('a'.repeat(200000)); + await inputHandler.parseP('a'.repeat(300000)); assert.deepEqual(calls, [ [4096, 5], [10000, 10000], @@ -1203,187 +1262,187 @@ describe('InputHandler', () => { ]); }); describe('windowOptions', () => { - it('all should be disabled by default and not report', () => { + it('all should be disabled by default and not report', async () => { bufferService.resize(10, 10); const stack: string[] = []; coreService.onData(data => stack.push(data)); - inputHandler.parse('\x1b[14t'); - inputHandler.parse('\x1b[16t'); - inputHandler.parse('\x1b[18t'); - inputHandler.parse('\x1b[20t'); - inputHandler.parse('\x1b[21t'); + await inputHandler.parseP('\x1b[14t'); + await inputHandler.parseP('\x1b[16t'); + await inputHandler.parseP('\x1b[18t'); + await inputHandler.parseP('\x1b[20t'); + await inputHandler.parseP('\x1b[21t'); assert.deepEqual(stack, []); }); - it('14 - GetWinSizePixels', () => { + it('14 - GetWinSizePixels', async () => { bufferService.resize(10, 10); optionsService.options.windowOptions.getWinSizePixels = true; const stack: string[] = []; coreService.onData(data => stack.push(data)); - inputHandler.parse('\x1b[14t'); + await inputHandler.parseP('\x1b[14t'); // does not report in test terminal due to missing renderer assert.deepEqual(stack, []); }); - it('16 - GetCellSizePixels', () => { + it('16 - GetCellSizePixels', async () => { bufferService.resize(10, 10); optionsService.options.windowOptions.getCellSizePixels = true; const stack: string[] = []; coreService.onData(data => stack.push(data)); - inputHandler.parse('\x1b[16t'); + await inputHandler.parseP('\x1b[16t'); // does not report in test terminal due to missing renderer assert.deepEqual(stack, []); }); - it('18 - GetWinSizeChars', () => { + it('18 - GetWinSizeChars', async () => { bufferService.resize(10, 10); optionsService.options.windowOptions.getWinSizeChars = true; const stack: string[] = []; coreService.onData(data => stack.push(data)); - inputHandler.parse('\x1b[18t'); + await inputHandler.parseP('\x1b[18t'); assert.deepEqual(stack, ['\x1b[8;10;10t']); bufferService.resize(50, 20); - inputHandler.parse('\x1b[18t'); + await inputHandler.parseP('\x1b[18t'); assert.deepEqual(stack, ['\x1b[8;10;10t', '\x1b[8;20;50t']); }); - it('22/23 - PushTitle/PopTitle', () => { + it('22/23 - PushTitle/PopTitle', async () => { bufferService.resize(10, 10); optionsService.options.windowOptions.pushTitle = true; optionsService.options.windowOptions.popTitle = true; const stack: string[] = []; inputHandler.onTitleChange(data => stack.push(data)); - inputHandler.parse('\x1b]0;1\x07'); - inputHandler.parse('\x1b[22t'); - inputHandler.parse('\x1b]0;2\x07'); - inputHandler.parse('\x1b[22t'); - inputHandler.parse('\x1b]0;3\x07'); - inputHandler.parse('\x1b[22t'); + await inputHandler.parseP('\x1b]0;1\x07'); + await inputHandler.parseP('\x1b[22t'); + await inputHandler.parseP('\x1b]0;2\x07'); + await inputHandler.parseP('\x1b[22t'); + await inputHandler.parseP('\x1b]0;3\x07'); + await inputHandler.parseP('\x1b[22t'); assert.deepEqual(inputHandler.windowTitleStack, ['1', '2', '3']); assert.deepEqual(inputHandler.iconNameStack, ['1', '2', '3']); assert.deepEqual(stack, ['1', '2', '3']); - inputHandler.parse('\x1b[23t'); - inputHandler.parse('\x1b[23t'); - inputHandler.parse('\x1b[23t'); - inputHandler.parse('\x1b[23t'); // one more to test "overflow" + await inputHandler.parseP('\x1b[23t'); + await inputHandler.parseP('\x1b[23t'); + await inputHandler.parseP('\x1b[23t'); + await inputHandler.parseP('\x1b[23t'); // one more to test "overflow" assert.deepEqual(inputHandler.windowTitleStack, []); assert.deepEqual(inputHandler.iconNameStack, []); assert.deepEqual(stack, ['1', '2', '3', '3', '2', '1']); }); - it('22/23 - PushTitle/PopTitle with ;1', () => { + it('22/23 - PushTitle/PopTitle with ;1', async () => { bufferService.resize(10, 10); optionsService.options.windowOptions.pushTitle = true; optionsService.options.windowOptions.popTitle = true; const stack: string[] = []; inputHandler.onTitleChange(data => stack.push(data)); - inputHandler.parse('\x1b]0;1\x07'); - inputHandler.parse('\x1b[22;1t'); - inputHandler.parse('\x1b]0;2\x07'); - inputHandler.parse('\x1b[22;1t'); - inputHandler.parse('\x1b]0;3\x07'); - inputHandler.parse('\x1b[22;1t'); + await inputHandler.parseP('\x1b]0;1\x07'); + await inputHandler.parseP('\x1b[22;1t'); + await inputHandler.parseP('\x1b]0;2\x07'); + await inputHandler.parseP('\x1b[22;1t'); + await inputHandler.parseP('\x1b]0;3\x07'); + await inputHandler.parseP('\x1b[22;1t'); assert.deepEqual(inputHandler.windowTitleStack, []); assert.deepEqual(inputHandler.iconNameStack, ['1', '2', '3']); assert.deepEqual(stack, ['1', '2', '3']); - inputHandler.parse('\x1b[23;1t'); - inputHandler.parse('\x1b[23;1t'); - inputHandler.parse('\x1b[23;1t'); - inputHandler.parse('\x1b[23;1t'); // one more to test "overflow" + await inputHandler.parseP('\x1b[23;1t'); + await inputHandler.parseP('\x1b[23;1t'); + await inputHandler.parseP('\x1b[23;1t'); + await inputHandler.parseP('\x1b[23;1t'); // one more to test "overflow" assert.deepEqual(inputHandler.windowTitleStack, []); assert.deepEqual(inputHandler.iconNameStack, []); assert.deepEqual(stack, ['1', '2', '3']); }); - it('22/23 - PushTitle/PopTitle with ;2', () => { + it('22/23 - PushTitle/PopTitle with ;2', async () => { bufferService.resize(10, 10); optionsService.options.windowOptions.pushTitle = true; optionsService.options.windowOptions.popTitle = true; const stack: string[] = []; inputHandler.onTitleChange(data => stack.push(data)); - inputHandler.parse('\x1b]0;1\x07'); - inputHandler.parse('\x1b[22;2t'); - inputHandler.parse('\x1b]0;2\x07'); - inputHandler.parse('\x1b[22;2t'); - inputHandler.parse('\x1b]0;3\x07'); - inputHandler.parse('\x1b[22;2t'); + await inputHandler.parseP('\x1b]0;1\x07'); + await inputHandler.parseP('\x1b[22;2t'); + await inputHandler.parseP('\x1b]0;2\x07'); + await inputHandler.parseP('\x1b[22;2t'); + await inputHandler.parseP('\x1b]0;3\x07'); + await inputHandler.parseP('\x1b[22;2t'); assert.deepEqual(inputHandler.windowTitleStack, ['1', '2', '3']); assert.deepEqual(inputHandler.iconNameStack, []); assert.deepEqual(stack, ['1', '2', '3']); - inputHandler.parse('\x1b[23;2t'); - inputHandler.parse('\x1b[23;2t'); - inputHandler.parse('\x1b[23;2t'); - inputHandler.parse('\x1b[23;2t'); // one more to test "overflow" + await inputHandler.parseP('\x1b[23;2t'); + await inputHandler.parseP('\x1b[23;2t'); + await inputHandler.parseP('\x1b[23;2t'); + await inputHandler.parseP('\x1b[23;2t'); // one more to test "overflow" assert.deepEqual(inputHandler.windowTitleStack, []); assert.deepEqual(inputHandler.iconNameStack, []); assert.deepEqual(stack, ['1', '2', '3', '3', '2', '1']); }); - it('DECCOLM - should only work with "SetWinLines" (24) enabled', () => { + it('DECCOLM - should only work with "SetWinLines" (24) enabled', async () => { // disabled bufferService.resize(10, 10); - inputHandler.parse('\x1b[?3l'); + await inputHandler.parseP('\x1b[?3l'); assert.equal(bufferService.cols, 10); - inputHandler.parse('\x1b[?3h'); + await inputHandler.parseP('\x1b[?3h'); assert.equal(bufferService.cols, 10); // enabled inputHandler.reset(); optionsService.options.windowOptions.setWinLines = true; - inputHandler.parse('\x1b[?3l'); + await inputHandler.parseP('\x1b[?3l'); assert.equal(bufferService.cols, 80); - inputHandler.parse('\x1b[?3h'); + await inputHandler.parseP('\x1b[?3h'); assert.equal(bufferService.cols, 132); }); }); describe('should correctly reset cells taken by wide chars', () => { - beforeEach(() => { + beforeEach(async () => { bufferService.resize(10, 5); optionsService.options.scrollback = 1; - inputHandler.parse('¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥'); + await inputHandler.parseP('¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥'); }); - it('print', () => { - inputHandler.parse('\x1b[H#'); + it('print', async () => { + await inputHandler.parseP('\x1b[H#'); assert.deepEqual(getLines(bufferService), ['# ¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[1;6H######'); + await inputHandler.parseP('\x1b[1;6H######'); assert.deepEqual(getLines(bufferService), ['# ¥ #####', '# ¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('#'); + await inputHandler.parseP('#'); assert.deepEqual(getLines(bufferService), ['# ¥ #####', '##¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('#'); + await inputHandler.parseP('#'); assert.deepEqual(getLines(bufferService), ['# ¥ #####', '### ¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[3;9H#'); + await inputHandler.parseP('\x1b[3;9H#'); assert.deepEqual(getLines(bufferService), ['# ¥ #####', '### ¥¥¥', '¥¥¥¥#', '¥¥¥¥¥', '']); - inputHandler.parse('#'); + await inputHandler.parseP('#'); assert.deepEqual(getLines(bufferService), ['# ¥ #####', '### ¥¥¥', '¥¥¥¥##', '¥¥¥¥¥', '']); - inputHandler.parse('#'); + await inputHandler.parseP('#'); assert.deepEqual(getLines(bufferService), ['# ¥ #####', '### ¥¥¥', '¥¥¥¥##', '# ¥¥¥¥', '']); - inputHandler.parse('\x1b[4;10H#'); + await inputHandler.parseP('\x1b[4;10H#'); assert.deepEqual(getLines(bufferService), ['# ¥ #####', '### ¥¥¥', '¥¥¥¥##', '# ¥¥¥ #', '']); }); - it('EL', () => { - inputHandler.parse('\x1b[1;6H\x1b[K#'); + it('EL', async () => { + await inputHandler.parseP('\x1b[1;6H\x1b[K#'); assert.deepEqual(getLines(bufferService), ['¥¥ #', '¥¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[2;5H\x1b[1K'); + await inputHandler.parseP('\x1b[2;5H\x1b[1K'); assert.deepEqual(getLines(bufferService), ['¥¥ #', ' ¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[3;6H\x1b[1K'); + await inputHandler.parseP('\x1b[3;6H\x1b[1K'); assert.deepEqual(getLines(bufferService), ['¥¥ #', ' ¥¥', ' ¥¥', '¥¥¥¥¥', '']); }); - it('ICH', () => { - inputHandler.parse('\x1b[1;6H\x1b[@'); + it('ICH', async () => { + await inputHandler.parseP('\x1b[1;6H\x1b[@'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥', '¥¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[2;4H\x1b[2@'); + await inputHandler.parseP('\x1b[2;4H\x1b[2@'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥', '¥ ¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[3;4H\x1b[3@'); + await inputHandler.parseP('\x1b[3;4H\x1b[3@'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥', '¥ ¥¥', '¥ ¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[4;4H\x1b[4@'); + await inputHandler.parseP('\x1b[4;4H\x1b[4@'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥', '¥ ¥¥', '¥ ¥', '¥ ¥', '']); }); - it('DCH', () => { - inputHandler.parse('\x1b[1;6H\x1b[P'); + it('DCH', async () => { + await inputHandler.parseP('\x1b[1;6H\x1b[P'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[2;6H\x1b[2P'); + await inputHandler.parseP('\x1b[2;6H\x1b[2P'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥¥', '¥¥ ¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[3;6H\x1b[3P'); + await inputHandler.parseP('\x1b[3;6H\x1b[3P'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥¥', '¥¥ ¥', '¥¥ ¥', '¥¥¥¥¥', '']); }); - it('ECH', () => { - inputHandler.parse('\x1b[1;6H\x1b[X'); + it('ECH', async () => { + await inputHandler.parseP('\x1b[1;6H\x1b[X'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[2;6H\x1b[2X'); + await inputHandler.parseP('\x1b[2;6H\x1b[2X'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥¥', '¥¥ ¥', '¥¥¥¥¥', '¥¥¥¥¥', '']); - inputHandler.parse('\x1b[3;6H\x1b[3X'); + await inputHandler.parseP('\x1b[3;6H\x1b[3X'); assert.deepEqual(getLines(bufferService), ['¥¥ ¥¥', '¥¥ ¥', '¥¥ ¥', '¥¥¥¥¥', '']); }); }); @@ -1395,74 +1454,74 @@ describe('InputHandler', () => { optionsService.options.scrollback = 1; }); describe('reverseWraparound unset (default)', () => { - it('cannot delete last cell', () => { - inputHandler.parse('12345'); - inputHandler.parse(ttyBS); + it('cannot delete last cell', async () => { + await inputHandler.parseP('12345'); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 1), ['123 5']); - inputHandler.parse(ttyBS.repeat(10)); + await inputHandler.parseP(ttyBS.repeat(10)); assert.deepEqual(getLines(bufferService, 1), [' 5']); }); - it('cannot access prev line', () => { - inputHandler.parse('12345'.repeat(2)); - inputHandler.parse(ttyBS); + it('cannot access prev line', async () => { + await inputHandler.parseP('12345'.repeat(2)); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), ['12345', '123 5']); - inputHandler.parse(ttyBS.repeat(10)); + await inputHandler.parseP(ttyBS.repeat(10)); assert.deepEqual(getLines(bufferService, 2), ['12345', ' 5']); }); }); describe('reverseWraparound set', () => { - it('can delete last cell', () => { - inputHandler.parse('\x1b[?45h'); - inputHandler.parse('12345'); - inputHandler.parse(ttyBS); + it('can delete last cell', async () => { + await inputHandler.parseP('\x1b[?45h'); + await inputHandler.parseP('12345'); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 1), ['1234 ']); - inputHandler.parse(ttyBS.repeat(7)); + await inputHandler.parseP(ttyBS.repeat(7)); assert.deepEqual(getLines(bufferService, 1), [' ']); }); - it('can access prev line if wrapped', () => { - inputHandler.parse('\x1b[?45h'); - inputHandler.parse('12345'.repeat(2)); - inputHandler.parse(ttyBS); + it('can access prev line if wrapped', async () => { + await inputHandler.parseP('\x1b[?45h'); + await inputHandler.parseP('12345'.repeat(2)); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), ['12345', '1234 ']); - inputHandler.parse(ttyBS.repeat(7)); + await inputHandler.parseP(ttyBS.repeat(7)); assert.deepEqual(getLines(bufferService, 2), ['12 ', ' ']); }); - it('should lift isWrapped', () => { - inputHandler.parse('\x1b[?45h'); - inputHandler.parse('12345'.repeat(2)); + it('should lift isWrapped', async () => { + await inputHandler.parseP('\x1b[?45h'); + await inputHandler.parseP('12345'.repeat(2)); assert.equal(bufferService.buffer.lines.get(1)?.isWrapped, true); - inputHandler.parse(ttyBS.repeat(7)); + await inputHandler.parseP(ttyBS.repeat(7)); assert.equal(bufferService.buffer.lines.get(1)?.isWrapped, false); }); - it('stops at hard NLs', () => { - inputHandler.parse('\x1b[?45h'); - inputHandler.parse('12345\r\n'); - inputHandler.parse('12345'.repeat(2)); - inputHandler.parse(ttyBS.repeat(50)); + it('stops at hard NLs', async () => { + await inputHandler.parseP('\x1b[?45h'); + await inputHandler.parseP('12345\r\n'); + await inputHandler.parseP('12345'.repeat(2)); + await inputHandler.parseP(ttyBS.repeat(50)); assert.deepEqual(getLines(bufferService, 3), ['12345', ' ', ' ']); assert.equal(bufferService.buffer.x, 0); assert.equal(bufferService.buffer.y, 1); }); - it('handles wide chars correctly', () => { - inputHandler.parse('\x1b[?45h'); - inputHandler.parse('¥¥¥'); + it('handles wide chars correctly', async () => { + await inputHandler.parseP('\x1b[?45h'); + await inputHandler.parseP('¥¥¥'); assert.deepEqual(getLines(bufferService, 2), ['¥¥', '¥']); - inputHandler.parse(ttyBS); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), ['¥¥', ' ']); assert.equal(bufferService.buffer.x, 1); - inputHandler.parse(ttyBS); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), ['¥¥', ' ']); assert.equal(bufferService.buffer.x, 0); - inputHandler.parse(ttyBS); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), ['¥ ', ' ']); assert.equal(bufferService.buffer.x, 3); // x=4 skipped due to early wrap-around - inputHandler.parse(ttyBS); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), ['¥ ', ' ']); assert.equal(bufferService.buffer.x, 2); - inputHandler.parse(ttyBS); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), [' ', ' ']); assert.equal(bufferService.buffer.x, 1); - inputHandler.parse(ttyBS); + await inputHandler.parseP(ttyBS); assert.deepEqual(getLines(bufferService, 2), [' ', ' ']); assert.equal(bufferService.buffer.x, 0); }); @@ -1473,72 +1532,72 @@ describe('InputHandler', () => { beforeEach(() => { bufferService.resize(10, 5); }); - it('4 | 24', () => { - inputHandler.parse('\x1b[4m'); + it('4 | 24', async () => { + await inputHandler.parseP('\x1b[4m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.SINGLE); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); }); - it('21 | 24', () => { - inputHandler.parse('\x1b[21m'); + it('21 | 24', async () => { + await inputHandler.parseP('\x1b[21m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DOUBLE); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); }); - it('4:1 | 4:0', () => { - inputHandler.parse('\x1b[4:1m'); + it('4:1 | 4:0', async () => { + await inputHandler.parseP('\x1b[4:1m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.SINGLE); - inputHandler.parse('\x1b[4:0m'); + await inputHandler.parseP('\x1b[4:0m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); - inputHandler.parse('\x1b[4:1m'); + await inputHandler.parseP('\x1b[4:1m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.SINGLE); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); }); - it('4:2 | 4:0', () => { - inputHandler.parse('\x1b[4:2m'); + it('4:2 | 4:0', async () => { + await inputHandler.parseP('\x1b[4:2m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DOUBLE); - inputHandler.parse('\x1b[4:0m'); + await inputHandler.parseP('\x1b[4:0m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); - inputHandler.parse('\x1b[4:2m'); + await inputHandler.parseP('\x1b[4:2m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DOUBLE); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); }); - it('4:3 | 4:0', () => { - inputHandler.parse('\x1b[4:3m'); + it('4:3 | 4:0', async () => { + await inputHandler.parseP('\x1b[4:3m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.CURLY); - inputHandler.parse('\x1b[4:0m'); + await inputHandler.parseP('\x1b[4:0m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); - inputHandler.parse('\x1b[4:3m'); + await inputHandler.parseP('\x1b[4:3m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.CURLY); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); }); - it('4:4 | 4:0', () => { - inputHandler.parse('\x1b[4:4m'); + it('4:4 | 4:0', async () => { + await inputHandler.parseP('\x1b[4:4m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DOTTED); - inputHandler.parse('\x1b[4:0m'); + await inputHandler.parseP('\x1b[4:0m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); - inputHandler.parse('\x1b[4:4m'); + await inputHandler.parseP('\x1b[4:4m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DOTTED); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); }); - it('4:5 | 4:0', () => { - inputHandler.parse('\x1b[4:5m'); + it('4:5 | 4:0', async () => { + await inputHandler.parseP('\x1b[4:5m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DASHED); - inputHandler.parse('\x1b[4:0m'); + await inputHandler.parseP('\x1b[4:0m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); - inputHandler.parse('\x1b[4:5m'); + await inputHandler.parseP('\x1b[4:5m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DASHED); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('\x1b[24m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.NONE); }); - it('4:x --> 4 should revert to single underline', () => { - inputHandler.parse('\x1b[4:5m'); + it('4:x --> 4 should revert to single underline', async () => { + await inputHandler.parseP('\x1b[4:5m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.DASHED); - inputHandler.parse('\x1b[4m'); + await inputHandler.parseP('\x1b[4m'); assert.equal(inputHandler.curAttrData.getUnderlineStyle(), UnderlineStyle.SINGLE); }); }); @@ -1546,9 +1605,9 @@ describe('InputHandler', () => { beforeEach(() => { bufferService.resize(10, 5); }); - it('defaults to FG color', () => { + it('defaults to FG color', async () => { for (const s of ['', '\x1b[30m', '\x1b[38;510m', '\x1b[38;2;1;2;3m']) { - inputHandler.parse(s); + await inputHandler.parseP(s); assert.equal(inputHandler.curAttrData.getUnderlineColor(), inputHandler.curAttrData.getFgColor()); assert.equal(inputHandler.curAttrData.getUnderlineColorMode(), inputHandler.curAttrData.getFgColorMode()); assert.equal(inputHandler.curAttrData.isUnderlineColorRGB(), inputHandler.curAttrData.isFgRGB()); @@ -1556,31 +1615,31 @@ describe('InputHandler', () => { assert.equal(inputHandler.curAttrData.isUnderlineColorDefault(), inputHandler.curAttrData.isFgDefault()); } }); - it('correctly sets P256/RGB colors', () => { - inputHandler.parse('\x1b[4m'); - inputHandler.parse('\x1b[58;5;123m'); + it('correctly sets P256/RGB colors', async () => { + await inputHandler.parseP('\x1b[4m'); + await inputHandler.parseP('\x1b[58;5;123m'); assert.equal(inputHandler.curAttrData.getUnderlineColor(), 123); assert.equal(inputHandler.curAttrData.getUnderlineColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.isUnderlineColorRGB(), false); assert.equal(inputHandler.curAttrData.isUnderlineColorPalette(), true); assert.equal(inputHandler.curAttrData.isUnderlineColorDefault(), false); - inputHandler.parse('\x1b[58;2::1:2:3m'); + await inputHandler.parseP('\x1b[58;2::1:2:3m'); assert.equal(inputHandler.curAttrData.getUnderlineColor(), (1 << 16) | (2 << 8) | 3); assert.equal(inputHandler.curAttrData.getUnderlineColorMode(), Attributes.CM_RGB); assert.equal(inputHandler.curAttrData.isUnderlineColorRGB(), true); assert.equal(inputHandler.curAttrData.isUnderlineColorPalette(), false); assert.equal(inputHandler.curAttrData.isUnderlineColorDefault(), false); }); - it('P256/RGB persistence', () => { + it('P256/RGB persistence', async () => { const cell = new CellData(); - inputHandler.parse('\x1b[4m'); - inputHandler.parse('\x1b[58;5;123m'); + await inputHandler.parseP('\x1b[4m'); + await inputHandler.parseP('\x1b[58;5;123m'); assert.equal(inputHandler.curAttrData.getUnderlineColor(), 123); assert.equal(inputHandler.curAttrData.getUnderlineColorMode(), Attributes.CM_P256); assert.equal(inputHandler.curAttrData.isUnderlineColorRGB(), false); assert.equal(inputHandler.curAttrData.isUnderlineColorPalette(), true); assert.equal(inputHandler.curAttrData.isUnderlineColorDefault(), false); - inputHandler.parse('ab'); + await inputHandler.parseP('ab'); bufferService.buffer!.lines.get(0)!.loadCell(1, cell); assert.equal(cell.getUnderlineColor(), 123); assert.equal(cell.getUnderlineColorMode(), Attributes.CM_P256); @@ -1588,13 +1647,13 @@ describe('InputHandler', () => { assert.equal(cell.isUnderlineColorPalette(), true); assert.equal(cell.isUnderlineColorDefault(), false); - inputHandler.parse('\x1b[4:0m'); + await inputHandler.parseP('\x1b[4:0m'); assert.equal(inputHandler.curAttrData.getUnderlineColor(), inputHandler.curAttrData.getFgColor()); assert.equal(inputHandler.curAttrData.getUnderlineColorMode(), inputHandler.curAttrData.getFgColorMode()); assert.equal(inputHandler.curAttrData.isUnderlineColorRGB(), inputHandler.curAttrData.isFgRGB()); assert.equal(inputHandler.curAttrData.isUnderlineColorPalette(), inputHandler.curAttrData.isFgPalette()); assert.equal(inputHandler.curAttrData.isUnderlineColorDefault(), inputHandler.curAttrData.isFgDefault()); - inputHandler.parse('a'); + await inputHandler.parseP('a'); bufferService.buffer!.lines.get(0)!.loadCell(1, cell); assert.equal(cell.getUnderlineColor(), 123); assert.equal(cell.getUnderlineColorMode(), Attributes.CM_P256); @@ -1608,15 +1667,15 @@ describe('InputHandler', () => { assert.equal(cell.isUnderlineColorPalette(), inputHandler.curAttrData.isFgPalette()); assert.equal(cell.isUnderlineColorDefault(), inputHandler.curAttrData.isFgDefault()); - inputHandler.parse('\x1b[4m'); - inputHandler.parse('\x1b[58;2::1:2:3m'); + await inputHandler.parseP('\x1b[4m'); + await inputHandler.parseP('\x1b[58;2::1:2:3m'); assert.equal(inputHandler.curAttrData.getUnderlineColor(), (1 << 16) | (2 << 8) | 3); assert.equal(inputHandler.curAttrData.getUnderlineColorMode(), Attributes.CM_RGB); assert.equal(inputHandler.curAttrData.isUnderlineColorRGB(), true); assert.equal(inputHandler.curAttrData.isUnderlineColorPalette(), false); assert.equal(inputHandler.curAttrData.isUnderlineColorDefault(), false); - inputHandler.parse('a'); - inputHandler.parse('\x1b[24m'); + await inputHandler.parseP('a'); + await inputHandler.parseP('\x1b[24m'); bufferService.buffer!.lines.get(0)!.loadCell(1, cell); assert.equal(cell.getUnderlineColor(), 123); assert.equal(cell.getUnderlineColorMode(), Attributes.CM_P256); @@ -1645,51 +1704,51 @@ describe('InputHandler', () => { }); }); describe('DECSTR', () => { - beforeEach(() => { + beforeEach(async () => { bufferService.resize(10, 5); optionsService.options.scrollback = 1; - inputHandler.parse('01234567890123'); + await inputHandler.parseP('01234567890123'); }); - it('should reset IRM', () => { - inputHandler.parse('\x1b[4h'); + it('should reset IRM', async () => { + await inputHandler.parseP('\x1b[4h'); assert.equal(coreService.modes.insertMode, true); - inputHandler.parse('\x1b[!p'); + await inputHandler.parseP('\x1b[!p'); assert.equal(coreService.modes.insertMode, false); }); - it('should reset cursor visibility', () => { - inputHandler.parse('\x1b[?25l'); + it('should reset cursor visibility', async () => { + await inputHandler.parseP('\x1b[?25l'); assert.equal(coreService.isCursorHidden, true); - inputHandler.parse('\x1b[!p'); + await inputHandler.parseP('\x1b[!p'); assert.equal(coreService.isCursorHidden, false); }); - it('should reset scroll margins', () => { - inputHandler.parse('\x1b[2;4r'); + it('should reset scroll margins', async () => { + await inputHandler.parseP('\x1b[2;4r'); assert.equal(bufferService.buffer.scrollTop, 1); assert.equal(bufferService.buffer.scrollBottom, 3); - inputHandler.parse('\x1b[!p'); + await inputHandler.parseP('\x1b[!p'); assert.equal(bufferService.buffer.scrollTop, 0); assert.equal(bufferService.buffer.scrollBottom, bufferService.rows - 1); }); - it('should reset text attributes', () => { - inputHandler.parse('\x1b[1;2;32;43m'); + it('should reset text attributes', async () => { + await inputHandler.parseP('\x1b[1;2;32;43m'); assert.equal(!!inputHandler.curAttrData.isBold(), true); - inputHandler.parse('\x1b[!p'); + await inputHandler.parseP('\x1b[!p'); assert.equal(!!inputHandler.curAttrData.isBold(), false); assert.equal(inputHandler.curAttrData.fg, 0); assert.equal(inputHandler.curAttrData.bg, 0); }); - it('should reset DECSC data', () => { - inputHandler.parse('\x1b7'); + it('should reset DECSC data', async () => { + await inputHandler.parseP('\x1b7'); assert.equal(bufferService.buffer.savedX, 4); assert.equal(bufferService.buffer.savedY, 1); - inputHandler.parse('\x1b[!p'); + await inputHandler.parseP('\x1b[!p'); assert.equal(bufferService.buffer.savedX, 0); assert.equal(bufferService.buffer.savedY, 0); }); - it('should reset DECOM', () => { - inputHandler.parse('\x1b[?6h'); + it('should reset DECOM', async () => { + await inputHandler.parseP('\x1b[?6h'); assert.equal(coreService.decPrivateModes.origin, true); - inputHandler.parse('\x1b[!p'); + await inputHandler.parseP('\x1b[!p'); assert.equal(coreService.decPrivateModes.origin, false); }); }); @@ -1700,7 +1759,8 @@ describe('InputHandler', () => { assert.isNotNull(event); assert.deepEqual(event!.colors[0], { colorIndex: 19, red: 0xa1, green: 0xb2, blue: 0xc3 }); - }), + }); + it('4: should ignore incorrect Ansi color change data', () => { // this is testing a private method assert.isNull(inputHandler.parseAnsiColorChange('17;rgb:a/b/c')); @@ -1708,6 +1768,7 @@ describe('InputHandler', () => { assert.isNull(inputHandler.parseAnsiColorChange('17;rgba:aa/bb/cc')); assert.isNull(inputHandler.parseAnsiColorChange('rgb:aa/bb/cc')); }); + it('4: should parse a list of Ansi color changes', () => { // this is testing a private method const event = inputHandler.parseAnsiColorChange('19;rgb:a1/b2/c3;17;rgb:00/11/22;255;rgb:01/ef/2d'); @@ -1733,15 +1794,75 @@ describe('InputHandler', () => { assert.equal(event!.colors.length, 1); assert.deepEqual(event!.colors[0], { colorIndex: 19, red: 0xa1, green: 0xb2, blue: 0xc3 }); }); - it('4: should fire event on Ansi color change', (done) => { - inputHandler.onAnsiColorChange(e => { - assert.isNotNull(e); - assert.isNotNull(e!.colors); - assert.deepEqual(e!.colors[0], { colorIndex: 17, red: 0x1a, green: 0x2b, blue: 0x3c }); - assert.deepEqual(e!.colors[1], { colorIndex: 12, red: 0x11, green: 0x22, blue: 0x33 }); - done(); + it('4: should fire event on Ansi color change', async () => { + return new Promise(async r => { + inputHandler.onAnsiColorChange(e => { + assert.isNotNull(e); + assert.isNotNull(e!.colors); + assert.deepEqual(e!.colors[0], { colorIndex: 17, red: 0x1a, green: 0x2b, blue: 0x3c }); + assert.deepEqual(e!.colors[1], { colorIndex: 12, red: 0x11, green: 0x22, blue: 0x33 }); + r(); + }); + await inputHandler.parseP('\x1b]4;17;rgb:1a/2b/3c;12;rgb:11/22/33\x1b\\'); }); - inputHandler.parse('\x1b]4;17;rgb:1a/2b/3c;12;rgb:11/22/33\x1b\\'); }); }); }); + + +describe('InputHandler - async handlers', () => { + let bufferService: IBufferService; + let coreService: ICoreService; + let optionsService: MockOptionsService; + let inputHandler: TestInputHandler; + + beforeEach(() => { + optionsService = new MockOptionsService(); + bufferService = new BufferService(optionsService); + bufferService.resize(80, 30); + coreService = new CoreService(() => {}, bufferService, new MockLogService(), optionsService); + coreService.onData(data => { console.log(data); }); + + inputHandler = new TestInputHandler(bufferService, new MockCharsetService(), coreService, new MockDirtyRowService(), new MockLogService(), optionsService, new MockCoreMouseService(), new MockUnicodeService()); + }); + + it('async CUP with CPR check', async () => { + const cup: number[][] = []; + const cpr: number[][] = []; + inputHandler.registerCsiHandler({final: 'H'}, async params => { + cup.push(params.toArray() as number[]); + await new Promise(res => setTimeout(res, 50)); + // late call of real repositioning + return inputHandler.cursorPosition(params); + }); + coreService.onData(data => { + const m = data.match(/\x1b\[(.*?);(.*?)R/); + if (m) { + cpr.push([parseInt(m[1]), parseInt(m[2])]); + } + }); + await inputHandler.parseP('aaa\x1b[3;4H\x1b[6nbbb\x1b[6;8H\x1b[6n'); + assert.deepEqual(cup, cpr); + }); + it('async OSC between', async () => { + inputHandler.registerOscHandler(1000, async data => { + await new Promise(res => setTimeout(res, 50)); + assert.deepEqual(getLines(bufferService, 2), ['hello world!', '']); + assert.equal(data, 'some data'); + return true; + }); + await inputHandler.parseP('hello world!\r\n\x1b]1000;some data\x07second line'); + assert.deepEqual(getLines(bufferService, 2), ['hello world!', 'second line']); + }); + it('async DCS between', async () => { + inputHandler.registerDcsHandler({final: 'a'}, async (data, params) => { + await new Promise(res => setTimeout(res, 50)); + assert.deepEqual(getLines(bufferService, 2), ['hello world!', '']); + assert.equal(data, 'some data'); + assert.deepEqual(params.toArray(), [1, 2]); + return true; + }); + await inputHandler.parseP('hello world!\r\n\x1bP1;2asome data\x1b\\second line'); + assert.deepEqual(getLines(bufferService, 2), ['hello world!', 'second line']); + }); +}); diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index 626e1fe2..13b0a0e7 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -4,7 +4,7 @@ * @license MIT */ -import { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IAnsiColorChangeEvent } from 'common/Types'; +import { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IAnsiColorChangeEvent, IParseStack } from 'common/Types'; import { C0, C1 } from 'common/data/EscapeSequences'; import { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets'; import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser'; @@ -17,7 +17,7 @@ import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IFunctionId import { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content, UnderlineStyle } from 'common/buffer/Constants'; import { CellData } from 'common/buffer/CellData'; import { AttributeData } from 'common/buffer/AttributeData'; -import { ICoreService, IBufferService, IOptionsService, ILogService, IDirtyRowService, ICoreMouseService, ICharsetService, IUnicodeService } from 'common/services/Services'; +import { ICoreService, IBufferService, IOptionsService, ILogService, IDirtyRowService, ICoreMouseService, ICharsetService, IUnicodeService, LogLevelEnum } from 'common/services/Services'; import { OscHandler } from 'common/parser/OscParser'; import { DcsHandler } from 'common/parser/DcsParser'; @@ -97,6 +97,9 @@ export enum WindowsOptionsReportType { GET_CELL_SIZE_PIXELS = 1 } +// create a warning log if an async handler takes longer than the limit (in ms) +const SLOW_ASYNC_LIMIT = 5000; + /** * DCS subparser implementations */ @@ -146,36 +149,42 @@ class DECRQSS implements IDcsHandler { this._data = concat(this._data, data.subarray(start, end)); } - public unhook(success: boolean): void { + public unhook(success: boolean): boolean { if (!success) { this._data = new Uint32Array(0); - return; + return true; } 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}\\`); + this._coreService.triggerDataEvent(`${C0.ESC}P1$r0"q${C0.ESC}\\`); + break; case '"p': // DECSCL - return this._coreService.triggerDataEvent(`${C0.ESC}P1$r61;1"p${C0.ESC}\\`); + this._coreService.triggerDataEvent(`${C0.ESC}P1$r61;1"p${C0.ESC}\\`); + break; 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}\\`); + this._coreService.triggerDataEvent(`${C0.ESC}P1$r${pt}${C0.ESC}\\`); + break; case 'm': // SGR // TODO: report real settings instead of 0m - return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0m${C0.ESC}\\`); + this._coreService.triggerDataEvent(`${C0.ESC}P1$r0m${C0.ESC}\\`); + break; 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}\\`); + this._coreService.triggerDataEvent(`${C0.ESC}P1$r${style} q${C0.ESC}\\`); + break; 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}\\`); } + return true; } } @@ -253,6 +262,14 @@ export class InputHandler extends Disposable implements IInputHandler { private _onAnsiColorChange = new EventEmitter(); public get onAnsiColorChange(): IEvent { return this._onAnsiColorChange.event; } + private _parseStack: IParseStack = { + paused: false, + cursorStartX: 0, + cursorStartY: 0, + decodedLength: 0, + position: 0 + }; + constructor( private readonly _bufferService: IBufferService, private readonly _charsetService: ICharsetService, @@ -297,53 +314,53 @@ export class InputHandler extends Disposable implements IInputHandler { /** * 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: 't'}, params => this.windowOptions(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)); + this._parser.registerCsiHandler({final: '@'}, params => this.insertChars(params)); + this._parser.registerCsiHandler({intermediates: ' ', final: '@'}, params => this.scrollLeft(params)); + this._parser.registerCsiHandler({final: 'A'}, params => this.cursorUp(params)); + this._parser.registerCsiHandler({intermediates: ' ', final: 'A'}, params => this.scrollRight(params)); + this._parser.registerCsiHandler({final: 'B'}, params => this.cursorDown(params)); + this._parser.registerCsiHandler({final: 'C'}, params => this.cursorForward(params)); + this._parser.registerCsiHandler({final: 'D'}, params => this.cursorBackward(params)); + this._parser.registerCsiHandler({final: 'E'}, params => this.cursorNextLine(params)); + this._parser.registerCsiHandler({final: 'F'}, params => this.cursorPrecedingLine(params)); + this._parser.registerCsiHandler({final: 'G'}, params => this.cursorCharAbsolute(params)); + this._parser.registerCsiHandler({final: 'H'}, params => this.cursorPosition(params)); + this._parser.registerCsiHandler({final: 'I'}, params => this.cursorForwardTab(params)); + this._parser.registerCsiHandler({final: 'J'}, params => this.eraseInDisplay(params)); + this._parser.registerCsiHandler({prefix: '?', final: 'J'}, params => this.eraseInDisplay(params)); + this._parser.registerCsiHandler({final: 'K'}, params => this.eraseInLine(params)); + this._parser.registerCsiHandler({prefix: '?', final: 'K'}, params => this.eraseInLine(params)); + this._parser.registerCsiHandler({final: 'L'}, params => this.insertLines(params)); + this._parser.registerCsiHandler({final: 'M'}, params => this.deleteLines(params)); + this._parser.registerCsiHandler({final: 'P'}, params => this.deleteChars(params)); + this._parser.registerCsiHandler({final: 'S'}, params => this.scrollUp(params)); + this._parser.registerCsiHandler({final: 'T'}, params => this.scrollDown(params)); + this._parser.registerCsiHandler({final: 'X'}, params => this.eraseChars(params)); + this._parser.registerCsiHandler({final: 'Z'}, params => this.cursorBackwardTab(params)); + this._parser.registerCsiHandler({final: '`'}, params => this.charPosAbsolute(params)); + this._parser.registerCsiHandler({final: 'a'}, params => this.hPositionRelative(params)); + this._parser.registerCsiHandler({final: 'b'}, params => this.repeatPrecedingCharacter(params)); + this._parser.registerCsiHandler({final: 'c'}, params => this.sendDeviceAttributesPrimary(params)); + this._parser.registerCsiHandler({prefix: '>', final: 'c'}, params => this.sendDeviceAttributesSecondary(params)); + this._parser.registerCsiHandler({final: 'd'}, params => this.linePosAbsolute(params)); + this._parser.registerCsiHandler({final: 'e'}, params => this.vPositionRelative(params)); + this._parser.registerCsiHandler({final: 'f'}, params => this.hVPosition(params)); + this._parser.registerCsiHandler({final: 'g'}, params => this.tabClear(params)); + this._parser.registerCsiHandler({final: 'h'}, params => this.setMode(params)); + this._parser.registerCsiHandler({prefix: '?', final: 'h'}, params => this.setModePrivate(params)); + this._parser.registerCsiHandler({final: 'l'}, params => this.resetMode(params)); + this._parser.registerCsiHandler({prefix: '?', final: 'l'}, params => this.resetModePrivate(params)); + this._parser.registerCsiHandler({final: 'm'}, params => this.charAttributes(params)); + this._parser.registerCsiHandler({final: 'n'}, params => this.deviceStatus(params)); + this._parser.registerCsiHandler({prefix: '?', final: 'n'}, params => this.deviceStatusPrivate(params)); + this._parser.registerCsiHandler({intermediates: '!', final: 'p'}, params => this.softReset(params)); + this._parser.registerCsiHandler({intermediates: ' ', final: 'q'}, params => this.setCursorStyle(params)); + this._parser.registerCsiHandler({final: 'r'}, params => this.setScrollRegion(params)); + this._parser.registerCsiHandler({final: 's'}, params => this.saveCursor(params)); + this._parser.registerCsiHandler({final: 't'}, params => this.windowOptions(params)); + this._parser.registerCsiHandler({final: 'u'}, params => this.restoreCursor(params)); + this._parser.registerCsiHandler({intermediates: '\'', final: '}'}, params => this.insertColumns(params)); + this._parser.registerCsiHandler({intermediates: '\'', final: '~'}, params => this.deleteColumns(params)); /** * execute handler @@ -367,14 +384,14 @@ export class InputHandler extends Disposable implements IInputHandler { * OSC handler */ // 0 - icon name + title - this._parser.setOscHandler(0, new OscHandler((data: string) => { this.setTitle(data); this.setIconName(data); })); + this._parser.registerOscHandler(0, new OscHandler(data => { this.setTitle(data); this.setIconName(data); return true; })); // 1 - icon name - this._parser.setOscHandler(1, new OscHandler((data: string) => this.setIconName(data))); + this._parser.registerOscHandler(1, new OscHandler(data => this.setIconName(data))); // 2 - title - this._parser.setOscHandler(2, new OscHandler((data: string) => this.setTitle(data))); + this._parser.registerOscHandler(2, new OscHandler(data => this.setTitle(data))); // 3 - set property X in the form "prop=value" // 4 - Change Color Number - this._parser.setOscHandler(4, new OscHandler((data: string) => this.setAnsiColor(data))); + this._parser.registerOscHandler(4, new OscHandler(data => this.setAnsiColor(data))); // 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) @@ -409,32 +426,32 @@ export class InputHandler extends Disposable implements IInputHandler { /** * 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.fullReset()); - 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()); + this._parser.registerEscHandler({final: '7'}, () => this.saveCursor()); + this._parser.registerEscHandler({final: '8'}, () => this.restoreCursor()); + this._parser.registerEscHandler({final: 'D'}, () => this.index()); + this._parser.registerEscHandler({final: 'E'}, () => this.nextLine()); + this._parser.registerEscHandler({final: 'H'}, () => this.tabSet()); + this._parser.registerEscHandler({final: 'M'}, () => this.reverseIndex()); + this._parser.registerEscHandler({final: '='}, () => this.keypadApplicationMode()); + this._parser.registerEscHandler({final: '>'}, () => this.keypadNumericMode()); + this._parser.registerEscHandler({final: 'c'}, () => this.fullReset()); + this._parser.registerEscHandler({final: 'n'}, () => this.setgLevel(2)); + this._parser.registerEscHandler({final: 'o'}, () => this.setgLevel(3)); + this._parser.registerEscHandler({final: '|'}, () => this.setgLevel(3)); + this._parser.registerEscHandler({final: '}'}, () => this.setgLevel(2)); + this._parser.registerEscHandler({final: '~'}, () => this.setgLevel(1)); + this._parser.registerEscHandler({intermediates: '%', final: '@'}, () => this.selectDefaultCharset()); + this._parser.registerEscHandler({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.registerEscHandler({intermediates: '(', final: flag}, () => this.selectCharset('(' + flag)); + this._parser.registerEscHandler({intermediates: ')', final: flag}, () => this.selectCharset(')' + flag)); + this._parser.registerEscHandler({intermediates: '*', final: flag}, () => this.selectCharset('*' + flag)); + this._parser.registerEscHandler({intermediates: '+', final: flag}, () => this.selectCharset('+' + flag)); + this._parser.registerEscHandler({intermediates: '-', final: flag}, () => this.selectCharset('-' + flag)); + this._parser.registerEscHandler({intermediates: '.', final: flag}, () => this.selectCharset('.' + flag)); + this._parser.registerEscHandler({intermediates: '/', final: flag}, () => this.selectCharset('/' + flag)); // TODO: supported? } - this._parser.setEscHandler({intermediates: '#', final: '8'}, () => this.screenAlignmentPattern()); + this._parser.registerEscHandler({intermediates: '#', final: '8'}, () => this.screenAlignmentPattern()); /** * error handler @@ -447,17 +464,71 @@ export class InputHandler extends Disposable implements IInputHandler { /** * DCS handler */ - this._parser.setDcsHandler({intermediates: '$', final: 'q'}, new DECRQSS(this._bufferService, this._coreService, this._logService, this._optionsService)); + this._parser.registerDcsHandler({intermediates: '$', final: 'q'}, new DECRQSS(this._bufferService, this._coreService, this._logService, this._optionsService)); } public dispose(): void { super.dispose(); } - public parse(data: string | Uint8Array): void { + /** + * Async parse support. + */ + private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void { + this._parseStack.paused = true; + this._parseStack.cursorStartX = cursorStartX; + this._parseStack.cursorStartY = cursorStartY; + this._parseStack.decodedLength = decodedLength; + this._parseStack.position = position; + } + + private _logSlowResolvingAsync(p: Promise): void { + // log a limited warning about an async handler taking too long + if (this._logService.logLevel <= LogLevelEnum.WARN) { + Promise.race([p, new Promise((res, rej) => setTimeout(() => rej('#SLOW_TIMEOUT'), SLOW_ASYNC_LIMIT))]) + .catch(err => { + if (err !== '#SLOW_TIMEOUT') { + throw err; + } + console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`); + }); + } + } + + /** + * Parse call with async handler support. + * + * Whether the stack state got preserved for the next call, is indicated by the return value: + * - undefined (void): + * all handlers were sync, no stack save, continue normally with next chunk + * - Promise\: + * execution stopped at async handler, stack saved, continue with + * same chunk and the promise resolve value as `promiseResult` until the method returns `undefined` + * + * Note: This method should only be called by `Terminal.write` to ensure correct execution order and + * proper continuation of async parser handlers. + */ + public parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise { + let result: void | Promise; let buffer = this._bufferService.buffer; - const cursorStartX = buffer.x; - const cursorStartY = buffer.y; + let cursorStartX = buffer.x; + let cursorStartY = buffer.y; + let start = 0; + const wasPaused = this._parseStack.paused; + + if (wasPaused) { + // assumption: _parseBuffer never mutates between async calls + if (result = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, promiseResult)) { + this._logSlowResolvingAsync(result); + return result; + } + cursorStartX = this._parseStack.cursorStartX; + cursorStartY = this._parseStack.cursorStartY; + this._parseStack.paused = false; + if (data.length > MAX_PARSEBUFFER_LENGTH) { + start = this._parseStack.position + MAX_PARSEBUFFER_LENGTH; + } + } this._logService.debug('parsing data', data); @@ -469,22 +540,35 @@ export class InputHandler extends Disposable implements IInputHandler { } // Clear the dirty row service so we know which lines changed as a result of parsing - this._dirtyRowService.clearRange(); + // Important: do not clear between async calls, otherwise we lost pending update information. + if (!wasPaused) { + this._dirtyRowService.clearRange(); + } // process big data in smaller chunks if (data.length > MAX_PARSEBUFFER_LENGTH) { - for (let i = 0; i < data.length; i += MAX_PARSEBUFFER_LENGTH) { + for (let i = start; 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); + if (result = this._parser.parse(this._parseBuffer, len)) { + this._preserveStack(cursorStartX, cursorStartY, len, i); + this._logSlowResolvingAsync(result); + return result; + } } } else { - const len = (typeof data === 'string') - ? this._stringDecoder.decode(data, this._parseBuffer) - : this._utf8Decoder.decode(data, this._parseBuffer); - this._parser.parse(this._parseBuffer, len); + if (!wasPaused) { + const len = (typeof data === 'string') + ? this._stringDecoder.decode(data, this._parseBuffer) + : this._utf8Decoder.decode(data, this._parseBuffer); + if (result = this._parser.parse(this._parseBuffer, len)) { + this._preserveStack(cursorStartX, cursorStartY, len, 0); + this._logSlowResolvingAsync(result); + return result; + } + } } buffer = this._bufferService.buffer; @@ -637,40 +721,40 @@ export class InputHandler extends Disposable implements IInputHandler { } /** - * Forward addCsiHandler from parser. + * Forward registerCsiHandler from parser. */ - public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable { + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable { if (id.final === 't' && !id.prefix && !id.intermediates) { // security: always check whether window option is allowed - return this._parser.addCsiHandler(id, params => { + return this._parser.registerCsiHandler(id, params => { if (!paramToWindowOption(params.params[0], this._optionsService.options.windowOptions)) { return true; } return callback(params); }); } - return this._parser.addCsiHandler(id, callback); + return this._parser.registerCsiHandler(id, callback); } /** - * Forward addDcsHandler from parser. + * Forward registerDcsHandler from parser. */ - public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable { - return this._parser.addDcsHandler(id, new DcsHandler(callback)); + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable { + return this._parser.registerDcsHandler(id, new DcsHandler(callback)); } /** - * Forward addEscHandler from parser. + * Forward registerEscHandler from parser. */ - public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable { - return this._parser.addEscHandler(id, callback); + public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable { + return this._parser.registerEscHandler(id, callback); } /** - * Forward addOscHandler from parser. + * Forward registerOscHandler from parser. */ - public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable { - return this._parser.addOscHandler(ident, new OscHandler(callback)); + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { + return this._parser.registerOscHandler(ident, new OscHandler(callback)); } /** @@ -681,8 +765,9 @@ export class InputHandler extends Disposable implements IInputHandler { * The behavior of the bell is further customizable with `ITerminalOptions.bellStyle` * and `ITerminalOptions.bellSound`. */ - public bell(): void { + public bell(): boolean { this._onRequestBell.fire(); + return true; } /** @@ -695,7 +780,7 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y C0 VT "Vertical Tabulation" "\v, \x0B" "Treated as LF." * @vt: #Y C0 FF "Form Feed" "\f, \x0C" "Treated as LF." */ - public lineFeed(): void { + public lineFeed(): boolean { // make buffer local for faster access const buffer = this._bufferService.buffer; @@ -717,6 +802,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._dirtyRowService.markDirty(buffer.y); this._onLineFeed.fire(); + return true; } /** @@ -725,8 +811,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y C0 CR "Carriage Return" "\r, \x0D" "Move the cursor to the beginning of the row." */ - public carriageReturn(): void { + public carriageReturn(): boolean { this._bufferService.buffer.x = 0; + return true; } /** @@ -740,7 +827,7 @@ export class InputHandler extends Disposable implements IInputHandler { * to the end of the previous row. Note that it is not possible to peek back into the scrollbuffer * with the cursor, thus at the home position (top-leftmost cell) this has no effect. */ - public backspace(): void { + public backspace(): boolean { const buffer = this._bufferService.buffer; // reverse wrap-around is disabled @@ -749,7 +836,7 @@ export class InputHandler extends Disposable implements IInputHandler { if (buffer.x > 0) { buffer.x--; } - return; + return true; } // reverse wrap-around is enabled @@ -790,6 +877,7 @@ export class InputHandler extends Disposable implements IInputHandler { } } this._restrictCursor(); + return true; } /** @@ -798,15 +886,16 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y C0 HT "Horizontal Tabulation" "\t, \x09" "Move the cursor to the next character tab stop." */ - public tab(): void { + public tab(): boolean { if (this._bufferService.buffer.x >= this._bufferService.cols) { - return; + return true; } const originalX = this._bufferService.buffer.x; this._bufferService.buffer.x = this._bufferService.buffer.nextStop(); if (this._optionsService.options.screenReaderMode) { this._onA11yTab.fire(this._bufferService.buffer.x - originalX); } + return true; } /** @@ -816,8 +905,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #P[Only limited ISO-2022 charset support.] C0 SO "Shift Out" "\x0E" "Switch to an alternative character set." */ - public shiftOut(): void { + public shiftOut(): boolean { this._charsetService.setgLevel(1); + return true; } /** @@ -827,8 +917,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y C0 SI "Shift In" "\x0F" "Return to regular character set after Shift Out." */ - public shiftIn(): void { + public shiftIn(): boolean { this._charsetService.setgLevel(0); + return true; } /** @@ -875,7 +966,7 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y CSI CUU "Cursor Up" "CSI Ps A" "Move cursor `Ps` times up (default=1)." * If the cursor would pass the top scroll margin, it will stop there. */ - public cursorUp(params: IParams): void { + public cursorUp(params: IParams): boolean { // stop at scrollTop const diffToTop = this._bufferService.buffer.y - this._bufferService.buffer.scrollTop; if (diffToTop >= 0) { @@ -883,6 +974,7 @@ export class InputHandler extends Disposable implements IInputHandler { } else { this._moveCursor(0, -(params.params[0] || 1)); } + return true; } /** @@ -892,7 +984,7 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y CSI CUD "Cursor Down" "CSI Ps B" "Move cursor `Ps` times down (default=1)." * If the cursor would pass the bottom scroll margin, it will stop there. */ - public cursorDown(params: IParams): void { + public cursorDown(params: IParams): boolean { // stop at scrollBottom const diffToBottom = this._bufferService.buffer.scrollBottom - this._bufferService.buffer.y; if (diffToBottom >= 0) { @@ -900,6 +992,7 @@ export class InputHandler extends Disposable implements IInputHandler { } else { this._moveCursor(0, params.params[0] || 1); } + return true; } /** @@ -908,8 +1001,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI CUF "Cursor Forward" "CSI Ps C" "Move cursor `Ps` times forward (default=1)." */ - public cursorForward(params: IParams): void { + public cursorForward(params: IParams): boolean { this._moveCursor(params.params[0] || 1, 0); + return true; } /** @@ -918,8 +1012,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI CUB "Cursor Backward" "CSI Ps D" "Move cursor `Ps` times backward (default=1)." */ - public cursorBackward(params: IParams): void { + public cursorBackward(params: IParams): boolean { this._moveCursor(-(params.params[0] || 1), 0); + return true; } /** @@ -930,9 +1025,10 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y CSI CNL "Cursor Next Line" "CSI Ps E" "Move cursor `Ps` times down (default=1) and to the first column." * Same as CUD, additionally places the cursor at the first column. */ - public cursorNextLine(params: IParams): void { + public cursorNextLine(params: IParams): boolean { this.cursorDown(params); this._bufferService.buffer.x = 0; + return true; } /** @@ -943,9 +1039,10 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y CSI CPL "Cursor Backward" "CSI Ps F" "Move cursor `Ps` times up (default=1) and to the first column." * Same as CUU, additionally places the cursor at the first column. */ - public cursorPrecedingLine(params: IParams): void { + public cursorPrecedingLine(params: IParams): boolean { this.cursorUp(params); this._bufferService.buffer.x = 0; + return true; } /** @@ -954,8 +1051,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI CHA "Cursor Horizontal Absolute" "CSI Ps G" "Move cursor to `Ps`-th column of the active row (default=1)." */ - public cursorCharAbsolute(params: IParams): void { + public cursorCharAbsolute(params: IParams): boolean { this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y); + return true; } /** @@ -967,12 +1065,14 @@ export class InputHandler extends Disposable implements IInputHandler { * If ORIGIN mode is not set, places the cursor to the absolute position within the viewport. * Note that the coordinates are 1-based, thus the top left position starts at `1 ; 1`. */ - public cursorPosition(params: IParams): void { + public cursorPosition(params: IParams): boolean { this._setCursor( // col (params.length >= 2) ? (params.params[1] || 1) - 1 : 0, // row - (params.params[0] || 1) - 1); + (params.params[0] || 1) - 1 + ); + return true; } /** @@ -982,8 +1082,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI HPA "Horizontal Position Absolute" "CSI Ps ` " "Same as CHA." */ - public charPosAbsolute(params: IParams): void { + public charPosAbsolute(params: IParams): boolean { this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y); + return true; } /** @@ -992,8 +1093,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI HPR "Horizontal Position Relative" "CSI Ps a" "Same as CUF." */ - public hPositionRelative(params: IParams): void { + public hPositionRelative(params: IParams): boolean { this._moveCursor(params.params[0] || 1, 0); + return true; } /** @@ -1002,8 +1104,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI VPA "Vertical Position Absolute" "CSI Ps d" "Move cursor to `Ps`-th row (default=1)." */ - public linePosAbsolute(params: IParams): void { + public linePosAbsolute(params: IParams): boolean { this._setCursor(this._bufferService.buffer.x, (params.params[0] || 1) - 1); + return true; } /** @@ -1013,8 +1116,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI VPR "Vertical Position Relative" "CSI Ps e" "Move cursor `Ps` times down (default=1)." */ - public vPositionRelative(params: IParams): void { + public vPositionRelative(params: IParams): boolean { this._moveCursor(0, params.params[0] || 1); + return true; } /** @@ -1025,8 +1129,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI HVP "Horizontal and Vertical Position" "CSI Ps ; Ps f" "Same as CUP." */ - public hVPosition(params: IParams): void { + public hVPosition(params: IParams): boolean { this.cursorPosition(params); + return true; } /** @@ -1040,13 +1145,14 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y CSI TBC "Tab Clear" "CSI Ps g" "Clear tab stops at current position (0) or all (3) (default=0)." * Clearing tabstops off the active row (Ps = 2, VT100) is currently not supported. */ - public tabClear(params: IParams): void { + public tabClear(params: IParams): boolean { 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 = {}; } + return true; } /** @@ -1055,14 +1161,15 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI CHT "Cursor Horizontal Tabulation" "CSI Ps I" "Move cursor `Ps` times tabs forward (default=1)." */ - public cursorForwardTab(params: IParams): void { + public cursorForwardTab(params: IParams): boolean { if (this._bufferService.buffer.x >= this._bufferService.cols) { - return; + return true; } let param = params.params[0] || 1; while (param--) { this._bufferService.buffer.x = this._bufferService.buffer.nextStop(); } + return true; } /** @@ -1070,9 +1177,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI CBT "Cursor Backward Tabulation" "CSI Ps Z" "Move cursor `Ps` tabs backward (default=1)." */ - public cursorBackwardTab(params: IParams): void { + public cursorBackwardTab(params: IParams): boolean { if (this._bufferService.buffer.x >= this._bufferService.cols) { - return; + return true; } let param = params.params[0] || 1; @@ -1082,6 +1189,7 @@ export class InputHandler extends Disposable implements IInputHandler { while (param--) { buffer.x = buffer.prevStop(); } + return true; } @@ -1140,7 +1248,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #P[Protection attributes are not supported.] CSI DECSED "Selective Erase In Display" "CSI ? Ps J" "Currently the same as ED." */ - public eraseInDisplay(params: IParams): void { + public eraseInDisplay(params: IParams): boolean { this._restrictCursor(); let j; switch (params.params[0]) { @@ -1187,6 +1295,7 @@ export class InputHandler extends Disposable implements IInputHandler { } break; } + return true; } /** @@ -1211,7 +1320,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #P[Protection attributes are not supported.] CSI DECSEL "Selective Erase In Line" "CSI ? Ps K" "Currently the same as EL." */ - public eraseInLine(params: IParams): void { + public eraseInLine(params: IParams): boolean { this._restrictCursor(); switch (params.params[0]) { case 0: @@ -1225,6 +1334,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } this._dirtyRowService.markDirty(this._bufferService.buffer.y); + return true; } /** @@ -1236,7 +1346,7 @@ export class InputHandler extends Disposable implements IInputHandler { * The cursor is set to the first column. * IL has no effect if the cursor is outside the scroll margins. */ - public insertLines(params: IParams): void { + public insertLines(params: IParams): boolean { this._restrictCursor(); let param = params.params[0] || 1; @@ -1244,7 +1354,7 @@ export class InputHandler extends Disposable implements IInputHandler { const buffer = this._bufferService.buffer; if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) { - return; + return true; } const row: number = buffer.ybase + buffer.y; @@ -1260,6 +1370,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom); buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only? + return true; } /** @@ -1271,7 +1382,7 @@ export class InputHandler extends Disposable implements IInputHandler { * The cursor is set to the first column. * DL has no effect if the cursor is outside the scroll margins. */ - public deleteLines(params: IParams): void { + public deleteLines(params: IParams): boolean { this._restrictCursor(); let param = params.params[0] || 1; @@ -1279,7 +1390,7 @@ export class InputHandler extends Disposable implements IInputHandler { const buffer = this._bufferService.buffer; if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) { - return; + return true; } const row: number = buffer.ybase + buffer.y; @@ -1296,6 +1407,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom); buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only? + return true; } /** @@ -1309,7 +1421,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) */ - public insertChars(params: IParams): void { + public insertChars(params: IParams): boolean { this._restrictCursor(); const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + this._bufferService.buffer.y); if (line) { @@ -1321,6 +1433,7 @@ export class InputHandler extends Disposable implements IInputHandler { ); this._dirtyRowService.markDirty(this._bufferService.buffer.y); } + return true; } /** @@ -1334,7 +1447,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) */ - public deleteChars(params: IParams): void { + public deleteChars(params: IParams): boolean { this._restrictCursor(); const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + this._bufferService.buffer.y); if (line) { @@ -1346,6 +1459,7 @@ export class InputHandler extends Disposable implements IInputHandler { ); this._dirtyRowService.markDirty(this._bufferService.buffer.y); } + return true; } /** @@ -1356,7 +1470,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * FIXME: scrolled out lines at top = 1 should add to scrollback (xterm) */ - public scrollUp(params: IParams): void { + public scrollUp(params: IParams): boolean { let param = params.params[0] || 1; // make buffer local for faster access @@ -1367,6 +1481,7 @@ export class InputHandler extends Disposable implements IInputHandler { buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 0, buffer.getBlankLine(this._eraseAttrData())); } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1374,7 +1489,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI SD "Scroll Down" "CSI Ps T" "Scroll `Ps` lines down (default=1)." */ - public scrollDown(params: IParams): void { + public scrollDown(params: IParams): boolean { let param = params.params[0] || 1; // make buffer local for faster access @@ -1385,6 +1500,7 @@ export class InputHandler extends Disposable implements IInputHandler { buffer.lines.splice(buffer.ybase + buffer.scrollTop, 0, buffer.getBlankLine(DEFAULT_ATTR_DATA)); } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1405,10 +1521,10 @@ export class InputHandler extends Disposable implements IInputHandler { * SL moves the content of all lines within the scroll margins `Ps` times to the left. * SL has no effect outside of the scroll margins. */ - public scrollLeft(params: IParams): void { + public scrollLeft(params: IParams): boolean { const buffer = this._bufferService.buffer; if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) { - return; + return true; } const param = params.params[0] || 1; for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) { @@ -1417,6 +1533,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1438,10 +1555,10 @@ export class InputHandler extends Disposable implements IInputHandler { * Content at the right margin is lost. * SL has no effect outside of the scroll margins. */ - public scrollRight(params: IParams): void { + public scrollRight(params: IParams): boolean { const buffer = this._bufferService.buffer; if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) { - return; + return true; } const param = params.params[0] || 1; for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) { @@ -1450,6 +1567,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1461,10 +1579,10 @@ export class InputHandler extends Disposable implements IInputHandler { * moving content to the right. Content at the right margin is lost. * DECIC has no effect outside the scrolling margins. */ - public insertColumns(params: IParams): void { + public insertColumns(params: IParams): boolean { const buffer = this._bufferService.buffer; if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) { - return; + return true; } const param = params.params[0] || 1; for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) { @@ -1473,6 +1591,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1484,10 +1603,10 @@ export class InputHandler extends Disposable implements IInputHandler { * moving content to the left. Blank columns are added at the right margin. * DECDC has no effect outside the scrolling margins. */ - public deleteColumns(params: IParams): void { + public deleteColumns(params: IParams): boolean { const buffer = this._bufferService.buffer; if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) { - return; + return true; } const param = params.params[0] || 1; for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) { @@ -1496,6 +1615,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1506,7 +1626,7 @@ export class InputHandler extends Disposable implements IInputHandler { * ED erases `Ps` characters from current cursor position to the right. * ED works inside or outside the scrolling margins. */ - public eraseChars(params: IParams): void { + public eraseChars(params: IParams): boolean { this._restrictCursor(); const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + this._bufferService.buffer.y); if (line) { @@ -1518,6 +1638,7 @@ export class InputHandler extends Disposable implements IInputHandler { ); this._dirtyRowService.markDirty(this._bufferService.buffer.y); } + return true; } /** @@ -1547,9 +1668,9 @@ export class InputHandler extends Disposable implements IInputHandler { * REP has no effect if the sequence does not follow a printable ASCII character * (NOOP for any other sequence in between or NON ASCII characters). */ - public repeatPrecedingCharacter(params: IParams): void { + public repeatPrecedingCharacter(params: IParams): boolean { if (!this._parser.precedingCodepoint) { - return; + return true; } // call print to insert the chars and handle correct wrapping const length = params.params[0] || 1; @@ -1558,6 +1679,7 @@ export class InputHandler extends Disposable implements IInputHandler { data[i] = this._parser.precedingCodepoint; } this.print(data, 0, data.length); + return true; } /** @@ -1585,15 +1707,16 @@ export class InputHandler extends Disposable implements IInputHandler { * * TODO: fix and cleanup response */ - public sendDeviceAttributesPrimary(params: IParams): void { + public sendDeviceAttributesPrimary(params: IParams): boolean { if (params.params[0] > 0) { - return; + return true; } if (this._is('xterm') || this._is('rxvt-unicode') || this._is('screen')) { this._coreService.triggerDataEvent(C0.ESC + '[?1;2c'); } else if (this._is('linux')) { this._coreService.triggerDataEvent(C0.ESC + '[?6c'); } + return true; } /** @@ -1620,9 +1743,9 @@ export class InputHandler extends Disposable implements IInputHandler { * * TODO: fix and cleanup response */ - public sendDeviceAttributesSecondary(params: IParams): void { + public sendDeviceAttributesSecondary(params: IParams): boolean { if (params.params[0] > 0) { - return; + return true; } // xterm and urxvt // seem to spit this @@ -1638,6 +1761,7 @@ export class InputHandler extends Disposable implements IInputHandler { } else if (this._is('screen')) { this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c'); } + return true; } /** @@ -1665,7 +1789,7 @@ export class InputHandler extends Disposable implements IInputHandler { * | 12 | Send/receive (SRM). Always off. | #N | * | 20 | Automatic Newline (LNM). Always off. | #N | */ - public setMode(params: IParams): void { + public setMode(params: IParams): boolean { for (let i = 0; i < params.length; i++) { switch (params.params[i]) { case 4: @@ -1676,6 +1800,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } /** @@ -1791,7 +1916,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * FIXME: implement DECSCNM, 1049 should clear altbuffer */ - public setModePrivate(params: IParams): void { + public setModePrivate(params: IParams): boolean { for (let i = 0; i < params.length; i++) { switch (params.params[i]) { case 1: @@ -1884,6 +2009,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } @@ -1907,7 +2033,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * FIXME: why is LNM commented out? */ - public resetMode(params: IParams): void { + public resetMode(params: IParams): boolean { for (let i = 0; i < params.length; i++) { switch (params.params[i]) { case 4: @@ -1918,6 +2044,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } /** @@ -2029,7 +2156,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * FIXME: DECCOLM is currently broken (already fixed in window options PR) */ - public resetModePrivate(params: IParams): void { + public resetModePrivate(params: IParams): boolean { for (let i = 0; i < params.length; i++) { switch (params.params[i]) { case 1: @@ -2106,6 +2233,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } /** @@ -2298,12 +2426,12 @@ export class InputHandler extends Disposable implements IInputHandler { * FIXME: blinking is implemented in attrs, but not working in renderers? * FIXME: remove dead branch for p=100 */ - public charAttributes(params: IParams): void { + public charAttributes(params: IParams): boolean { // Optimize a single SGR0. if (params.length === 1 && params.params[0] === 0) { this._curAttrData.fg = DEFAULT_ATTR_DATA.fg; this._curAttrData.bg = DEFAULT_ATTR_DATA.bg; - return; + return true; } const l = params.length; @@ -2402,6 +2530,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._logService.debug('Unknown SGR attribute: %d.', p); } } + return true; } /** @@ -2429,7 +2558,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI DSR "Device Status Report" "CSI Ps n" "Request cursor position (CPR) with `Ps` = 6." */ - public deviceStatus(params: IParams): void { + public deviceStatus(params: IParams): boolean { switch (params.params[0]) { case 5: // status report @@ -2442,10 +2571,11 @@ export class InputHandler extends Disposable implements IInputHandler { this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`); break; } + return true; } // @vt: #P[Only CPR is supported.] CSI DECDSR "DEC Device Status Report" "CSI ? Ps n" "Only CPR is supported (same as DSR)." - public deviceStatusPrivate(params: IParams): void { + public deviceStatusPrivate(params: IParams): boolean { // modern xterm doesnt seem to // respond to any of these except ?6, 6, and 5 switch (params.params[0]) { @@ -2472,6 +2602,7 @@ export class InputHandler extends Disposable implements IInputHandler { // this.handler(C0.ESC + '[?50n'); break; } + return true; } /** @@ -2493,7 +2624,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * FIXME: there are several more attributes missing (see VT520 manual) */ - public softReset(params: IParams): void { + public softReset(params: IParams): boolean { this._coreService.isCursorHidden = false; this._onRequestSyncScrollBar.fire(); this._bufferService.buffer.scrollTop = 0; @@ -2511,6 +2642,7 @@ export class InputHandler extends Disposable implements IInputHandler { // reset DECOM this._coreService.decPrivateModes.origin = false; + return true; } /** @@ -2532,7 +2664,7 @@ export class InputHandler extends Disposable implements IInputHandler { * - 5: steady bar * - 6: blink bar */ - public setCursorStyle(params: IParams): void { + public setCursorStyle(params: IParams): boolean { const param = params.params[0] || 1; switch (param) { case 1: @@ -2550,6 +2682,7 @@ export class InputHandler extends Disposable implements IInputHandler { } const isBlinking = param % 2 === 1; this._optionsService.options.cursorBlink = isBlinking; + return true; } /** @@ -2559,7 +2692,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y CSI DECSTBM "Set Top and Bottom Margin" "CSI Ps ; Ps r" "Set top and bottom margins of the viewport [top;bottom] (default = viewport size)." */ - public setScrollRegion(params: IParams): void { + public setScrollRegion(params: IParams): boolean { const top = params.params[0] || 1; let bottom: number; @@ -2572,6 +2705,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._bufferService.buffer.scrollBottom = bottom - 1; this._setCursor(0, 0); } + return true; } /** @@ -2604,9 +2738,9 @@ export class InputHandler extends Disposable implements IInputHandler { * Ps = 23 ; 2 -> Restore xterm window title from stack. supported * Ps >= 24 not implemented */ - public windowOptions(params: IParams): void { + public windowOptions(params: IParams): boolean { if (!paramToWindowOption(params.params[0], this._optionsService.options.windowOptions)) { - return; + return true; } const second = (params.length > 1) ? params.params[1] : 0; switch (params.params[0]) { @@ -2650,6 +2784,7 @@ export class InputHandler extends Disposable implements IInputHandler { } break; } + return true; } @@ -2661,12 +2796,13 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #P[TODO...] CSI SCOSC "Save Cursor" "CSI s" "Save cursor position, charmap and text attributes." * @vt: #Y ESC SC "Save Cursor" "ESC 7" "Save cursor position, charmap and text attributes." */ - public saveCursor(params?: IParams): void { + public saveCursor(params?: IParams): boolean { 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._curAttrData.fg; this._bufferService.buffer.savedCurAttrData.bg = this._curAttrData.bg; this._bufferService.buffer.savedCharset = this._charsetService.charset; + return true; } @@ -2678,7 +2814,7 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #P[TODO...] CSI SCORC "Restore Cursor" "CSI u" "Restore cursor position, charmap and text attributes." * @vt: #Y ESC RC "Restore Cursor" "ESC 8" "Restore cursor position, charmap and text attributes." */ - public restoreCursor(params?: IParams): void { + public restoreCursor(params?: IParams): boolean { 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._curAttrData.fg = this._bufferService.buffer.savedCurAttrData.fg; @@ -2688,6 +2824,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._charsetService.charset = this._bufferService.buffer.savedCharset; } this._restrictCursor(); + return true; } @@ -2701,23 +2838,25 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y OSC 2 "Set Windows Title" "OSC 2 ; Pt BEL" "Set window title." * xterm.js does not manipulate the title directly, instead exposes changes via the event `Terminal.onTitleChange`. */ - public setTitle(data: string): void { + public setTitle(data: string): boolean { this._windowTitle = data; this._onTitleChange.fire(data); + return true; } /** * OSC 1; ST * Note: Icon name is not exposed. */ - public setIconName(data: string): void { + public setIconName(data: string): boolean { this._iconName = data; + return true; } protected _parseAnsiColorChange(data: string): IAnsiColorChangeEvent | null { const result: IAnsiColorChangeEvent = { colors: [] }; // example data: 5;rgb:aa/bb/cc - const regex = /(\d+);rgb:([0-9a-f]{2})\/([0-9a-f]{2})\/([0-9a-f]{2})/gi; + const regex = /(\d+);rgb:([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})/gi; let match; while ((match = regex.exec(data)) !== null) { @@ -2743,7 +2882,7 @@ export class InputHandler extends Disposable implements IInputHandler { * `c` is the color index between 0 and 255. `spec` color format is 'rgb:hh/hh/hh' where `h` are hexadecimal digits. * There may be multipe c ; spec elements present in the same instruction, e.g. 1;rgb:10/20/30;2;rgb:a0/b0/c0. */ - public setAnsiColor(data: string): void { + public setAnsiColor(data: string): boolean { const event = this._parseAnsiColorChange(data); if (event) { this._onAnsiColorChange.fire(event); @@ -2751,6 +2890,7 @@ export class InputHandler extends Disposable implements IInputHandler { else { this._logService.warn(`Expected format ;rgb:// but got data: ${data}`); } + return true; } /** @@ -2762,9 +2902,10 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y C1 NEL "Next Line" "\x85" "Move the cursor to the beginning of the next row." * @vt: #Y ESC NEL "Next Line" "ESC E" "Move the cursor to the beginning of the next row." */ - public nextLine(): void { + public nextLine(): boolean { this._bufferService.buffer.x = 0; this.index(); + return true; } /** @@ -2772,10 +2913,11 @@ export class InputHandler extends Disposable implements IInputHandler { * 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 { + public keypadApplicationMode(): boolean { this._logService.debug('Serial port requested application keypad.'); this._coreService.decPrivateModes.applicationKeypad = true; this._onRequestSyncScrollBar.fire(); + return true; } /** @@ -2783,10 +2925,11 @@ export class InputHandler extends Disposable implements IInputHandler { * DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html) * Enables the keypad to send numeric characters to the host. */ - public keypadNumericMode(): void { + public keypadNumericMode(): boolean { this._logService.debug('Switching back to normal keypad.'); this._coreService.decPrivateModes.applicationKeypad = false; this._onRequestSyncScrollBar.fire(); + return true; } /** @@ -2795,9 +2938,10 @@ export class InputHandler extends Disposable implements IInputHandler { * Select default character set. UTF-8 is not supported (string are unicode anyways) * therefore ESC % G does the same. */ - public selectDefaultCharset(): void { + public selectDefaultCharset(): boolean { this._charsetService.setgLevel(0); this._charsetService.setgCharset(0, DEFAULT_CHARSET); // US (default) + return true; } /** @@ -2816,16 +2960,16 @@ export class InputHandler extends Disposable implements IInputHandler { * ESC / C * Designate G3 Character Set (VT300). C = A -> ISO Latin-1 Supplemental. - Supported? */ - public selectCharset(collectAndFlag: string): void { + public selectCharset(collectAndFlag: string): boolean { if (collectAndFlag.length !== 2) { this.selectDefaultCharset(); - return; + return true; } if (collectAndFlag[0] === '/') { - return; // TODO: Is this supported? + return true; // TODO: Is this supported? } this._charsetService.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET); - return; + return true; } /** @@ -2837,7 +2981,7 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y C1 IND "Index" "\x84" "Move the cursor one line down scrolling if needed." * @vt: #Y ESC IND "Index" "ESC D" "Move the cursor one line down scrolling if needed." */ - public index(): void { + public index(): boolean { this._restrictCursor(); const buffer = this._bufferService.buffer; this._bufferService.buffer.y++; @@ -2848,6 +2992,7 @@ export class InputHandler extends Disposable implements IInputHandler { buffer.y = this._bufferService.rows - 1; } this._restrictCursor(); + return true; } /** @@ -2860,8 +3005,9 @@ export class InputHandler extends Disposable implements IInputHandler { * @vt: #Y C1 HTS "Horizontal Tabulation Set" "\x88" "Places a tab stop at the current cursor position." * @vt: #Y ESC HTS "Horizontal Tabulation Set" "ESC H" "Places a tab stop at the current cursor position." */ - public tabSet(): void { + public tabSet(): boolean { this._bufferService.buffer.tabs[this._bufferService.buffer.x] = true; + return true; } /** @@ -2873,7 +3019,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y ESC IR "Reverse Index" "ESC M" "Move the cursor one line up scrolling if needed." */ - public reverseIndex(): void { + public reverseIndex(): boolean { this._restrictCursor(); const buffer = this._bufferService.buffer; if (buffer.y === buffer.scrollTop) { @@ -2888,6 +3034,7 @@ export class InputHandler extends Disposable implements IInputHandler { buffer.y--; this._restrictCursor(); // quickfix to not run out of bounds } + return true; } /** @@ -2895,9 +3042,10 @@ export class InputHandler extends Disposable implements IInputHandler { * DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html) * Reset to initial state. */ - public fullReset(): void { + public fullReset(): boolean { this._parser.reset(); this._onRequestReset.fire(); + return true; } public reset(): void { @@ -2924,8 +3072,9 @@ export class InputHandler extends Disposable implements IInputHandler { * 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 { + public setgLevel(level: number): boolean { this._charsetService.setgLevel(level); + return true; } /** @@ -2936,7 +3085,7 @@ export class InputHandler extends Disposable implements IInputHandler { * * @vt: #Y ESC DECALN "Screen Alignment Pattern" "ESC # 8" "Fill viewport with a test pattern (E)." */ - public screenAlignmentPattern(): void { + public screenAlignmentPattern(): boolean { // prepare cell data const cell = new CellData(); cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0); @@ -2956,5 +3105,6 @@ export class InputHandler extends Disposable implements IInputHandler { } this._dirtyRowService.markAllDirty(); this._setCursor(0, 0); + return true; } } diff --git a/src/common/TestUtils.test.ts b/src/common/TestUtils.test.ts index 35357744..01ceacbd 100644 --- a/src/common/TestUtils.test.ts +++ b/src/common/TestUtils.test.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { IBufferService, ICoreService, ILogService, IOptionsService, ITerminalOptions, IPartialTerminalOptions, IDirtyRowService, ICoreMouseService, ICharsetService, IUnicodeService, IUnicodeVersionProvider } from 'common/services/Services'; +import { IBufferService, ICoreService, ILogService, IOptionsService, ITerminalOptions, IPartialTerminalOptions, IDirtyRowService, ICoreMouseService, ICharsetService, IUnicodeService, IUnicodeVersionProvider, LogLevelEnum } from 'common/services/Services'; import { IEvent, EventEmitter } from 'common/EventEmitter'; import { clone } from 'common/Clone'; import { DEFAULT_OPTIONS } from 'common/services/OptionsService'; @@ -92,6 +92,7 @@ export class MockDirtyRowService implements IDirtyRowService { export class MockLogService implements ILogService { public serviceBrand: any; + public logLevel = LogLevelEnum.DEBUG; public debug(message: any, ...optionalParams: any[]): void {} public info(message: any, ...optionalParams: any[]): void {} public warn(message: any, ...optionalParams: any[]): void {} diff --git a/src/common/Types.d.ts b/src/common/Types.d.ts index b76d29ae..2dd3f4b8 100644 --- a/src/common/Types.d.ts +++ b/src/common/Types.d.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { ITerminalOptions as IPublicTerminalOptions } from 'xterm'; +import { IFunctionIdentifier, ITerminalOptions as IPublicTerminalOptions } from 'xterm'; import { IEvent, IEventEmitter } from 'common/EventEmitter'; import { IDeleteEvent, IInsertEvent } from 'common/CircularList'; import { IParams } from 'common/parser/Types'; @@ -359,8 +359,12 @@ export interface IInputHandler { onTitleChange: IEvent; onRequestScroll: IEvent; - parse(data: string | Uint8Array): void; + parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise; print(data: Uint32Array, start: number, end: number): void; + registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise): IDisposable; + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise): IDisposable; + registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise): IDisposable; + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable; /** C0 BEL */ bell(): void; /** C0 LF */ lineFeed(): void; @@ -437,3 +441,11 @@ export interface IInputHandler { ESC ~ */ setgLevel(level: number): void; /** ESC # 8 */ screenAlignmentPattern(): void; } + +interface IParseStack { + paused: boolean; + cursorStartX: number; + cursorStartY: number; + decodedLength: number; + position: number; +} diff --git a/src/common/buffer/BufferLine.test.ts b/src/common/buffer/BufferLine.test.ts index 4c5fc3a4..fa15a854 100644 --- a/src/common/buffer/BufferLine.test.ts +++ b/src/common/buffer/BufferLine.test.ts @@ -6,7 +6,7 @@ import { NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, DEFAULT_ATTR, Content, import { BufferLine } from 'common/buffer//BufferLine'; import { CellData } from 'common/buffer/CellData'; import { CharData, IBufferLine } from '../Types'; -import { assert, expect } from 'chai'; +import { assert } from 'chai'; import { AttributeData } from 'common/buffer/AttributeData'; @@ -151,20 +151,20 @@ describe('CellData', () => { describe('BufferLine', function(): void { it('ctor', function(): void { let line: IBufferLine = new TestBufferLine(0); - expect(line.length).equals(0); - expect(line.isWrapped).equals(false); + assert.equal(line.length, 0); + assert.equal(line.isWrapped, false); line = new TestBufferLine(10); - expect(line.length).equals(10); - expect(line.loadCell(0, new CellData()).getAsCharData()).eql([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); - expect(line.isWrapped).equals(false); + assert.equal(line.length, 10); + assert.deepEqual(line.loadCell(0, new CellData()).getAsCharData(), [0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); + assert.equal(line.isWrapped, false); line = new TestBufferLine(10, undefined, true); - expect(line.length).equals(10); - expect(line.loadCell(0, new CellData()).getAsCharData()).eql([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); - expect(line.isWrapped).equals(true); + assert.equal(line.length, 10); + assert.deepEqual(line.loadCell(0, new CellData()).getAsCharData(), [0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); + assert.equal(line.isWrapped, true); line = new TestBufferLine(10, CellData.fromCharData([123, 'a', 456, 'a'.charCodeAt(0)]), true); - expect(line.length).equals(10); - expect(line.loadCell(0, new CellData()).getAsCharData()).eql([123, 'a', 456, 'a'.charCodeAt(0)]); - expect(line.isWrapped).equals(true); + assert.equal(line.length, 10); + assert.deepEqual(line.loadCell(0, new CellData()).getAsCharData(), [123, 'a', 456, 'a'.charCodeAt(0)]); + assert.equal(line.isWrapped, true); }); it('insertCells', function(): void { const line = new TestBufferLine(3); @@ -172,7 +172,7 @@ describe('BufferLine', function(): void { line.setCell(1, CellData.fromCharData([2, 'b', 0, 'b'.charCodeAt(0)])); line.setCell(2, CellData.fromCharData([3, 'c', 0, 'c'.charCodeAt(0)])); line.insertCells(1, 3, CellData.fromCharData([4, 'd', 0, 'd'.charCodeAt(0)])); - expect(line.toArray()).eql([ + assert.deepEqual(line.toArray(), [ [1, 'a', 0, 'a'.charCodeAt(0)], [4, 'd', 0, 'd'.charCodeAt(0)], [4, 'd', 0, 'd'.charCodeAt(0)] @@ -186,7 +186,7 @@ describe('BufferLine', function(): void { line.setCell(3, CellData.fromCharData([4, 'd', 0, 'd'.charCodeAt(0)])); line.setCell(4, CellData.fromCharData([5, 'e', 0, 'e'.charCodeAt(0)])); line.deleteCells(1, 2, CellData.fromCharData([6, 'f', 0, 'f'.charCodeAt(0)])); - expect(line.toArray()).eql([ + assert.deepEqual(line.toArray(), [ [1, 'a', 0, 'a'.charCodeAt(0)], [4, 'd', 0, 'd'.charCodeAt(0)], [5, 'e', 0, 'e'.charCodeAt(0)], @@ -202,7 +202,7 @@ describe('BufferLine', function(): void { line.setCell(3, CellData.fromCharData([4, 'd', 0, 'd'.charCodeAt(0)])); line.setCell(4, CellData.fromCharData([5, 'e', 0, 'e'.charCodeAt(0)])); line.replaceCells(2, 4, CellData.fromCharData([6, 'f', 0, 'f'.charCodeAt(0)])); - expect(line.toArray()).eql([ + assert.deepEqual(line.toArray(), [ [1, 'a', 0, 'a'.charCodeAt(0)], [2, 'b', 0, 'b'.charCodeAt(0)], [6, 'f', 0, 'f'.charCodeAt(0)], @@ -218,7 +218,7 @@ describe('BufferLine', function(): void { line.setCell(3, CellData.fromCharData([4, 'd', 0, 'd'.charCodeAt(0)])); line.setCell(4, CellData.fromCharData([5, 'e', 0, 'e'.charCodeAt(0)])); line.fill(CellData.fromCharData([123, 'z', 0, 'z'.charCodeAt(0)])); - expect(line.toArray()).eql([ + assert.deepEqual(line.toArray(), [ [123, 'z', 0, 'z'.charCodeAt(0)], [123, 'z', 0, 'z'.charCodeAt(0)], [123, 'z', 0, 'z'.charCodeAt(0)], @@ -234,9 +234,9 @@ describe('BufferLine', function(): void { line.setCell(3, CellData.fromCharData([4, 'd', 0, 'd'.charCodeAt(0)])); line.setCell(4, CellData.fromCharData([5, 'e', 0, 'e'.charCodeAt(0)])); const line2 = line.clone(); - expect(TestBufferLine.prototype.toArray.apply(line2)).eql(line.toArray()); - expect(line2.length).equals(line.length); - expect(line2.isWrapped).equals(line.isWrapped); + assert.deepEqual(TestBufferLine.prototype.toArray.apply(line2), line.toArray()); + assert.equal(line2.length, line.length); + assert.equal(line2.isWrapped, line.isWrapped); }); it('copyFrom', function(): void { const line = new TestBufferLine(5); @@ -247,92 +247,92 @@ describe('BufferLine', function(): void { line.setCell(4, CellData.fromCharData([5, 'e', 0, 'e'.charCodeAt(0)])); const line2 = new TestBufferLine(5, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)]), true); line2.copyFrom(line); - expect(line2.toArray()).eql(line.toArray()); - expect(line2.length).equals(line.length); - expect(line2.isWrapped).equals(line.isWrapped); + assert.deepEqual(line2.toArray(), line.toArray()); + assert.equal(line2.length, line.length); + assert.equal(line2.isWrapped, line.isWrapped); }); it('should support combining chars', function(): void { // CHAR_DATA_CODE_INDEX resembles current behavior in InputHandler.print // --> set code to the last charCodeAt value of the string // Note: needs to be fixed once the string pointer is in place const line = new TestBufferLine(2, CellData.fromCharData([1, 'e\u0301', 0, '\u0301'.charCodeAt(0)])); - expect(line.toArray()).eql([[1, 'e\u0301', 0, '\u0301'.charCodeAt(0)], [1, 'e\u0301', 0, '\u0301'.charCodeAt(0)]]); + assert.deepEqual(line.toArray(), [[1, 'e\u0301', 0, '\u0301'.charCodeAt(0)], [1, 'e\u0301', 0, '\u0301'.charCodeAt(0)]]); const line2 = new TestBufferLine(5, CellData.fromCharData([1, 'a', 0, '\u0301'.charCodeAt(0)]), true); line2.copyFrom(line); - expect(line2.toArray()).eql(line.toArray()); + assert.deepEqual(line2.toArray(), line.toArray()); const line3 = line.clone(); - expect(TestBufferLine.prototype.toArray.apply(line3)).eql(line.toArray()); + assert.deepEqual(TestBufferLine.prototype.toArray.apply(line3), line.toArray()); }); describe('resize', function(): void { it('enlarge(false)', function(): void { const line = new TestBufferLine(5, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)]), false); line.resize(10, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)])); - expect(line.toArray()).eql((Array(10) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); + assert.deepEqual(line.toArray(), (Array(10) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); }); it('enlarge(true)', function(): void { const line = new TestBufferLine(5, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)]), false); line.resize(10, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)])); - expect(line.toArray()).eql((Array(10) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); + assert.deepEqual(line.toArray(), (Array(10) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); }); it('shrink(true) - should apply new size', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)]), false); line.resize(5, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)])); - expect(line.toArray()).eql((Array(5) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); + assert.deepEqual(line.toArray(), (Array(5) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); }); it('shrink to 0 length', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)]), false); line.resize(0, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)])); - expect(line.toArray()).eql((Array(0) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); + assert.deepEqual(line.toArray(), (Array(0) as any).fill([1, 'a', 0, 'a'.charCodeAt(0)])); }); it('should remove combining data on replaced cells after shrinking then enlarging', () => { const line = new TestBufferLine(10, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)]), false); line.set(2, [ 0, '😁', 1, '😁'.charCodeAt(0) ]); line.set(9, [ 0, '😁', 1, '😁'.charCodeAt(0) ]); - expect(line.translateToString()).eql('aa😁aaaaaa😁'); - expect(Object.keys(line.combined).length).eql(2); + assert.equal(line.translateToString(), 'aa😁aaaaaa😁'); + assert.equal(Object.keys(line.combined).length, 2); line.resize(5, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)])); - expect(line.translateToString()).eql('aa😁aa'); + assert.equal(line.translateToString(), 'aa😁aa'); line.resize(10, CellData.fromCharData([1, 'a', 0, 'a'.charCodeAt(0)])); - expect(line.translateToString()).eql('aa😁aaaaaaa'); - expect(Object.keys(line.combined).length).eql(1); + assert.equal(line.translateToString(), 'aa😁aaaaaaa'); + assert.equal(Object.keys(line.combined).length, 1); }); }); describe('getTrimLength', function(): void { it('empty line', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); - expect(line.getTrimmedLength()).equal(0); + assert.equal(line.getTrimmedLength(), 0); }); it('ASCII', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); line.setCell(0, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(2, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); - expect(line.getTrimmedLength()).equal(3); + assert.equal(line.getTrimmedLength(), 3); }); it('surrogate', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); line.setCell(0, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(2, CellData.fromCharData([1, '𝄞', 1, '𝄞'.charCodeAt(0)])); - expect(line.getTrimmedLength()).equal(3); + assert.equal(line.getTrimmedLength(), 3); }); it('combining', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); line.setCell(0, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(2, CellData.fromCharData([1, 'e\u0301', 1, '\u0301'.charCodeAt(0)])); - expect(line.getTrimmedLength()).equal(3); + assert.equal(line.getTrimmedLength(), 3); }); it('fullwidth', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); line.setCell(0, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(2, CellData.fromCharData([1, '1', 2, '1'.charCodeAt(0)])); line.setCell(3, CellData.fromCharData([0, '', 0, 0])); - expect(line.getTrimmedLength()).equal(4); // also counts null cell after fullwidth + assert.equal(line.getTrimmedLength(), 4); // also counts null cell after fullwidth }); }); describe('translateToString with and w\'o trimming', function(): void { it('empty line', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); - expect(line.translateToString(false)).equal(' '); - expect(line.translateToString(true)).equal(''); + assert.equal(line.translateToString(false), ' '); + assert.equal(line.translateToString(true), ''); }); it('ASCII', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); @@ -340,14 +340,14 @@ describe('BufferLine', function(): void { line.setCell(2, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(4, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(5, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); - expect(line.translateToString(false)).equal('a a aa '); - expect(line.translateToString(true)).equal('a a aa'); - expect(line.translateToString(false, 0, 5)).equal('a a a'); - expect(line.translateToString(false, 0, 4)).equal('a a '); - expect(line.translateToString(false, 0, 3)).equal('a a'); - expect(line.translateToString(true, 0, 5)).equal('a a a'); - expect(line.translateToString(true, 0, 4)).equal('a a '); - expect(line.translateToString(true, 0, 3)).equal('a a'); + assert.equal(line.translateToString(false), 'a a aa '); + assert.equal(line.translateToString(true), 'a a aa'); + assert.equal(line.translateToString(false, 0, 5), 'a a a'); + assert.equal(line.translateToString(false, 0, 4), 'a a '); + assert.equal(line.translateToString(false, 0, 3), 'a a'); + assert.equal(line.translateToString(true, 0, 5), 'a a a'); + assert.equal(line.translateToString(true, 0, 4), 'a a '); + assert.equal(line.translateToString(true, 0, 3), 'a a'); }); it('surrogate', function(): void { @@ -356,14 +356,14 @@ describe('BufferLine', function(): void { line.setCell(2, CellData.fromCharData([1, '𝄞', 1, '𝄞'.charCodeAt(0)])); line.setCell(4, CellData.fromCharData([1, '𝄞', 1, '𝄞'.charCodeAt(0)])); line.setCell(5, CellData.fromCharData([1, '𝄞', 1, '𝄞'.charCodeAt(0)])); - expect(line.translateToString(false)).equal('a 𝄞 𝄞𝄞 '); - expect(line.translateToString(true)).equal('a 𝄞 𝄞𝄞'); - expect(line.translateToString(false, 0, 5)).equal('a 𝄞 𝄞'); - expect(line.translateToString(false, 0, 4)).equal('a 𝄞 '); - expect(line.translateToString(false, 0, 3)).equal('a 𝄞'); - expect(line.translateToString(true, 0, 5)).equal('a 𝄞 𝄞'); - expect(line.translateToString(true, 0, 4)).equal('a 𝄞 '); - expect(line.translateToString(true, 0, 3)).equal('a 𝄞'); + assert.equal(line.translateToString(false), 'a 𝄞 𝄞𝄞 '); + assert.equal(line.translateToString(true), 'a 𝄞 𝄞𝄞'); + assert.equal(line.translateToString(false, 0, 5), 'a 𝄞 𝄞'); + assert.equal(line.translateToString(false, 0, 4), 'a 𝄞 '); + assert.equal(line.translateToString(false, 0, 3), 'a 𝄞'); + assert.equal(line.translateToString(true, 0, 5), 'a 𝄞 𝄞'); + assert.equal(line.translateToString(true, 0, 4), 'a 𝄞 '); + assert.equal(line.translateToString(true, 0, 3), 'a 𝄞'); }); it('combining', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); @@ -371,14 +371,14 @@ describe('BufferLine', function(): void { line.setCell(2, CellData.fromCharData([1, 'e\u0301', 1, '\u0301'.charCodeAt(0)])); line.setCell(4, CellData.fromCharData([1, 'e\u0301', 1, '\u0301'.charCodeAt(0)])); line.setCell(5, CellData.fromCharData([1, 'e\u0301', 1, '\u0301'.charCodeAt(0)])); - expect(line.translateToString(false)).equal('a e\u0301 e\u0301e\u0301 '); - expect(line.translateToString(true)).equal('a e\u0301 e\u0301e\u0301'); - expect(line.translateToString(false, 0, 5)).equal('a e\u0301 e\u0301'); - expect(line.translateToString(false, 0, 4)).equal('a e\u0301 '); - expect(line.translateToString(false, 0, 3)).equal('a e\u0301'); - expect(line.translateToString(true, 0, 5)).equal('a e\u0301 e\u0301'); - expect(line.translateToString(true, 0, 4)).equal('a e\u0301 '); - expect(line.translateToString(true, 0, 3)).equal('a e\u0301'); + assert.equal(line.translateToString(false), 'a e\u0301 e\u0301e\u0301 '); + assert.equal(line.translateToString(true), 'a e\u0301 e\u0301e\u0301'); + assert.equal(line.translateToString(false, 0, 5), 'a e\u0301 e\u0301'); + assert.equal(line.translateToString(false, 0, 4), 'a e\u0301 '); + assert.equal(line.translateToString(false, 0, 3), 'a e\u0301'); + assert.equal(line.translateToString(true, 0, 5), 'a e\u0301 e\u0301'); + assert.equal(line.translateToString(true, 0, 4), 'a e\u0301 '); + assert.equal(line.translateToString(true, 0, 3), 'a e\u0301'); }); it('fullwidth', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); @@ -389,20 +389,20 @@ describe('BufferLine', function(): void { line.setCell(6, CellData.fromCharData([0, '', 0, 0])); line.setCell(7, CellData.fromCharData([1, '1', 2, '1'.charCodeAt(0)])); line.setCell(8, CellData.fromCharData([0, '', 0, 0])); - expect(line.translateToString(false)).equal('a 1 11 '); - expect(line.translateToString(true)).equal('a 1 11'); - expect(line.translateToString(false, 0, 7)).equal('a 1 1'); - expect(line.translateToString(false, 0, 6)).equal('a 1 1'); - expect(line.translateToString(false, 0, 5)).equal('a 1 '); - expect(line.translateToString(false, 0, 4)).equal('a 1'); - expect(line.translateToString(false, 0, 3)).equal('a 1'); - expect(line.translateToString(false, 0, 2)).equal('a '); - expect(line.translateToString(true, 0, 7)).equal('a 1 1'); - expect(line.translateToString(true, 0, 6)).equal('a 1 1'); - expect(line.translateToString(true, 0, 5)).equal('a 1 '); - expect(line.translateToString(true, 0, 4)).equal('a 1'); - expect(line.translateToString(true, 0, 3)).equal('a 1'); - expect(line.translateToString(true, 0, 2)).equal('a '); + assert.equal(line.translateToString(false), 'a 1 11 '); + assert.equal(line.translateToString(true), 'a 1 11'); + assert.equal(line.translateToString(false, 0, 7), 'a 1 1'); + assert.equal(line.translateToString(false, 0, 6), 'a 1 1'); + assert.equal(line.translateToString(false, 0, 5), 'a 1 '); + assert.equal(line.translateToString(false, 0, 4), 'a 1'); + assert.equal(line.translateToString(false, 0, 3), 'a 1'); + assert.equal(line.translateToString(false, 0, 2), 'a '); + assert.equal(line.translateToString(true, 0, 7), 'a 1 1'); + assert.equal(line.translateToString(true, 0, 6), 'a 1 1'); + assert.equal(line.translateToString(true, 0, 5), 'a 1 '); + assert.equal(line.translateToString(true, 0, 4), 'a 1'); + assert.equal(line.translateToString(true, 0, 3), 'a 1'); + assert.equal(line.translateToString(true, 0, 2), 'a '); }); it('space at end', function(): void { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]), false); @@ -411,21 +411,21 @@ describe('BufferLine', function(): void { line.setCell(4, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(5, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); line.setCell(6, CellData.fromCharData([1, ' ', 1, ' '.charCodeAt(0)])); - expect(line.translateToString(false)).equal('a a aa '); - expect(line.translateToString(true)).equal('a a aa '); + assert.equal(line.translateToString(false), 'a a aa '); + assert.equal(line.translateToString(true), 'a a aa '); }); it('should always return some sane value', function(): void { // sanity check - broken line with invalid out of bound null width cells // this can atm happen with deleting/inserting chars in inputhandler by "breaking" // fullwidth pairs --> needs to be fixed after settling BufferLine impl const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, 0, NULL_CELL_CODE]), false); - expect(line.translateToString(false)).equal(' '); - expect(line.translateToString(true)).equal(''); + assert.equal(line.translateToString(false), ' '); + assert.equal(line.translateToString(true), ''); }); it('should work with endCol=0', () => { const line = new TestBufferLine(10, CellData.fromCharData([DEFAULT_ATTR, NULL_CELL_CHAR, 0, NULL_CELL_CODE]), false); line.setCell(0, CellData.fromCharData([1, 'a', 1, 'a'.charCodeAt(0)])); - expect(line.translateToString(true, 0, 0)).equal(''); + assert.equal(line.translateToString(true, 0, 0), ''); }); }); describe('addCharToCell', () => { diff --git a/src/common/input/TextDecoder.test.ts b/src/common/input/TextDecoder.test.ts index 92b0e03a..da1760a2 100644 --- a/src/common/input/TextDecoder.test.ts +++ b/src/common/input/TextDecoder.test.ts @@ -58,8 +58,8 @@ describe('text encodings', () => { const decoder = new StringToUtf32(); const target = new Uint32Array(5); for (let i = 0; i < 65536; ++i) { - // skip surrogate pairs - if (i >= 0xD800 && i <= 0xDFFF) { + // skip surrogate pairs and a BOM + if ((i >= 0xD800 && i <= 0xDFFF) || i === 0xFEFF) { continue; } const length = decoder.decode(String.fromCharCode(i), target); @@ -84,6 +84,14 @@ describe('text encodings', () => { decoder.clear(); } }); + + it('0xFEFF(BOM)', () => { + const decoder = new StringToUtf32(); + const target = new Uint32Array(5); + const length = decoder.decode(String.fromCharCode(0xFEFF), target); + assert.equal(length, 0); + decoder.clear(); + }); }); it('test strings', () => { @@ -118,8 +126,8 @@ describe('text encodings', () => { const decoder = new Utf8ToUtf32(); const target = new Uint32Array(5); for (let i = 0; i < 65536; ++i) { - // skip surrogate pairs - if (i >= 0xD800 && i <= 0xDFFF) { + // skip surrogate pairs and a BOM + if ((i >= 0xD800 && i <= 0xDFFF) || i === 0xFEFF) { continue; } const utf8Data = fromByteString(encode(String.fromCharCode(i))); @@ -142,6 +150,15 @@ describe('text encodings', () => { decoder.clear(); } }); + + it('0xFEFF(BOM)', () => { + const decoder = new Utf8ToUtf32(); + const target = new Uint32Array(5); + const utf8Data = fromByteString(encode(String.fromCharCode(0xFEFF))); + const length = decoder.decode(utf8Data, target); + assert.equal(length, 0); + decoder.clear(); + }); }); it('test strings', () => { @@ -215,6 +232,19 @@ describe('text encodings', () => { } assert(decoded, 'Ä€𝄞Ö𝄞€Ü𝄞€'); }); + + it('BOMs (3 byte sequences) - advance by 2', () => { + const decoder = new Utf8ToUtf32(); + const target = new Uint32Array(5); + const utf8Data = fromByteString('\xef\xbb\xbf\xef\xbb\xbf'); + let decoded = ''; + for (let i = 0; i < utf8Data.length; i += 2) { + const written = decoder.decode(utf8Data.slice(i, i + 2), target); + decoded += toString(target, written); + } + assert.equal(decoded, ''); + }); + it('test break after 3 bytes - issue #2495', () => { const decoder = new Utf8ToUtf32(); const target = new Uint32Array(5); diff --git a/src/common/input/TextDecoder.ts b/src/common/input/TextDecoder.ts index 6ecab011..715e9197 100644 --- a/src/common/input/TextDecoder.ts +++ b/src/common/input/TextDecoder.ts @@ -105,6 +105,10 @@ export class StringToUtf32 { } continue; } + if (code === 0xFEFF) { + // BOM + continue; + } target[size++] = code; } return size; @@ -188,8 +192,8 @@ export class Utf8ToUtf32 { target[size++] = cp; } } else if (type === 3) { - if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF)) { - // illegal codepoint + if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF) || cp === 0xFEFF) { + // illegal codepoint or BOM } else { target[size++] = cp; } @@ -286,8 +290,8 @@ export class Utf8ToUtf32 { continue; } codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F); - if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) { - // illegal codepoint, no i-- here + if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint === 0xFEFF) { + // illegal codepoint or BOM, no i-- here continue; } target[size++] = codepoint; diff --git a/src/common/input/WriteBuffer.test.ts b/src/common/input/WriteBuffer.test.ts index d3dfebd0..89106423 100644 --- a/src/common/input/WriteBuffer.test.ts +++ b/src/common/input/WriteBuffer.test.ts @@ -85,5 +85,26 @@ describe('WriteBuffer', () => { done(); }); }); + it('writeSync called from action does not overflow callstack - issue #3265', () => { + wb = new WriteBuffer(data => { + const num = parseInt(data as string); + if (num < 1000000) { + wb.writeSync('' + (num + 1)); + } + }); + wb.writeSync('1'); + }); + it('writeSync maxSubsequentCalls argument', () => { + let last: string = ''; + wb = new WriteBuffer(data => { + last = data as string; + const num = parseInt(data as string); + if (num < 1000000) { + wb.writeSync('' + (num + 1), 10); + } + }); + wb.writeSync('1', 10); + assert.equal(last, '11'); // 1 + 10 sub calls = 11 + }); }); }); diff --git a/src/common/input/WriteBuffer.ts b/src/common/input/WriteBuffer.ts index c7d82458..cc84c9ab 100644 --- a/src/common/input/WriteBuffer.ts +++ b/src/common/input/WriteBuffer.ts @@ -31,33 +31,66 @@ const WRITE_TIMEOUT_MS = 12; */ const WRITE_BUFFER_LENGTH_THRESHOLD = 50; +// queueMicrotask polyfill for nodejs < v11 +const qmt: (cb: () => void) => void = (typeof queueMicrotask === 'undefined') + ? (cb: () => void) => { Promise.resolve().then(cb); } + : queueMicrotask; + + export class WriteBuffer { private _writeBuffer: (string | Uint8Array)[] = []; private _callbacks: ((() => void) | undefined)[] = []; private _pendingData = 0; private _bufferOffset = 0; + private _isSyncWriting = false; + private _syncCalls = 0; - constructor(private _action: (data: string | Uint8Array) => void) { } + constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise) { } + + /** + * @deprecated Unreliable, to be removed soon. + */ + public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void { + // stop writeSync recursions with maxSubsequentCalls argument + // This is dangerous to use as it will lose the current data chunk + // and return immediately. + if (maxSubsequentCalls !== undefined && this._syncCalls > maxSubsequentCalls) { + // comment next line if a whole loop block should only contain x `writeSync` calls + // (total flat vs. deep nested limit) + this._syncCalls = 0; + return; + } + // append chunk to buffer + this._pendingData += data.length; + this._writeBuffer.push(data); + this._callbacks.push(undefined); + + // increase recursion counter + this._syncCalls++; + // exit early if another writeSync loop is active + if (this._isSyncWriting) { + return; + } + this._isSyncWriting = true; - 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; + // we have to do it here as single loop steps to not corrupt loop subject + // by another writeSync call triggered from _action + let chunk: string | Uint8Array | undefined; + while (chunk = this._writeBuffer.shift()) { + this._action(chunk); + const cb = this._callbacks.shift(); + if (cb) cb(); } - // handle current data chunk - this._action(data); + // reset to avoid reprocessing of chunks with scheduled innerWrite call + // stopping scheduled innerWrite by offset > length condition + this._pendingData = 0; + this._bufferOffset = 0x7FFFFFFF; + + // allow another writeSync to loop + this._isSyncWriting = false; + this._syncCalls = 0; } public write(data: string | Uint8Array, callback?: () => void): void { @@ -76,16 +109,97 @@ export class WriteBuffer { this._callbacks.push(callback); } - protected _innerWrite(): void { - const startTime = Date.now(); + /** + * Inner write call, that enters the sliced chunk processing by timing. + * + * `lastTime` indicates, when the last _innerWrite call had started. + * It is used to aggregate async handler execution under a timeout constraint + * effectively lowering the redrawing needs, schematically: + * + * macroTask _innerWrite: + * if (Date.now() - (lastTime | 0) < WRITE_TIMEOUT_MS): + * schedule microTask _innerWrite(lastTime) + * else: + * schedule macroTask _innerWrite(0) + * + * overall execution order on task queues: + * + * macrotasks: [...] --> _innerWrite(0) --> [...] --> screenUpdate --> [...] + * m t: | + * i a: [...] + * c s: | + * r k: while < timeout: + * o s: _innerWrite(timeout) + * + * `promiseResult` depicts the promise resolve value of an async handler. + * This value gets carried forward through all saved stack states of the + * paused parser for proper continuation. + * + * Note, for pure sync code `lastTime` and `promiseResult` have no meaning. + */ + protected _innerWrite(lastTime: number = 0, promiseResult: boolean = true): void { + const startTime = lastTime || Date.now(); while (this._writeBuffer.length > this._bufferOffset) { const data = this._writeBuffer[this._bufferOffset]; - const cb = this._callbacks[this._bufferOffset]; - this._bufferOffset++; + const result = this._action(data, promiseResult); + if (result) { + /** + * If we get a promise as return value, we re-schedule the continuation + * as thenable on the promise and exit right away. + * + * The exit here means, that we block input processing at the current active chunk, + * the exact execution position within the chunk is preserved by the saved + * stack content in InputHandler and EscapeSequenceParser. + * + * Resuming happens automatically from that saved stack state. + * Also the resolved promise value is passed along the callstack to + * `EscapeSequenceParser.parse` to correctly resume the stopped handler loop. + * + * Exceptions on async handlers will be logged to console async, but do not interrupt + * the input processing (continues with next handler at the current input position). + */ - this._action(data); - this._pendingData -= data.length; + /** + * If a promise takes long to resolve, we should schedule continuation behind setTimeout. + * This might already be too late, if our .then enters really late (executor + prev thens took very long). + * This cannot be solved here for the handler itself (it is the handlers responsibility to slice hard work), + * but we can at least schedule a screen update as we gain control. + */ + const continuation: (r: boolean) => void = (r: boolean) => Date.now() - startTime >= WRITE_TIMEOUT_MS + ? setTimeout(() => this._innerWrite(0, r)) + : this._innerWrite(startTime, r); + + /** + * Optimization considerations: + * The continuation above favors FPS over throughput by eval'ing `startTime` on resolve. + * This might schedule too many screen updates with bad throughput drops (in case a slow + * resolving handler sliced its work properly behind setTimeout calls). We cannot spot + * this condition here, also the renderer has no way to spot nonsense updates either. + * FIXME: A proper fix for this would track the FPS at the renderer entry level separately. + * + * If favoring of FPS shows bad throughtput impact, use the following instead. It favors + * throughput by eval'ing `startTime` upfront pulling at least one more chunk into the + * current microtask queue (executed before setTimeout). + */ + // const continuation: (r: boolean) => void = Date.now() - startTime >= WRITE_TIMEOUT_MS + // ? r => setTimeout(() => this._innerWrite(0, r)) + // : r => this._innerWrite(startTime, r); + + // Handle exceptions synchronously to current band position, idea: + // 1. spawn a single microtask which we allow to throw hard + // 2. spawn a promise immediately resolving to `true` + // (executed on the same queue, thus properly aligned before continuation happens) + result.catch(err => { + qmt(() => {throw err;}); + return Promise.resolve(false); + }).then(continuation); + return; + } + + const cb = this._callbacks[this._bufferOffset]; if (cb) cb(); + this._bufferOffset++; + this._pendingData -= data.length; if (Date.now() - startTime >= WRITE_TIMEOUT_MS) { break; @@ -99,10 +213,10 @@ export class WriteBuffer { this._callbacks = this._callbacks.slice(this._bufferOffset); this._bufferOffset = 0; } - setTimeout(() => this._innerWrite(), 0); + setTimeout(() => this._innerWrite()); } else { - this._writeBuffer = []; - this._callbacks = []; + this._writeBuffer.length = 0; + this._callbacks.length = 0; this._pendingData = 0; this._bufferOffset = 0; } diff --git a/src/common/parser/DcsParser.test.ts b/src/common/parser/DcsParser.test.ts index dbabb4fa..096ebb58 100644 --- a/src/common/parser/DcsParser.test.ts +++ b/src/common/parser/DcsParser.test.ts @@ -61,11 +61,12 @@ class TestHandler implements IDcsHandler { public put(data: Uint32Array, start: number, end: number): void { this.output.push([this.msg, 'PUT', utf32ToString(data, start, end)]); } - public unhook(success: boolean): void | boolean { + public unhook(success: boolean): boolean { this.output.push([this.msg, 'UNHOOK', success]); if (this.returnFalse) { return false; } + return true; } } @@ -84,7 +85,7 @@ describe('DcsParser', () => { }); describe('handler registration', () => { it('setDcsHandler', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th')); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th')); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); parser.put(data, 0, data.length); @@ -100,7 +101,7 @@ describe('DcsParser', () => { ]); }); it('clearDcsHandler', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th')); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th')); parser.clearHandler(identifier({intermediates: '+', final: 'p'})); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); @@ -117,8 +118,8 @@ describe('DcsParser', () => { ]); }); it('addDcsHandler', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th1')); - parser.addHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th2')); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th1')); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th2')); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); parser.put(data, 0, data.length); @@ -137,8 +138,8 @@ describe('DcsParser', () => { ]); }); it('addDcsHandler with return false', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th1')); - parser.addHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th2', true)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th1')); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th2', true)); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); parser.put(data, 0, data.length); @@ -157,8 +158,8 @@ describe('DcsParser', () => { ]); }); it('dispose handlers', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th1')); - const dispo = parser.addHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th2', true)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th1')); + const dispo = parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 'th2', true)); dispo.dispose(); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); @@ -176,7 +177,7 @@ describe('DcsParser', () => { }); describe('DcsHandlerFactory', () => { it('should be called once on end(true)', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => reports.push([params.toArray(), data]))); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push([params.toArray(), data]); return true; })); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); parser.put(data, 0, data.length); @@ -186,7 +187,7 @@ describe('DcsParser', () => { assert.deepEqual(reports, [[[1, 2, 3], 'Here comes the mouse!']]); }); it('should not be called on end(false)', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => reports.push([params.toArray(), data]))); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push([params.toArray(), data]); return true; })); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); parser.put(data, 0, data.length); @@ -196,8 +197,8 @@ describe('DcsParser', () => { assert.deepEqual(reports, []); }); it('should be disposable', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => reports.push(['one', params.toArray(), data]))); - const dispo = parser.addHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => reports.push(['two', params.toArray(), data]))); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push(['one', params.toArray(), data]); return true; })); + const dispo = parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push(['two', params.toArray(), data]); return true; })); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); parser.put(data, 0, data.length); @@ -215,8 +216,8 @@ describe('DcsParser', () => { assert.deepEqual(reports, [['two', [1, 2, 3], 'Here comes the mouse!'], ['one', [1, 2, 3], 'some other data']]); }); it('should respect return false', () => { - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => reports.push(['one', params.toArray(), data]))); - parser.addHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push(['two', params.toArray(), data]); return false; })); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push(['one', params.toArray(), data]); return true; })); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push(['two', params.toArray(), data]); return false; })); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('Here comes'); parser.put(data, 0, data.length); @@ -227,7 +228,7 @@ describe('DcsParser', () => { }); it('should work up to payload limit', function(): void { this.timeout(10000); - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => reports.push([params.toArray(), data]))); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push([params.toArray(), data]); return true; })); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); const data = toUtf32('A'.repeat(1000)); for (let i = 0; i < PAYLOAD_LIMIT; i += 1000) { @@ -238,7 +239,7 @@ describe('DcsParser', () => { }); it('should abort for payload limit +1', function(): void { this.timeout(10000); - parser.setHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => reports.push([params.toArray(), data]))); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler((data, params) => { reports.push([params.toArray(), data]); return true; })); parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); let data = toUtf32('A'.repeat(1000)); for (let i = 0; i < PAYLOAD_LIMIT; i += 1000) { @@ -251,3 +252,208 @@ describe('DcsParser', () => { }); }); }); + + +class TestHandlerAsync implements IDcsHandler { + constructor(public output: any[], public msg: string, public returnFalse: boolean = false) {} + public hook(params: IParams): void { + this.output.push([this.msg, 'HOOK', params.toArray()]); + } + public put(data: Uint32Array, start: number, end: number): void { + this.output.push([this.msg, 'PUT', utf32ToString(data, start, end)]); + } + public async unhook(success: boolean): Promise { + // simple sleep to check in tests whether ordering gets messed up + await new Promise(res => setTimeout(res, 20)); + this.output.push([this.msg, 'UNHOOK', success]); + if (this.returnFalse) { + return false; + } + return true; + } +} +async function unhookP(parser: DcsParser, success: boolean): Promise { + let result: void | Promise; + let prev: boolean | undefined; + while (result = parser.unhook(success, prev)) { + prev = await result; + } +} + + +describe('DcsParser - async tests', () => { + let parser: DcsParser; + let reports: any[] = []; + beforeEach(() => { + reports = []; + parser = new DcsParser(); + parser.setHandlerFallback((id, action, data) => { + if (action === 'HOOK') { + data = data.toArray(); + } + reports.push([id, action, data]); + }); + }); + describe('sync and async mixed', () => { + describe('sync | async | sync', () => { + it('first should run, cleanup action for others', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 's1', false)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandlerAsync(reports, 'a1', false)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 's2', false)); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['s2', 'HOOK', [1, 2, 3]], + ['a1', 'HOOK', [1, 2, 3]], + ['s1', 'HOOK', [1, 2, 3]], + ['s2', 'PUT', 'Here comes'], + ['a1', 'PUT', 'Here comes'], + ['s1', 'PUT', 'Here comes'], + ['s2', 'PUT', 'the mouse!'], + ['a1', 'PUT', 'the mouse!'], + ['s1', 'PUT', 'the mouse!'], + ['s2', 'UNHOOK', true], + ['a1', 'UNHOOK', false], // important: a1 before s1 + ['s1', 'UNHOOK', false] + ]); + }); + it('all should run', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 's1', true)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandlerAsync(reports, 'a1', true)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 's2', true)); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['s2', 'HOOK', [1, 2, 3]], + ['a1', 'HOOK', [1, 2, 3]], + ['s1', 'HOOK', [1, 2, 3]], + ['s2', 'PUT', 'Here comes'], + ['a1', 'PUT', 'Here comes'], + ['s1', 'PUT', 'Here comes'], + ['s2', 'PUT', 'the mouse!'], + ['a1', 'PUT', 'the mouse!'], + ['s1', 'PUT', 'the mouse!'], + ['s2', 'UNHOOK', true], + ['a1', 'UNHOOK', true], // important: a1 before s1 + ['s1', 'UNHOOK', true] + ]); + }); + }); + describe('async | sync | async', () => { + it('first should run, cleanup action for others', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandlerAsync(reports, 'a1', false)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 's1', false)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandlerAsync(reports, 'a2', false)); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['a2', 'HOOK', [1, 2, 3]], + ['s1', 'HOOK', [1, 2, 3]], + ['a1', 'HOOK', [1, 2, 3]], + ['a2', 'PUT', 'Here comes'], + ['s1', 'PUT', 'Here comes'], + ['a1', 'PUT', 'Here comes'], + ['a2', 'PUT', 'the mouse!'], + ['s1', 'PUT', 'the mouse!'], + ['a1', 'PUT', 'the mouse!'], + ['a2', 'UNHOOK', true], + ['s1', 'UNHOOK', false], // important: s1 between a2 .. a1 + ['a1', 'UNHOOK', false] + ]); + }); + it('all should run', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandlerAsync(reports, 'a1', true)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandler(reports, 's1', true)); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new TestHandlerAsync(reports, 'a2', true)); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['a2', 'HOOK', [1, 2, 3]], + ['s1', 'HOOK', [1, 2, 3]], + ['a1', 'HOOK', [1, 2, 3]], + ['a2', 'PUT', 'Here comes'], + ['s1', 'PUT', 'Here comes'], + ['a1', 'PUT', 'Here comes'], + ['a2', 'PUT', 'the mouse!'], + ['s1', 'PUT', 'the mouse!'], + ['a1', 'PUT', 'the mouse!'], + ['a2', 'UNHOOK', true], + ['s1', 'UNHOOK', true], // important: s1 between a2 .. a1 + ['a1', 'UNHOOK', true] + ]); + }); + }); + describe('DcsHandlerFactory', () => { + it('should be called once on end(true)', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler(async (data, params) => { reports.push([params.toArray(), data]); return true; })); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [[[1, 2, 3], 'Here comes the mouse!']]); + }); + it('should not be called on end(false)', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler(async (data, params) => { reports.push([params.toArray(), data]); return true; })); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, false); + assert.deepEqual(reports, []); + }); + it('should be disposable', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler(async (data, params) => { reports.push(['one', params.toArray(), data]); return true; })); + const dispo = parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler(async (data, params) => { reports.push(['two', params.toArray(), data]); return true; })); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [['two', [1, 2, 3], 'Here comes the mouse!']]); + dispo.dispose(); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + data = toUtf32('some other'); + parser.put(data, 0, data.length); + data = toUtf32(' data'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [['two', [1, 2, 3], 'Here comes the mouse!'], ['one', [1, 2, 3], 'some other data']]); + }); + it('should respect return false', async () => { + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler(async (data, params) => { reports.push(['one', params.toArray(), data]); return true; })); + parser.registerHandler(identifier({intermediates: '+', final: 'p'}), new DcsHandler(async (data, params) => { reports.push(['two', params.toArray(), data]); return false; })); + parser.hook(identifier({intermediates: '+', final: 'p'}), Params.fromArray([1, 2, 3])); + let data = toUtf32('Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + await unhookP(parser, true); + assert.deepEqual(reports, [['two', [1, 2, 3], 'Here comes the mouse!'], ['one', [1, 2, 3], 'Here comes the mouse!']]); + }); + }); + }); +}); diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index a09fd68c..b66524ba 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -4,7 +4,7 @@ */ import { IDisposable } from 'common/Types'; -import { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType } from 'common/parser/Types'; +import { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType, ISubParserStackState } from 'common/parser/Types'; import { utf32ToString } from 'common/input/TextDecoder'; import { Params } from 'common/parser/Params'; import { PAYLOAD_LIMIT } from 'common/parser/Constants'; @@ -15,14 +15,20 @@ export class DcsParser implements IDcsParser { private _handlers: IHandlerCollection = Object.create(null); private _active: IDcsHandler[] = EMPTY_HANDLERS; private _ident: number = 0; - private _handlerFb: DcsFallbackHandlerType = () => {}; + private _handlerFb: DcsFallbackHandlerType = () => { }; + private _stack: ISubParserStackState = { + paused: false, + loopPosition: 0, + fallThrough: false + }; public dispose(): void { this._handlers = Object.create(null); - this._handlerFb = () => {}; + this._handlerFb = () => { }; + this._active = EMPTY_HANDLERS; } - public addHandler(ident: number, handler: IDcsHandler): IDisposable { + public registerHandler(ident: number, handler: IDcsHandler): IDisposable { if (this._handlers[ident] === undefined) { this._handlers[ident] = []; } @@ -38,10 +44,6 @@ export class DcsParser implements IDcsParser { }; } - public setHandler(ident: number, handler: IDcsHandler): void { - this._handlers[ident] = [handler]; - } - public clearHandler(ident: number): void { if (this._handlers[ident]) delete this._handlers[ident]; } @@ -51,9 +53,13 @@ export class DcsParser implements IDcsParser { } public reset(): void { + // force cleanup leftover handlers if (this._active.length) { - this.unhook(false); + for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) { + this._active[j].unhook(false); + } } + this._stack.paused = false; this._active = EMPTY_HANDLERS; this._ident = 0; } @@ -82,20 +88,42 @@ export class DcsParser implements IDcsParser { } } - public unhook(success: boolean): void { + public unhook(success: boolean, promiseResult: boolean = true): void | Promise { if (!this._active.length) { this._handlerFb(this._ident, 'UNHOOK', success); } else { + let handlerResult: boolean | Promise = false; let j = this._active.length - 1; - for (; j >= 0; j--) { - if (this._active[j].unhook(success) !== false) { - break; - } + let fallThrough = false; + if (this._stack.paused) { + j = this._stack.loopPosition - 1; + handlerResult = promiseResult; + fallThrough = this._stack.fallThrough; + this._stack.paused = false; } - j--; - // cleanup left over handlers + if (!fallThrough && handlerResult === false) { + for (; j >= 0; j--) { + handlerResult = this._active[j].unhook(success); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = false; + return handlerResult; + } + } + j--; + } + // cleanup left over handlers (fallThrough for async) for (; j >= 0; j--) { - this._active[j].unhook(false); + handlerResult = this._active[j].unhook(false); + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } } } this._active = EMPTY_HANDLERS; @@ -103,19 +131,27 @@ export class DcsParser implements IDcsParser { } } +// predefine empty params as [0] (ZDM) +const EMPTY_PARAMS = new Params(); +EMPTY_PARAMS.addParam(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 _params: IParams = EMPTY_PARAMS; private _hitLimit: boolean = false; - constructor(private _handler: (data: string, params: IParams) => any) {} + constructor(private _handler: (data: string, params: IParams) => boolean | Promise) { } public hook(params: IParams): void { - this._params = params.clone(); + // since we need to preserve params until `unhook`, we have to clone it + // (only borrowed from parser and spans multiple parser states) + // perf optimization: + // clone only, if we have non empty params, otherwise stick with default + this._params = (params.length > 1 || params.params[0]) ? params.clone() : EMPTY_PARAMS; this._data = ''; this._hitLimit = false; } @@ -131,14 +167,24 @@ export class DcsHandler implements IDcsHandler { } } - public unhook(success: boolean): any { - let ret; + public unhook(success: boolean): boolean | Promise { + let ret: boolean | Promise = false; if (this._hitLimit) { ret = false; } else if (success) { - ret = this._handler(this._data, this._params || new Params()); + ret = this._handler(this._data, this._params); + if (ret instanceof Promise) { + // need to hold data and params until `ret` got resolved + // dont care for errors, data will be freed anyway on next start + return ret.then(res => { + this._params = EMPTY_PARAMS; + this._data = ''; + this._hitLimit = false; + return res; + }); + } } - this._params = undefined; + this._params = EMPTY_PARAMS; this._data = ''; this._hitLimit = false; return ret; diff --git a/src/common/parser/EscapeSequenceParser.test.ts b/src/common/parser/EscapeSequenceParser.test.ts index 4934d346..4b23fa00 100644 --- a/src/common/parser/EscapeSequenceParser.test.ts +++ b/src/common/parser/EscapeSequenceParser.test.ts @@ -3,9 +3,9 @@ * @license MIT */ -import { IParsingState, IParams, ParamsArray, IOscParser, IOscHandler, OscFallbackHandlerType, IFunctionIdentifier } from 'common/parser/Types'; +import { IParsingState, IParams, ParamsArray, IOscParser, IOscHandler, OscFallbackHandlerType, IFunctionIdentifier, IParserStackState, ParserStackType, ResumableHandlersType } from 'common/parser/Types'; import { EscapeSequenceParser, TransitionTable, VT500_TRANSITION_TABLE } from 'common/parser/EscapeSequenceParser'; -import * as chai from 'chai'; +import { assert } from 'chai'; import { StringToUtf32, stringFromCodePoint, utf32ToString } from 'common/input/TextDecoder'; import { ParserState } from 'common/parser/Constants'; import { Params } from 'common/parser/Params'; @@ -24,7 +24,7 @@ function r(a: number, b: number): string[] { } class MockOscPutParser implements IOscParser { - private _fallback: OscFallbackHandlerType = () => {}; + private _fallback: OscFallbackHandlerType = () => { }; public data = ''; public reset(): void { this.data = ''; @@ -41,7 +41,7 @@ class MockOscPutParser implements IOscParser { this._fallback(id, 'END', this.data.slice(this.data.indexOf(';') + 1)); } } - public addHandler(ident: number, handler: IOscHandler): IDisposable { + public registerHandler(ident: number, handler: IOscHandler): IDisposable { throw new Error('not implemented'); } public setHandler(ident: number, handler: IOscHandler): void { @@ -92,43 +92,58 @@ class TestEscapeSequenceParser extends EscapeSequenceParser { public identifier(id: IFunctionIdentifier): number { return this._identifier(id); } + public get parseStack(): IParserStackState { + return this._parseStack; + } + private _trackStack = false; + public trackStackSavesOnPause(): void { + this._trackStack = true; + } + public trackedStack: IParserStackState[] = []; + public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise { + const result = super.parse(data, length, promiseResult); + if (result instanceof Promise && this._trackStack) { + this.trackedStack.push({ ...this.parseStack }); + } + return result; + } } // test object to collect parser actions and compare them with expected values const testTerminal: any = { calls: [], - clear: function (): void { + clear(): void { this.calls = []; }, - compare: function (value: any): void { - chai.expect(this.calls.slice()).eql(value); // weird bug w'o slicing here + compare(value: any): void { + assert.deepEqual(this.calls, value); }, - print: function (data: Uint32Array, start: number, end: number): void { + print(data: Uint32Array, start: number, end: number): void { let s = ''; for (let i = start; i < end; ++i) { s += stringFromCodePoint(data[i]); } this.calls.push(['print', s]); }, - actionOSC: function (s: string): void { + actionOSC(s: string): void { this.calls.push(['osc', s]); }, - actionExecute: function (flag: string): void { + actionExecute(flag: string): void { this.calls.push(['exe', flag]); }, - actionCSI: function (collect: string, params: IParams, flag: string): void { + actionCSI(collect: string, params: IParams, flag: string): void { this.calls.push(['csi', collect, params.toArray(), flag]); }, - actionESC: function (collect: string, flag: string): void { + actionESC(collect: string, flag: string): void { this.calls.push(['esc', collect, flag]); }, - actionDCSHook: function (params: IParams): void { + actionDCSHook(params: IParams): void { this.calls.push(['dcs hook', params.toArray()]); }, - actionDCSPrint: function (s: string): void { + actionDCSPrint(s: string): void { this.calls.push(['dcs put', s]); }, - actionDCSUnhook: function (success: boolean): void { + actionDCSUnhook(success: boolean): void { this.calls.push(['dcs unhook', success]); } }; @@ -191,40 +206,40 @@ function parse(parser: TestEscapeSequenceParser, data: string): void { parser.parse(container, decoder.decode(data, container)); } -describe('EscapeSequenceParser', function (): void { +describe('EscapeSequenceParser', () => { const parser = testParser; - describe('Parser init and methods', function (): void { - it('constructor', function (): void { + describe('Parser init and methods', () => { + it('constructor', () => { let p = new TestEscapeSequenceParser(); - chai.expect(p.transitions).equal(VT500_TRANSITION_TABLE); + assert.deepEqual(p.transitions, VT500_TRANSITION_TABLE); p = new TestEscapeSequenceParser(VT500_TRANSITION_TABLE); - chai.expect(p.transitions).equal(VT500_TRANSITION_TABLE); + assert.deepEqual(p.transitions, VT500_TRANSITION_TABLE); const tansitions: TransitionTable = new TransitionTable(10); p = new TestEscapeSequenceParser(tansitions); - chai.expect(p.transitions).equal(tansitions); + assert.deepEqual(p.transitions, tansitions); }); - it('inital states', function (): void { - chai.expect(parser.initialState).equal(ParserState.GROUND); - chai.expect(parser.currentState).equal(ParserState.GROUND); - chai.expect(parser.osc).equal(''); - chai.expect(parser.params).eql([0]); - chai.expect(parser.collect).equal(''); + it('inital states', () => { + assert.equal(parser.initialState, ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); + assert.equal(parser.osc, ''); + assert.deepEqual(parser.params, [0]); + assert.equal(parser.collect, ''); }); - it('reset states', function (): void { + it('reset states', () => { parser.currentState = 124; parser.osc = '#'; parser.params = [123]; parser.collect = '#'; parser.reset(); - chai.expect(parser.currentState).equal(ParserState.GROUND); - chai.expect(parser.osc).equal(''); - chai.expect(parser.params).eql([0]); - chai.expect(parser.collect).equal(''); + assert.equal(parser.currentState, ParserState.GROUND); + assert.equal(parser.osc, ''); + assert.deepEqual(parser.params, [0]); + assert.equal(parser.collect, ''); }); }); - describe('state transitions and actions', function (): void { - it('state GROUND execute action', function (): void { + describe('state transitions and actions', () => { + it('state GROUND execute action', () => { parser.reset(); testTerminal.clear(); let exes = r(0x00, 0x18); @@ -233,26 +248,26 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = ParserState.GROUND; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state GROUND print action', function (): void { + it('state GROUND print action', () => { parser.reset(); testTerminal.clear(); const printables = r(0x20, 0x7f); // NOTE: DEL excluded for (let i = 0; i < printables.length; ++i) { parser.currentState = ParserState.GROUND; parse(parser, printables[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([['print', printables[i]]]); parser.reset(); testTerminal.clear(); } }); - it('trans ANYWHERE --> GROUND with actions', function (): void { + it('trans ANYWHERE --> GROUND with actions', () => { const exes = [ '\x18', '\x1a', '\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87', '\x88', @@ -269,32 +284,32 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = state; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare((state in exceptions ? exceptions[state][exes[i]] : 0) || [['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } parse(parser, '\x9c'); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([]); parser.reset(); testTerminal.clear(); } }); - it('trans ANYWHERE --> ESCAPE with clear', function (): void { + it('trans ANYWHERE --> ESCAPE with clear', () => { parser.reset(); for (state in states) { parser.currentState = state; parser.params = [23]; parser.collect = '#'; parse(parser, '\x1b'); - chai.expect(parser.currentState).equal(ParserState.ESCAPE); - chai.expect(parser.params).eql([0]); - chai.expect(parser.collect).equal(''); + assert.equal(parser.currentState, ParserState.ESCAPE); + assert.deepEqual(parser.params, [0]); + assert.equal(parser.collect, ''); parser.reset(); } }); - it('state ESCAPE execute rules', function (): void { + it('state ESCAPE execute rules', () => { parser.reset(); testTerminal.clear(); let exes = r(0x00, 0x18); @@ -303,23 +318,23 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = ParserState.ESCAPE; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.ESCAPE); + assert.equal(parser.currentState, ParserState.ESCAPE); testTerminal.compare([['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state ESCAPE ignore', function (): void { + it('state ESCAPE ignore', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.ESCAPE; parse(parser, '\x7f'); - chai.expect(parser.currentState).equal(ParserState.ESCAPE); + assert.equal(parser.currentState, ParserState.ESCAPE); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); - it('trans ESCAPE --> GROUND with ecs_dispatch action', function (): void { + it('trans ESCAPE --> GROUND with ecs_dispatch action', () => { parser.reset(); testTerminal.clear(); let dispatches = r(0x30, 0x50); @@ -329,24 +344,24 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < dispatches.length; ++i) { parser.currentState = ParserState.ESCAPE; parse(parser, dispatches[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([['esc', '', dispatches[i]]]); parser.reset(); testTerminal.clear(); } }); - it('trans ESCAPE --> ESCAPE_INTERMEDIATE with collect action', function (): void { + it('trans ESCAPE --> ESCAPE_INTERMEDIATE with collect action', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.ESCAPE; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.ESCAPE_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.ESCAPE_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('state ESCAPE_INTERMEDIATE execute rules', function (): void { + it('state ESCAPE_INTERMEDIATE execute rules', () => { parser.reset(); testTerminal.clear(); let exes = r(0x00, 0x18); @@ -355,57 +370,57 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = ParserState.ESCAPE_INTERMEDIATE; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.ESCAPE_INTERMEDIATE); + assert.equal(parser.currentState, ParserState.ESCAPE_INTERMEDIATE); testTerminal.compare([['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state ESCAPE_INTERMEDIATE ignore', function (): void { + it('state ESCAPE_INTERMEDIATE ignore', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.ESCAPE_INTERMEDIATE; parse(parser, '\x7f'); - chai.expect(parser.currentState).equal(ParserState.ESCAPE_INTERMEDIATE); + assert.equal(parser.currentState, ParserState.ESCAPE_INTERMEDIATE); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); - it('state ESCAPE_INTERMEDIATE collect action', function (): void { + it('state ESCAPE_INTERMEDIATE collect action', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.ESCAPE_INTERMEDIATE; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.ESCAPE_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.ESCAPE_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('trans ESCAPE_INTERMEDIATE --> GROUND with esc_dispatch action', function (): void { + it('trans ESCAPE_INTERMEDIATE --> GROUND with esc_dispatch action', () => { parser.reset(); testTerminal.clear(); const collect = r(0x30, 0x7f); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.ESCAPE_INTERMEDIATE; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); // '\x5c' --> ESC + \ (7bit ST) parser does not expose this as it already got handled testTerminal.compare((collect[i] === '\x5c') ? [] : [['esc', '', collect[i]]]); parser.reset(); testTerminal.clear(); } }); - it('trans ANYWHERE/ESCAPE --> CSI_ENTRY with clear', function (): void { + it('trans ANYWHERE/ESCAPE --> CSI_ENTRY with clear', () => { parser.reset(); // C0 parser.currentState = ParserState.ESCAPE; parser.params = [123]; parser.collect = '#'; parse(parser, '['); - chai.expect(parser.currentState).equal(ParserState.CSI_ENTRY); - chai.expect(parser.params).eql([0]); - chai.expect(parser.collect).equal(''); + assert.equal(parser.currentState, ParserState.CSI_ENTRY); + assert.deepEqual(parser.params, [0]); + assert.equal(parser.collect, ''); parser.reset(); // C1 for (state in states) { @@ -413,13 +428,13 @@ describe('EscapeSequenceParser', function (): void { parser.params = [123]; parser.collect = '#'; parse(parser, '\x9b'); - chai.expect(parser.currentState).equal(ParserState.CSI_ENTRY); - chai.expect(parser.params).eql([0]); - chai.expect(parser.collect).equal(''); + assert.equal(parser.currentState, ParserState.CSI_ENTRY); + assert.deepEqual(parser.params, [0]); + assert.equal(parser.collect, ''); parser.reset(); } }); - it('state CSI_ENTRY execute rules', function (): void { + it('state CSI_ENTRY execute rules', () => { parser.reset(); testTerminal.clear(); let exes = r(0x00, 0x18); @@ -428,59 +443,59 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = ParserState.CSI_ENTRY; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_ENTRY); + assert.equal(parser.currentState, ParserState.CSI_ENTRY); testTerminal.compare([['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state CSI_ENTRY ignore', function (): void { + it('state CSI_ENTRY ignore', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.CSI_ENTRY; parse(parser, '\x7f'); - chai.expect(parser.currentState).equal(ParserState.CSI_ENTRY); + assert.equal(parser.currentState, ParserState.CSI_ENTRY); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); - it('trans CSI_ENTRY --> GROUND with csi_dispatch action', function (): void { + it('trans CSI_ENTRY --> GROUND with csi_dispatch action', () => { parser.reset(); const dispatches = r(0x40, 0x7f); for (let i = 0; i < dispatches.length; ++i) { parser.currentState = ParserState.CSI_ENTRY; parse(parser, dispatches[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([['csi', '', [0], dispatches[i]]]); parser.reset(); testTerminal.clear(); } }); - it('trans CSI_ENTRY --> CSI_PARAM with param/collect actions', function (): void { + it('trans CSI_ENTRY --> CSI_PARAM with param/collect actions', () => { parser.reset(); const params = ['\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39']; const collect = ['\x3c', '\x3d', '\x3e', '\x3f']; for (let i = 0; i < params.length; ++i) { parser.currentState = ParserState.CSI_ENTRY; parse(parser, params[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); - chai.expect(parser.params).eql([params[i].charCodeAt(0) - 48]); + assert.equal(parser.currentState, ParserState.CSI_PARAM); + assert.deepEqual(parser.params, [params[i].charCodeAt(0) - 48]); parser.reset(); } parser.currentState = ParserState.CSI_ENTRY; parse(parser, '\x3b'); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); - chai.expect(parser.params).eql([0, 0]); + assert.equal(parser.currentState, ParserState.CSI_PARAM); + assert.deepEqual(parser.params, [0, 0]); parser.reset(); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.CSI_ENTRY; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.CSI_PARAM); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('state CSI_PARAM execute rules', function (): void { + it('state CSI_PARAM execute rules', () => { parser.reset(); testTerminal.clear(); let exes = r(0x00, 0x18); @@ -489,74 +504,74 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = ParserState.CSI_PARAM; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); + assert.equal(parser.currentState, ParserState.CSI_PARAM); testTerminal.compare([['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state CSI_PARAM param action', function (): void { + it('state CSI_PARAM param action', () => { parser.reset(); const params = ['\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39']; for (let i = 0; i < params.length; ++i) { parser.currentState = ParserState.CSI_PARAM; parse(parser, params[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); - chai.expect(parser.params).eql([params[i].charCodeAt(0) - 48]); + assert.equal(parser.currentState, ParserState.CSI_PARAM); + assert.deepEqual(parser.params, [params[i].charCodeAt(0) - 48]); parser.reset(); } parser.currentState = ParserState.CSI_PARAM; parse(parser, '\x3b'); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); - chai.expect(parser.params).eql([0, 0]); + assert.equal(parser.currentState, ParserState.CSI_PARAM); + assert.deepEqual(parser.params, [0, 0]); parser.reset(); }); - it('state CSI_PARAM ignore', function (): void { + it('state CSI_PARAM ignore', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.CSI_PARAM; parse(parser, '\x7f'); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); + assert.equal(parser.currentState, ParserState.CSI_PARAM); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); - it('trans CSI_PARAM --> GROUND with csi_dispatch action', function (): void { + it('trans CSI_PARAM --> GROUND with csi_dispatch action', () => { parser.reset(); const dispatches = r(0x40, 0x7f); for (let i = 0; i < dispatches.length; ++i) { parser.currentState = ParserState.CSI_PARAM; parser.params = [0, 1]; parse(parser, dispatches[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([['csi', '', [0, 1], dispatches[i]]]); parser.reset(); testTerminal.clear(); } }); - it('trans CSI_ENTRY --> CSI_INTERMEDIATE with collect action', function (): void { + it('trans CSI_ENTRY --> CSI_INTERMEDIATE with collect action', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.CSI_ENTRY; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.CSI_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('trans CSI_PARAM --> CSI_INTERMEDIATE with collect action', function (): void { + it('trans CSI_PARAM --> CSI_INTERMEDIATE with collect action', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.CSI_PARAM; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.CSI_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('state CSI_INTERMEDIATE execute rules', function (): void { + it('state CSI_INTERMEDIATE execute rules', () => { parser.reset(); testTerminal.clear(); let exes = r(0x00, 0x18); @@ -565,88 +580,88 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = ParserState.CSI_INTERMEDIATE; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_INTERMEDIATE); + assert.equal(parser.currentState, ParserState.CSI_INTERMEDIATE); testTerminal.compare([['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state CSI_INTERMEDIATE collect', function (): void { + it('state CSI_INTERMEDIATE collect', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.CSI_INTERMEDIATE; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.CSI_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('state CSI_INTERMEDIATE ignore', function (): void { + it('state CSI_INTERMEDIATE ignore', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.CSI_INTERMEDIATE; parse(parser, '\x7f'); - chai.expect(parser.currentState).equal(ParserState.CSI_INTERMEDIATE); + assert.equal(parser.currentState, ParserState.CSI_INTERMEDIATE); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); - it('trans CSI_INTERMEDIATE --> GROUND with csi_dispatch action', function (): void { + it('trans CSI_INTERMEDIATE --> GROUND with csi_dispatch action', () => { parser.reset(); const dispatches = r(0x40, 0x7f); for (let i = 0; i < dispatches.length; ++i) { parser.currentState = ParserState.CSI_INTERMEDIATE; parser.params = [0, 1]; parse(parser, dispatches[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([['csi', '', [0, 1], dispatches[i]]]); parser.reset(); testTerminal.clear(); } }); - it('trans CSI_ENTRY --> CSI_PARAM for ":" (0x3a)', function (): void { + it('trans CSI_ENTRY --> CSI_PARAM for ":" (0x3a)', () => { parser.reset(); parser.currentState = ParserState.CSI_ENTRY; parse(parser, '\x3a'); - chai.expect(parser.currentState).equal(ParserState.CSI_PARAM); + assert.equal(parser.currentState, ParserState.CSI_PARAM); parser.reset(); }); - it('trans CSI_PARAM --> CSI_IGNORE', function (): void { + it('trans CSI_PARAM --> CSI_IGNORE', () => { parser.reset(); const chars = ['\x3c', '\x3d', '\x3e', '\x3f']; for (let i = 0; i < chars.length; ++i) { parser.currentState = ParserState.CSI_PARAM; parse(parser, '\x3b' + chars[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_IGNORE); - chai.expect(parser.params).eql([0, 0]); + assert.equal(parser.currentState, ParserState.CSI_IGNORE); + assert.deepEqual(parser.params, [0, 0]); parser.reset(); } }); - it('trans CSI_PARAM --> CSI_IGNORE', function (): void { + it('trans CSI_PARAM --> CSI_IGNORE', () => { parser.reset(); const chars = ['\x3c', '\x3d', '\x3e', '\x3f']; for (let i = 0; i < chars.length; ++i) { - chai.expect(parser.params).eql([0]); + assert.deepEqual(parser.params, [0]); parser.currentState = ParserState.CSI_PARAM; parse(parser, '\x3b' + chars[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_IGNORE); - chai.expect(parser.params).eql([0, 0]); + assert.equal(parser.currentState, ParserState.CSI_IGNORE); + assert.deepEqual(parser.params, [0, 0]); parser.reset(); } }); - it('trans CSI_INTERMEDIATE --> CSI_IGNORE', function (): void { + it('trans CSI_INTERMEDIATE --> CSI_IGNORE', () => { parser.reset(); const chars = r(0x30, 0x40); for (let i = 0; i < chars.length; ++i) { parser.currentState = ParserState.CSI_INTERMEDIATE; parse(parser, chars[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_IGNORE); - chai.expect(parser.params).eql([0]); + assert.equal(parser.currentState, ParserState.CSI_IGNORE); + assert.deepEqual(parser.params, [0]); parser.reset(); } }); - it('state CSI_IGNORE execute rules', function (): void { + it('state CSI_IGNORE execute rules', () => { parser.reset(); testTerminal.clear(); let exes = r(0x00, 0x18); @@ -655,13 +670,13 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < exes.length; ++i) { parser.currentState = ParserState.CSI_IGNORE; parse(parser, exes[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_IGNORE); + assert.equal(parser.currentState, ParserState.CSI_IGNORE); testTerminal.compare([['exe', exes[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state CSI_IGNORE ignore', function (): void { + it('state CSI_IGNORE ignore', () => { parser.reset(); testTerminal.clear(); let ignored = r(0x20, 0x40); @@ -669,32 +684,32 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < ignored.length; ++i) { parser.currentState = ParserState.CSI_IGNORE; parse(parser, ignored[i]); - chai.expect(parser.currentState).equal(ParserState.CSI_IGNORE); + assert.equal(parser.currentState, ParserState.CSI_IGNORE); testTerminal.compare([]); parser.reset(); testTerminal.clear(); } }); - it('trans CSI_IGNORE --> GROUND', function (): void { + it('trans CSI_IGNORE --> GROUND', () => { parser.reset(); const dispatches = r(0x40, 0x7f); for (let i = 0; i < dispatches.length; ++i) { parser.currentState = ParserState.CSI_IGNORE; parser.params = [0, 1]; parse(parser, dispatches[i]); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([]); parser.reset(); testTerminal.clear(); } }); - it('trans ANYWHERE/ESCAPE --> SOS_PM_APC_STRING', function (): void { + it('trans ANYWHERE/ESCAPE --> SOS_PM_APC_STRING', () => { parser.reset(); // C0 let initializers = ['\x58', '\x5e', '\x5f']; for (let i = 0; i < initializers.length; ++i) { parse(parser, '\x1b' + initializers[i]); - chai.expect(parser.currentState).equal(ParserState.SOS_PM_APC_STRING); + assert.equal(parser.currentState, ParserState.SOS_PM_APC_STRING); parser.reset(); } // C1 @@ -703,12 +718,12 @@ describe('EscapeSequenceParser', function (): void { initializers = ['\x98', '\x9e', '\x9f']; for (let i = 0; i < initializers.length; ++i) { parse(parser, initializers[i]); - chai.expect(parser.currentState).equal(ParserState.SOS_PM_APC_STRING); + assert.equal(parser.currentState, ParserState.SOS_PM_APC_STRING); parser.reset(); } } }); - it('state SOS_PM_APC_STRING ignore rules', function (): void { + it('state SOS_PM_APC_STRING ignore rules', () => { parser.reset(); let ignored = r(0x00, 0x18); ignored = ignored.concat(['\x19']); @@ -717,25 +732,25 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < ignored.length; ++i) { parser.currentState = ParserState.SOS_PM_APC_STRING; parse(parser, ignored[i]); - chai.expect(parser.currentState).equal(ParserState.SOS_PM_APC_STRING); + assert.equal(parser.currentState, ParserState.SOS_PM_APC_STRING); parser.reset(); } }); - it('trans ANYWHERE/ESCAPE --> OSC_STRING', function (): void { + it('trans ANYWHERE/ESCAPE --> OSC_STRING', () => { parser.reset(); // C0 parse(parser, '\x1b]'); - chai.expect(parser.currentState).equal(ParserState.OSC_STRING); + assert.equal(parser.currentState, ParserState.OSC_STRING); parser.reset(); // C1 for (state in states) { parser.currentState = state; parse(parser, '\x9d'); - chai.expect(parser.currentState).equal(ParserState.OSC_STRING); + assert.equal(parser.currentState, ParserState.OSC_STRING); parser.reset(); } }); - it('state OSC_STRING ignore rules', function (): void { + it('state OSC_STRING ignore rules', () => { parser.reset(); const ignored = [ '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', /* '\x07', */ '\x08', @@ -744,37 +759,37 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < ignored.length; ++i) { parser.currentState = ParserState.OSC_STRING; parse(parser, ignored[i]); - chai.expect(parser.currentState).equal(ParserState.OSC_STRING); - chai.expect(parser.osc).equal(''); + assert.equal(parser.currentState, ParserState.OSC_STRING); + assert.equal(parser.osc, ''); parser.reset(); } }); - it('state OSC_STRING put action', function (): void { + it('state OSC_STRING put action', () => { parser.reset(); const puts = r(0x20, 0x80); for (let i = 0; i < puts.length; ++i) { parser.currentState = ParserState.OSC_STRING; parse(parser, puts[i]); - chai.expect(parser.currentState).equal(ParserState.OSC_STRING); - chai.expect(parser.osc).equal(puts[i]); + assert.equal(parser.currentState, ParserState.OSC_STRING); + assert.equal(parser.osc, puts[i]); parser.reset(); } }); - it('state DCS_ENTRY', function (): void { + it('state DCS_ENTRY', () => { parser.reset(); // C0 parse(parser, '\x1bP'); - chai.expect(parser.currentState).equal(ParserState.DCS_ENTRY); + assert.equal(parser.currentState, ParserState.DCS_ENTRY); parser.reset(); // C1 for (state in states) { parser.currentState = state; parse(parser, '\x90'); - chai.expect(parser.currentState).equal(ParserState.DCS_ENTRY); + assert.equal(parser.currentState, ParserState.DCS_ENTRY); parser.reset(); } }); - it('state DCS_ENTRY ignore rules', function (): void { + it('state DCS_ENTRY ignore rules', () => { parser.reset(); const ignored = [ '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', @@ -783,35 +798,35 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < ignored.length; ++i) { parser.currentState = ParserState.DCS_ENTRY; parse(parser, ignored[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_ENTRY); + assert.equal(parser.currentState, ParserState.DCS_ENTRY); parser.reset(); } }); - it('state DCS_ENTRY --> DCS_PARAM with param/collect actions', function (): void { + it('state DCS_ENTRY --> DCS_PARAM with param/collect actions', () => { parser.reset(); const params = ['\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39']; const collect = ['\x3c', '\x3d', '\x3e', '\x3f']; for (let i = 0; i < params.length; ++i) { parser.currentState = ParserState.DCS_ENTRY; parse(parser, params[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PARAM); - chai.expect(parser.params).eql([params[i].charCodeAt(0) - 48]); + assert.equal(parser.currentState, ParserState.DCS_PARAM); + assert.deepEqual(parser.params, [params[i].charCodeAt(0) - 48]); parser.reset(); } parser.currentState = ParserState.DCS_ENTRY; parse(parser, '\x3b'); - chai.expect(parser.currentState).equal(ParserState.DCS_PARAM); - chai.expect(parser.params).eql([0, 0]); + assert.equal(parser.currentState, ParserState.DCS_PARAM); + assert.deepEqual(parser.params, [0, 0]); parser.reset(); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.DCS_ENTRY; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PARAM); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.DCS_PARAM); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('state DCS_PARAM ignore rules', function (): void { + it('state DCS_PARAM ignore rules', () => { parser.reset(); const ignored = [ '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', @@ -820,55 +835,55 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < ignored.length; ++i) { parser.currentState = ParserState.DCS_PARAM; parse(parser, ignored[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PARAM); + assert.equal(parser.currentState, ParserState.DCS_PARAM); parser.reset(); } }); - it('state DCS_PARAM param action', function (): void { + it('state DCS_PARAM param action', () => { parser.reset(); const params = ['\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39']; for (let i = 0; i < params.length; ++i) { parser.currentState = ParserState.DCS_PARAM; parse(parser, params[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PARAM); - chai.expect(parser.params).eql([params[i].charCodeAt(0) - 48]); + assert.equal(parser.currentState, ParserState.DCS_PARAM); + assert.deepEqual(parser.params, [params[i].charCodeAt(0) - 48]); parser.reset(); } parser.currentState = ParserState.DCS_PARAM; parse(parser, '\x3b'); - chai.expect(parser.currentState).equal(ParserState.DCS_PARAM); - chai.expect(parser.params).eql([0, 0]); + assert.equal(parser.currentState, ParserState.DCS_PARAM); + assert.deepEqual(parser.params, [0, 0]); parser.reset(); }); - it('trans DCS_ENTRY --> DCS_PARAM for ":" (0x3a)', function (): void { + it('trans DCS_ENTRY --> DCS_PARAM for ":" (0x3a)', () => { parser.reset(); parser.currentState = ParserState.DCS_ENTRY; parse(parser, '\x3a'); - chai.expect(parser.currentState).equal(ParserState.DCS_PARAM); + assert.equal(parser.currentState, ParserState.DCS_PARAM); parser.reset(); }); - it('trans DCS_PARAM --> DCS_IGNORE', function (): void { + it('trans DCS_PARAM --> DCS_IGNORE', () => { parser.reset(); const chars = ['\x3c', '\x3d', '\x3e', '\x3f']; for (let i = 0; i < chars.length; ++i) { parser.currentState = ParserState.DCS_PARAM; parse(parser, '\x3b' + chars[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_IGNORE); - chai.expect(parser.params).eql([0, 0]); + assert.equal(parser.currentState, ParserState.DCS_IGNORE); + assert.deepEqual(parser.params, [0, 0]); parser.reset(); } }); - it('trans DCS_INTERMEDIATE --> DCS_IGNORE', function (): void { + it('trans DCS_INTERMEDIATE --> DCS_IGNORE', () => { parser.reset(); const chars = r(0x30, 0x40); for (let i = 0; i < chars.length; ++i) { parser.currentState = ParserState.DCS_INTERMEDIATE; parse(parser, chars[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_IGNORE); + assert.equal(parser.currentState, ParserState.DCS_IGNORE); parser.reset(); } }); - it('state DCS_IGNORE ignore rules', function (): void { + it('state DCS_IGNORE ignore rules', () => { parser.reset(); let ignored = [ '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', @@ -878,33 +893,33 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < ignored.length; ++i) { parser.currentState = ParserState.DCS_IGNORE; parse(parser, ignored[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_IGNORE); + assert.equal(parser.currentState, ParserState.DCS_IGNORE); parser.reset(); } }); - it('trans DCS_ENTRY --> DCS_INTERMEDIATE with collect action', function (): void { + it('trans DCS_ENTRY --> DCS_INTERMEDIATE with collect action', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.DCS_ENTRY; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.DCS_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('trans DCS_PARAM --> DCS_INTERMEDIATE with collect action', function (): void { + it('trans DCS_PARAM --> DCS_INTERMEDIATE with collect action', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.DCS_PARAM; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.DCS_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('state DCS_INTERMEDIATE ignore rules', function (): void { + it('state DCS_INTERMEDIATE ignore rules', () => { parser.reset(); const ignored = [ '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', @@ -913,72 +928,72 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < ignored.length; ++i) { parser.currentState = ParserState.DCS_INTERMEDIATE; parse(parser, ignored[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_INTERMEDIATE); + assert.equal(parser.currentState, ParserState.DCS_INTERMEDIATE); parser.reset(); } }); - it('state DCS_INTERMEDIATE collect action', function (): void { + it('state DCS_INTERMEDIATE collect action', () => { parser.reset(); const collect = r(0x20, 0x30); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.DCS_INTERMEDIATE; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_INTERMEDIATE); - chai.expect(parser.collect).equal(collect[i]); + assert.equal(parser.currentState, ParserState.DCS_INTERMEDIATE); + assert.equal(parser.collect, collect[i]); parser.reset(); } }); - it('trans DCS_INTERMEDIATE --> DCS_IGNORE', function (): void { + it('trans DCS_INTERMEDIATE --> DCS_IGNORE', () => { parser.reset(); const chars = r(0x30, 0x40); for (let i = 0; i < chars.length; ++i) { parser.currentState = ParserState.DCS_INTERMEDIATE; parse(parser, '\x20' + chars[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_IGNORE); - chai.expect(parser.collect).equal('\x20'); + assert.equal(parser.currentState, ParserState.DCS_IGNORE); + assert.equal(parser.collect, '\x20'); parser.reset(); } }); - it('trans DCS_ENTRY --> DCS_PASSTHROUGH with hook', function (): void { + it('trans DCS_ENTRY --> DCS_PASSTHROUGH with hook', () => { parser.reset(); testTerminal.clear(); const collect = r(0x40, 0x7f); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.DCS_ENTRY; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PASSTHROUGH); + assert.equal(parser.currentState, ParserState.DCS_PASSTHROUGH); testTerminal.compare([['dcs hook', [0]]]); parser.reset(); testTerminal.clear(); } }); - it('trans DCS_PARAM --> DCS_PASSTHROUGH with hook', function (): void { + it('trans DCS_PARAM --> DCS_PASSTHROUGH with hook', () => { parser.reset(); testTerminal.clear(); const collect = r(0x40, 0x7f); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.DCS_PARAM; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PASSTHROUGH); + assert.equal(parser.currentState, ParserState.DCS_PASSTHROUGH); testTerminal.compare([['dcs hook', [0]]]); parser.reset(); testTerminal.clear(); } }); - it('trans DCS_INTERMEDIATE --> DCS_PASSTHROUGH with hook', function (): void { + it('trans DCS_INTERMEDIATE --> DCS_PASSTHROUGH with hook', () => { parser.reset(); testTerminal.clear(); const collect = r(0x40, 0x7f); for (let i = 0; i < collect.length; ++i) { parser.currentState = ParserState.DCS_INTERMEDIATE; parse(parser, collect[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PASSTHROUGH); + assert.equal(parser.currentState, ParserState.DCS_PASSTHROUGH); testTerminal.compare([['dcs hook', [0]]]); parser.reset(); testTerminal.clear(); } }); - it('state DCS_PASSTHROUGH put action', function (): void { + it('state DCS_PASSTHROUGH put action', () => { parser.reset(); testTerminal.clear(); let puts = r(0x00, 0x18); @@ -988,18 +1003,18 @@ describe('EscapeSequenceParser', function (): void { for (let i = 0; i < puts.length; ++i) { parser.currentState = ParserState.DCS_PASSTHROUGH; parse(parser, puts[i]); - chai.expect(parser.currentState).equal(ParserState.DCS_PASSTHROUGH); + assert.equal(parser.currentState, ParserState.DCS_PASSTHROUGH); testTerminal.compare([['dcs put', puts[i]]]); parser.reset(); testTerminal.clear(); } }); - it('state DCS_PASSTHROUGH ignore', function (): void { + it('state DCS_PASSTHROUGH ignore', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.DCS_PASSTHROUGH; parse(parser, '\x7f'); - chai.expect(parser.currentState).equal(ParserState.DCS_PASSTHROUGH); + assert.equal(parser.currentState, ParserState.DCS_PASSTHROUGH); testTerminal.compare([]); parser.reset(); testTerminal.clear(); @@ -1015,8 +1030,8 @@ describe('EscapeSequenceParser', function (): void { testTerminal.compare(value); } - describe('escape sequence examples', function (): void { - it('CSI with print and execute', function (): void { + describe('escape sequence examples', () => { + it('CSI with print and execute', () => { test('\x1b[<31;5mHello World! öäü€\nabc', [ ['csi', '<', [31, 5], 'm'], @@ -1025,19 +1040,19 @@ describe('EscapeSequenceParser', function (): void { ['print', 'abc'] ], null); }); - it('OSC', function (): void { + it('OSC', () => { test('\x1b]0;abc123€öäü\x07', [ ['osc', '0;abc123€öäü, success: true'] ], null); }); - it('single DCS', function (): void { + it('single DCS', () => { test('\x1bP1;2;3+$aäbc;däe\x9c', [ ['dcs hook', [1, 2, 3]], ['dcs put', 'äbc;däe'], ['dcs unhook', true] ], null); }); - it('multi DCS', function (): void { + it('multi DCS', () => { test('\x1bP1;2;3+$abc;de', [ ['dcs hook', [1, 2, 3]], ['dcs put', 'bc;de'] @@ -1048,7 +1063,7 @@ describe('EscapeSequenceParser', function (): void { ['dcs unhook', true] ], true); }); - it('print + DCS(C1)', function (): void { + it('print + DCS(C1)', () => { test('abc\x901;2;3+$abc;de\x9c', [ ['print', 'abc'], ['dcs hook', [1, 2, 3]], @@ -1056,26 +1071,26 @@ describe('EscapeSequenceParser', function (): void { ['dcs unhook', true] ], null); }); - it('print + PM(C1) + print', function (): void { + it('print + PM(C1) + print', () => { test('abc\x98123tzf\x9cdefg', [ ['print', 'abc'], ['print', 'defg'] ], null); }); - it('print + OSC(C1) + print', function (): void { + it('print + OSC(C1) + print', () => { test('abc\x9d123;tzf\x9cdefg', [ ['print', 'abc'], ['osc', '123;tzf, success: true'], ['print', 'defg'] ], null); }); - it('error recovery', function (): void { + it('error recovery', () => { test('\x1b[1€abcdefg\x9b<;c', [ ['print', 'abcdefg'], ['csi', '<', [0, 0], 'c'] ], null); }); - it('7bit ST should be swallowed', function (): void { + it('7bit ST should be swallowed', () => { test('abc\x9d123;tzf\x1b\\defg', [ ['print', 'abc'], ['osc', '123;tzf, success: true'], @@ -1091,7 +1106,7 @@ describe('EscapeSequenceParser', function (): void { ['print', 'abc'] ], null); }); - it('colon notation in DCS params', function (): void { + it('colon notation in DCS params', () => { test('abc\x901;2::55;3+$abc;de\x9c', [ ['print', 'abc'], ['dcs hook', [1, 2, [-1, 55], 3]], @@ -1127,50 +1142,50 @@ describe('EscapeSequenceParser', function (): void { }); }); - describe('coverage tests', function (): void { - it('CSI_IGNORE error', function (): void { + describe('coverage tests', () => { + it('CSI_IGNORE error', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.CSI_IGNORE; parse(parser, '€öäü'); - chai.expect(parser.currentState).equal(ParserState.CSI_IGNORE); + assert.equal(parser.currentState, ParserState.CSI_IGNORE); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); - it('DCS_IGNORE error', function (): void { + it('DCS_IGNORE error', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.DCS_IGNORE; parse(parser, '€öäü'); - chai.expect(parser.currentState).equal(ParserState.DCS_IGNORE); + assert.equal(parser.currentState, ParserState.DCS_IGNORE); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); - it('DCS_PASSTHROUGH error', function (): void { + it('DCS_PASSTHROUGH error', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.DCS_PASSTHROUGH; parse(parser, '\x901;2;3+$a€öäü'); - chai.expect(parser.currentState).equal(ParserState.DCS_PASSTHROUGH); + assert.equal(parser.currentState, ParserState.DCS_PASSTHROUGH); testTerminal.compare([['dcs hook', [1, 2, 3]], ['dcs put', '€öäü']]); parser.reset(); testTerminal.clear(); }); - it('error else of if (code > 159)', function (): void { + it('error else of if (code > 159)', () => { parser.reset(); testTerminal.clear(); parser.currentState = ParserState.GROUND; parse(parser, '\x9c'); - chai.expect(parser.currentState).equal(ParserState.GROUND); + assert.equal(parser.currentState, ParserState.GROUND); testTerminal.compare([]); parser.reset(); testTerminal.clear(); }); }); - describe('set/clear handler', function (): void { + describe('set/clear handler', () => { const INPUT = '\x1b[1;31mhello \x1b%Gwor\x1bEld!\x1b[0m\r\n$>\x1b]1;foo=bar\x1b\\'; let parser2: TestEscapeSequenceParser; let print = ''; @@ -1187,269 +1202,275 @@ describe('EscapeSequenceParser', function (): void { osc.length = 0; dcs.length = 0; } - beforeEach(function (): void { + beforeEach(() => { parser2 = new TestEscapeSequenceParser(); clearAccu(); }); - it('print handler', function (): void { + it('print handler', () => { parser2.setPrintHandler(function (data: Uint32Array, start: number, end: number): void { for (let i = start; i < end; ++i) { print += stringFromCodePoint(data[i]); } }); parse(parser2, INPUT); - chai.expect(print).equal('hello world!$>'); + assert.equal(print, 'hello world!$>'); parser2.clearPrintHandler(); parser2.clearPrintHandler(); // should not throw clearAccu(); parse(parser2, INPUT); - chai.expect(print).equal(''); + assert.equal(print, ''); }); - it('ESC handler', function (): void { - parser2.setEscHandler({intermediates: '%', final: 'G'}, function (): void { + it('ESC handler', () => { + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, function (): boolean { esc.push('%G'); + return true; }); - parser2.setEscHandler({final: 'E'}, function (): void { + parser2.registerEscHandler({ final: 'E' }, function (): boolean { esc.push('E'); + return true; }); parse(parser2, INPUT); - chai.expect(esc).eql(['%G', 'E']); - parser2.clearEscHandler({intermediates: '%', final: 'G'}); - parser2.clearEscHandler({intermediates: '%', final: 'G'}); // should not throw + assert.deepEqual(esc, ['%G', 'E']); + parser2.clearEscHandler({ intermediates: '%', final: 'G' }); + parser2.clearEscHandler({ intermediates: '%', final: 'G' }); // should not throw clearAccu(); parse(parser2, INPUT); - chai.expect(esc).eql(['E']); - parser2.clearEscHandler({final: 'E'}); + assert.deepEqual(esc, ['E']); + parser2.clearEscHandler({ final: 'E' }); clearAccu(); parse(parser2, INPUT); - chai.expect(esc).eql([]); + assert.deepEqual(esc, []); }); describe('ESC custom handlers', () => { it('prevent fallback', () => { - parser2.setEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('default - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom - %G'); return true; }); parse(parser2, INPUT); - chai.expect(esc).eql(['custom - %G']); + assert.deepEqual(esc, ['custom - %G']); }); it('allow fallback', () => { - parser2.setEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom - %G'); return false; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('default - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom - %G'); return false; }); parse(parser2, INPUT); - chai.expect(esc).eql(['custom - %G', 'default - %G']); + assert.deepEqual(esc, ['custom - %G', 'default - %G']); }); it('Multiple custom handlers fallback once', () => { - parser2.setEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom - %G'); return true; }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom2 - %G'); return false; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('default - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom2 - %G'); return false; }); parse(parser2, INPUT); - chai.expect(esc).eql(['custom2 - %G', 'custom - %G']); + assert.deepEqual(esc, ['custom2 - %G', 'custom - %G']); }); it('Multiple custom handlers no fallback', () => { - parser2.setEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom - %G'); return true; }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom2 - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('default - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom2 - %G'); return true; }); parse(parser2, INPUT); - chai.expect(esc).eql(['custom2 - %G']); + assert.deepEqual(esc, ['custom2 - %G']); }); it('Execution order should go from latest handler down to the original', () => { const order: number[] = []; - parser2.setEscHandler({intermediates: '%', final: 'G'}, () => { order.push(1); }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { order.push(2); return false; }); - parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { order.push(3); return false; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { order.push(1); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { order.push(2); return false; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { order.push(3); return false; }); parse(parser2, '\x1b%G'); - chai.expect(order).eql([3, 2, 1]); + assert.deepEqual(order, [3, 2, 1]); }); it('Dispose should work', () => { - parser2.setEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); }); - const dispo = parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('default - %G'); return true; }); + const dispo = parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom - %G'); return true; }); dispo.dispose(); parse(parser2, INPUT); - chai.expect(esc).eql(['default - %G']); + assert.deepEqual(esc, ['default - %G']); }); it('Should not corrupt the parser when dispose is called twice', () => { - parser2.setEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); }); - const dispo = parser2.addEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('custom - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('default - %G'); return true; }); + const dispo = parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom - %G'); return true; }); dispo.dispose(); dispo.dispose(); parse(parser2, INPUT); - chai.expect(esc).eql(['default - %G']); + assert.deepEqual(esc, ['default - %G']); }); }); - it('CSI handler', function (): void { - parser2.setCsiHandler({final: 'm'}, function (params: IParams): void { + it('CSI handler', () => { + parser2.registerCsiHandler({ final: 'm' }, function (params: IParams): boolean { csi.push(['m', params.toArray(), '']); + return true; }); parse(parser2, INPUT); - chai.expect(csi).eql([['m', [1, 31], ''], ['m', [0], '']]); - parser2.clearCsiHandler({final: 'm'}); - parser2.clearCsiHandler({final: 'm'}); // should not throw + assert.deepEqual(csi, [['m', [1, 31], ''], ['m', [0], '']]); + parser2.clearCsiHandler({ final: 'm' }); + parser2.clearCsiHandler({ final: 'm' }); // should not throw clearAccu(); parse(parser2, INPUT); - chai.expect(csi).eql([]); + assert.deepEqual(csi, []); }); describe('CSI custom handlers', () => { it('Prevent fallback', () => { const csiCustom: [string, ParamsArray, string][] = []; - parser2.setCsiHandler({final: 'm'}, params => { csi.push(['m', params.toArray(), '']); }); - parser2.addCsiHandler({final: 'm'}, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csi.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); parse(parser2, INPUT); - chai.expect(csi).eql([], 'Should not fallback to original handler'); - chai.expect(csiCustom).eql([['m', [1, 31], ''], ['m', [0], '']]); + assert.deepEqual(csi, [], 'Should not fallback to original handler'); + assert.deepEqual(csiCustom, [['m', [1, 31], ''], ['m', [0], '']]); }); it('Allow fallback', () => { const csiCustom: [string, ParamsArray, string][] = []; - parser2.setCsiHandler({final: 'm'}, params => { csi.push(['m', params.toArray(), '']); }); - parser2.addCsiHandler({final: 'm'}, params => { csiCustom.push(['m', params.toArray(), '']); return false; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csi.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom.push(['m', params.toArray(), '']); return false; }); parse(parser2, INPUT); - chai.expect(csi).eql([['m', [1, 31], ''], ['m', [0], '']], 'Should fallback to original handler'); - chai.expect(csiCustom).eql([['m', [1, 31], ''], ['m', [0], '']]); + assert.deepEqual(csi, [['m', [1, 31], ''], ['m', [0], '']], 'Should fallback to original handler'); + assert.deepEqual(csiCustom, [['m', [1, 31], ''], ['m', [0], '']]); }); it('Multiple custom handlers fallback once', () => { const csiCustom: [string, ParamsArray, string][] = []; const csiCustom2: [string, ParamsArray, string][] = []; - parser2.setCsiHandler({final: 'm'}, params => { csi.push(['m', params.toArray(), '']); }); - parser2.addCsiHandler({final: 'm'}, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); - parser2.addCsiHandler({final: 'm'}, params => { csiCustom2.push(['m', params.toArray(), '']); return false; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csi.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom2.push(['m', params.toArray(), '']); return false; }); parse(parser2, INPUT); - chai.expect(csi).eql([], 'Should not fallback to original handler'); - chai.expect(csiCustom).eql([['m', [1, 31], ''], ['m', [0], '']]); - chai.expect(csiCustom2).eql([['m', [1, 31], ''], ['m', [0], '']]); + assert.deepEqual(csi, [], 'Should not fallback to original handler'); + assert.deepEqual(csiCustom, [['m', [1, 31], ''], ['m', [0], '']]); + assert.deepEqual(csiCustom2, [['m', [1, 31], ''], ['m', [0], '']]); }); it('Multiple custom handlers no fallback', () => { const csiCustom: [string, ParamsArray, string][] = []; const csiCustom2: [string, ParamsArray, string][] = []; - parser2.setCsiHandler({final: 'm'}, params => { csi.push(['m', params.toArray(), '']); }); - parser2.addCsiHandler({final: 'm'}, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); - parser2.addCsiHandler({final: 'm'}, params => { csiCustom2.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csi.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom2.push(['m', params.toArray(), '']); return true; }); parse(parser2, INPUT); - chai.expect(csi).eql([], 'Should not fallback to original handler'); - chai.expect(csiCustom).eql([], 'Should not fallback once'); - chai.expect(csiCustom2).eql([['m', [1, 31], ''], ['m', [0], '']]); + assert.deepEqual(csi, [], 'Should not fallback to original handler'); + assert.deepEqual(csiCustom, [], 'Should not fallback once'); + assert.deepEqual(csiCustom2, [['m', [1, 31], ''], ['m', [0], '']]); }); it('Execution order should go from latest handler down to the original', () => { const order: number[] = []; - parser2.setCsiHandler({final: 'm'}, () => { order.push(1); }); - parser2.addCsiHandler({final: 'm'}, () => { order.push(2); return false; }); - parser2.addCsiHandler({final: 'm'}, () => { order.push(3); return false; }); + parser2.registerCsiHandler({ final: 'm' }, () => { order.push(1); return true; }); + parser2.registerCsiHandler({ final: 'm' }, () => { order.push(2); return false; }); + parser2.registerCsiHandler({ final: 'm' }, () => { order.push(3); return false; }); parse(parser2, '\x1b[0m'); - chai.expect(order).eql([3, 2, 1]); + assert.deepEqual(order, [3, 2, 1]); }); it('Dispose should work', () => { const csiCustom: [string, ParamsArray, string][] = []; - parser2.setCsiHandler({final: 'm'}, params => { csi.push(['m', params.toArray(), '']); }); - const customHandler = parser2.addCsiHandler({final: 'm'}, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csi.push(['m', params.toArray(), '']); return true; }); + const customHandler = parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); customHandler.dispose(); parse(parser2, INPUT); - chai.expect(csi).eql([['m', [1, 31], ''], ['m', [0], '']]); - chai.expect(csiCustom).eql([], 'Should not use custom handler as it was disposed'); + assert.deepEqual(csi, [['m', [1, 31], ''], ['m', [0], '']]); + assert.deepEqual(csiCustom, [], 'Should not use custom handler as it was disposed'); }); it('Should not corrupt the parser when dispose is called twice', () => { const csiCustom: [string, ParamsArray, string][] = []; - parser2.setCsiHandler({final: 'm'}, params => { csi.push(['m', params.toArray(), '']); }); - const customHandler = parser2.addCsiHandler({final: 'm'}, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csi.push(['m', params.toArray(), '']); return true; }); + const customHandler = parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); customHandler.dispose(); customHandler.dispose(); parse(parser2, INPUT); - chai.expect(csi).eql([['m', [1, 31], ''], ['m', [0], '']]); - chai.expect(csiCustom).eql([], 'Should not use custom handler as it was disposed'); + assert.deepEqual(csi, [['m', [1, 31], ''], ['m', [0], '']]); + assert.deepEqual(csiCustom, [], 'Should not use custom handler as it was disposed'); }); }); - it('EXECUTE handler', function (): void { - parser2.setExecuteHandler('\n', function (): void { + it('EXECUTE handler', () => { + parser2.setExecuteHandler('\n', function (): boolean { exe.push('\n'); + return true; }); - parser2.setExecuteHandler('\r', function (): void { + parser2.setExecuteHandler('\r', function (): boolean { exe.push('\r'); + return true; }); parse(parser2, INPUT); - chai.expect(exe).eql(['\r', '\n']); + assert.deepEqual(exe, ['\r', '\n']); parser2.clearExecuteHandler('\r'); parser2.clearExecuteHandler('\r'); // should not throw clearAccu(); parse(parser2, INPUT); - chai.expect(exe).eql(['\n']); + assert.deepEqual(exe, ['\n']); }); - it('OSC handler', function (): void { - parser2.setOscHandler(1, new OscHandler(function (data: string): void { + it('OSC handler', () => { + parser2.registerOscHandler(1, new OscHandler(function (data: string): boolean { osc.push([1, data]); + return true; })); parse(parser2, INPUT); - chai.expect(osc).eql([[1, 'foo=bar']]); + assert.deepEqual(osc, [[1, 'foo=bar']]); parser2.clearOscHandler(1); parser2.clearOscHandler(1); // should not throw clearAccu(); parse(parser2, INPUT); - chai.expect(osc).eql([]); + assert.deepEqual(osc, []); }); describe('OSC custom handlers', () => { it('Prevent fallback', () => { const oscCustom: [number, string][] = []; - parser2.setOscHandler(1, new OscHandler(data => osc.push([1, data]))); - parser2.addOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { osc.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); parse(parser2, INPUT); - chai.expect(osc).eql([], 'Should not fallback to original handler'); - chai.expect(oscCustom).eql([[1, 'foo=bar']]); + assert.deepEqual(osc, [], 'Should not fallback to original handler'); + assert.deepEqual(oscCustom, [[1, 'foo=bar']]); }); it('Allow fallback', () => { const oscCustom: [number, string][] = []; - parser2.setOscHandler(1, new OscHandler(data => osc.push([1, data]))); - parser2.addOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return false; })); + parser2.registerOscHandler(1, new OscHandler(data => { osc.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return false; })); parse(parser2, INPUT); - chai.expect(osc).eql([[1, 'foo=bar']], 'Should fallback to original handler'); - chai.expect(oscCustom).eql([[1, 'foo=bar']]); + assert.deepEqual(osc, [[1, 'foo=bar']], 'Should fallback to original handler'); + assert.deepEqual(oscCustom, [[1, 'foo=bar']]); }); it('Multiple custom handlers fallback once', () => { const oscCustom: [number, string][] = []; const oscCustom2: [number, string][] = []; - parser2.setOscHandler(1, new OscHandler(data => osc.push([1, data]))); - parser2.addOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); - parser2.addOscHandler(1, new OscHandler(data => { oscCustom2.push([1, data]); return false; })); + parser2.registerOscHandler(1, new OscHandler(data => { osc.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { oscCustom2.push([1, data]); return false; })); parse(parser2, INPUT); - chai.expect(osc).eql([], 'Should not fallback to original handler'); - chai.expect(oscCustom).eql([[1, 'foo=bar']]); - chai.expect(oscCustom2).eql([[1, 'foo=bar']]); + assert.deepEqual(osc, [], 'Should not fallback to original handler'); + assert.deepEqual(oscCustom, [[1, 'foo=bar']]); + assert.deepEqual(oscCustom2, [[1, 'foo=bar']]); }); it('Multiple custom handlers no fallback', () => { const oscCustom: [number, string][] = []; const oscCustom2: [number, string][] = []; - parser2.setOscHandler(1, new OscHandler(data => osc.push([1, data]))); - parser2.addOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); - parser2.addOscHandler(1, new OscHandler(data => { oscCustom2.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { osc.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { oscCustom2.push([1, data]); return true; })); parse(parser2, INPUT); - chai.expect(osc).eql([], 'Should not fallback to original handler'); - chai.expect(oscCustom).eql([], 'Should not fallback once'); - chai.expect(oscCustom2).eql([[1, 'foo=bar']]); + assert.deepEqual(osc, [], 'Should not fallback to original handler'); + assert.deepEqual(oscCustom, [], 'Should not fallback once'); + assert.deepEqual(oscCustom2, [[1, 'foo=bar']]); }); it('Execution order should go from latest handler down to the original', () => { const order: number[] = []; - parser2.setOscHandler(1, new OscHandler(() => order.push(1))); - parser2.addOscHandler(1, new OscHandler(() => { order.push(2); return false; })); - parser2.addOscHandler(1, new OscHandler(() => { order.push(3); return false; })); + parser2.registerOscHandler(1, new OscHandler(() => { order.push(1); return true; })); + parser2.registerOscHandler(1, new OscHandler(() => { order.push(2); return false; })); + parser2.registerOscHandler(1, new OscHandler(() => { order.push(3); return false; })); parse(parser2, '\x1b]1;foo=bar\x1b\\'); - chai.expect(order).eql([3, 2, 1]); + assert.deepEqual(order, [3, 2, 1]); }); it('Dispose should work', () => { const oscCustom: [number, string][] = []; - parser2.setOscHandler(1, new OscHandler(data => osc.push([1, data]))); - const customHandler = parser2.addOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { osc.push([1, data]); return true; })); + const customHandler = parser2.registerOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); customHandler.dispose(); parse(parser2, INPUT); - chai.expect(osc).eql([[1, 'foo=bar']]); - chai.expect(oscCustom).eql([], 'Should not use custom handler as it was disposed'); + assert.deepEqual(osc, [[1, 'foo=bar']]); + assert.deepEqual(oscCustom, [], 'Should not use custom handler as it was disposed'); }); it('Should not corrupt the parser when dispose is called twice', () => { const oscCustom: [number, string][] = []; - parser2.setOscHandler(1, new OscHandler(data => osc.push([1, data]))); - const customHandler = parser2.addOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); + parser2.registerOscHandler(1, new OscHandler(data => { osc.push([1, data]); return true; })); + const customHandler = parser2.registerOscHandler(1, new OscHandler(data => { oscCustom.push([1, data]); return true; })); customHandler.dispose(); customHandler.dispose(); parse(parser2, INPUT); - chai.expect(osc).eql([[1, 'foo=bar']]); - chai.expect(oscCustom).eql([], 'Should not use custom handler as it was disposed'); + assert.deepEqual(osc, [[1, 'foo=bar']]); + assert.deepEqual(oscCustom, [], 'Should not use custom handler as it was disposed'); }); }); - it('DCS handler', function (): void { - parser2.setDcsHandler({intermediates: '+', final: 'p'}, { + it('DCS handler', () => { + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, { hook: function (params: IParams): void { dcs.push(['hook', '', params.toArray(), 0]); }, @@ -1460,90 +1481,91 @@ describe('EscapeSequenceParser', function (): void { } dcs.push(['put', s]); }, - unhook: function (): void { + unhook: function (): boolean { dcs.push(['unhook']); + return true; } }); parse(parser2, '\x1bP1;2;3+pabc'); parse(parser2, ';de\x9c'); - chai.expect(dcs).eql([ + assert.deepEqual(dcs, [ ['hook', '', [1, 2, 3], 0], ['put', 'abc'], ['put', ';de'], ['unhook'] ]); - parser2.clearDcsHandler({intermediates: '+', final: 'p'}); - parser2.clearDcsHandler({intermediates: '+', final: 'p'}); // should not throw + parser2.clearDcsHandler({ intermediates: '+', final: 'p' }); + parser2.clearDcsHandler({ intermediates: '+', final: 'p' }); // should not throw clearAccu(); parse(parser2, '\x1bP1;2;3+pabc'); parse(parser2, ';de\x9c'); - chai.expect(dcs).eql([]); + assert.deepEqual(dcs, []); }); describe('DCS custom handlers', () => { const DCS_INPUT = '\x1bP1;2;3+pabc\x1b\\'; it('Prevent fallback', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - parser2.setDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => dcsCustom.push(['A', params.toArray(), data]))); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['A', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); parse(parser2, DCS_INPUT); - chai.expect(dcsCustom).eql([['B', [1, 2, 3], 'abc']]); + assert.deepEqual(dcsCustom, [['B', [1, 2, 3], 'abc']]); }); it('Allow fallback', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - parser2.setDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => dcsCustom.push(['A', params.toArray(), data]))); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return false; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['A', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return false; })); parse(parser2, DCS_INPUT); - chai.expect(dcsCustom).eql([['B', [1, 2, 3], 'abc'], ['A', [1, 2, 3], 'abc']]); + assert.deepEqual(dcsCustom, [['B', [1, 2, 3], 'abc'], ['A', [1, 2, 3], 'abc']]); }); it('Multiple custom handlers fallback once', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - parser2.setDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => dcsCustom.push(['A', params.toArray(), data]))); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['C', params.toArray(), data]); return false; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['A', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['C', params.toArray(), data]); return false; })); parse(parser2, DCS_INPUT); - chai.expect(dcsCustom).eql([['C', [1, 2, 3], 'abc'], ['B', [1, 2, 3], 'abc']]); + assert.deepEqual(dcsCustom, [['C', [1, 2, 3], 'abc'], ['B', [1, 2, 3], 'abc']]); }); it('Multiple custom handlers no fallback', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - parser2.setDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => dcsCustom.push(['A', params.toArray(), data]))); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['C', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['A', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['C', params.toArray(), data]); return true; })); parse(parser2, DCS_INPUT); - chai.expect(dcsCustom).eql([['C', [1, 2, 3], 'abc']]); + assert.deepEqual(dcsCustom, [['C', [1, 2, 3], 'abc']]); }); it('Execution order should go from latest handler down to the original', () => { const order: number[] = []; - parser2.setDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler(() => order.push(1))); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler(() => { order.push(2); return false; })); - parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler(() => { order.push(3); return false; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler(() => { order.push(1); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler(() => { order.push(2); return false; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler(() => { order.push(3); return false; })); parse(parser2, DCS_INPUT); - chai.expect(order).eql([3, 2, 1]); + assert.deepEqual(order, [3, 2, 1]); }); it('Dispose should work', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - parser2.setDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => dcsCustom.push(['A', params.toArray(), data]))); - const dispo = parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['A', params.toArray(), data]); return true; })); + const dispo = parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); dispo.dispose(); parse(parser2, DCS_INPUT); - chai.expect(dcsCustom).eql([['A', [1, 2, 3], 'abc']]); + assert.deepEqual(dcsCustom, [['A', [1, 2, 3], 'abc']]); }); it('Should not corrupt the parser when dispose is called twice', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - parser2.setDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => dcsCustom.push(['A', params.toArray(), data]))); - const dispo = parser2.addDcsHandler({intermediates: '+', final: 'p'}, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['A', params.toArray(), data]); return true; })); + const dispo = parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, new DcsHandler((data, params) => { dcsCustom.push(['B', params.toArray(), data]); return true; })); dispo.dispose(); dispo.dispose(); parse(parser2, DCS_INPUT); - chai.expect(dcsCustom).eql([['A', [1, 2, 3], 'abc']]); + assert.deepEqual(dcsCustom, [['A', [1, 2, 3], 'abc']]); }); }); - it('ERROR handler', function (): void { + it('ERROR handler', () => { let errorState: IParsingState | null = null; parser2.setErrorHandler(function (state: IParsingState): IParsingState { errorState = state; return state; }); parse(parser2, '\x1b[1;2;€;3m'); // faulty escape sequence - chai.expect(errorState).eql({ + assert.deepEqual(errorState, { position: 6, code: '€'.charCodeAt(0), currentState: ParserState.CSI_PARAM, @@ -1555,7 +1577,7 @@ describe('EscapeSequenceParser', function (): void { parser2.clearErrorHandler(); // should not throw errorState = null; parse(parser2, '\x1b[1;2;a;3m'); - chai.expect(errorState).eql(null); + assert.equal(errorState, null); }); }); describe('function identifiers', () => { @@ -1563,69 +1585,69 @@ describe('EscapeSequenceParser', function (): void { it('prefix range 0x3c .. 0x3f, one byte', () => { for (let i = 0x3c; i <= 0x3f; ++i) { const c = String.fromCharCode(i); - chai.expect(parser.identToString(parser.identifier({prefix: c, final: 'z'}))).eql(c + 'z'); + assert.equal(parser.identToString(parser.identifier({ prefix: c, final: 'z' })), c + 'z'); } - chai.assert.throws(() => { parser.identifier({prefix: '\x3b', final: 'z'}); }, 'prefix must be in range 0x3c .. 0x3f'); - chai.assert.throws(() => { parser.identifier({prefix: '\x40', final: 'z'}); }, 'prefix must be in range 0x3c .. 0x3f'); - chai.assert.throws(() => { parser.identifier({prefix: '??', final: 'z'}); }, 'only one byte as prefix supported'); + assert.throws(() => { parser.identifier({ prefix: '\x3b', final: 'z' }); }, 'prefix must be in range 0x3c .. 0x3f'); + assert.throws(() => { parser.identifier({ prefix: '\x40', final: 'z' }); }, 'prefix must be in range 0x3c .. 0x3f'); + assert.throws(() => { parser.identifier({ prefix: '??', final: 'z' }); }, 'only one byte as prefix supported'); }); it('intermediates range 0x20 .. 0x2f, up to two bytes', () => { for (let i = 0x20; i <= 0x2f; ++i) { const c = String.fromCharCode(i); - chai.expect(parser.identToString(parser.identifier({intermediates: c + c, final: 'z'}))).eql(c + c + 'z'); + assert.equal(parser.identToString(parser.identifier({ intermediates: c + c, final: 'z' })), c + c + 'z'); } - chai.assert.throws(() => { parser.identifier({intermediates: '\x1f', final: 'z'}); }, 'intermediate must be in range 0x20 .. 0x2f'); - chai.assert.throws(() => { parser.identifier({intermediates: '\x30', final: 'z'}); }, 'intermediate must be in range 0x20 .. 0x2f'); - chai.assert.throws(() => { parser.identifier({intermediates: '!!!', final: 'z'}); }, 'only two bytes as intermediates are supported'); + assert.throws(() => { parser.identifier({ intermediates: '\x1f', final: 'z' }); }, 'intermediate must be in range 0x20 .. 0x2f'); + assert.throws(() => { parser.identifier({ intermediates: '\x30', final: 'z' }); }, 'intermediate must be in range 0x20 .. 0x2f'); + assert.throws(() => { parser.identifier({ intermediates: '!!!', final: 'z' }); }, 'only two bytes as intermediates are supported'); }); it('final CSI/DCS range 0x40 .. 0x7e (default), one byte', () => { for (let i = 0x40; i <= 0x7e; ++i) { const c = String.fromCharCode(i); - chai.expect(parser.identToString(parser.identifier({final: c}))).eql(c); + assert.equal(parser.identToString(parser.identifier({ final: c })), c); } - chai.assert.throws(() => { parser.identifier({final: '\x3f'}); }, 'final must be in range 64 .. 126'); - chai.assert.throws(() => { parser.identifier({final: '\x7f'}); }, 'final must be in range 64 .. 126'); - chai.assert.throws(() => { parser.identifier({final: 'zz'}); }, 'final must be a single byte'); + assert.throws(() => { parser.identifier({ final: '\x3f' }); }, 'final must be in range 64 .. 126'); + assert.throws(() => { parser.identifier({ final: '\x7f' }); }, 'final must be in range 64 .. 126'); + assert.throws(() => { parser.identifier({ final: 'zz' }); }, 'final must be a single byte'); }); it('final ESC range 0x30 .. 0x7e, one byte', () => { for (let i = 0x30; i <= 0x7e; ++i) { const final = String.fromCharCode(i); let handler: IDisposable | undefined; - chai.assert.doesNotThrow(() => { handler = parser.addEscHandler({final}, () => {}); }, 'final must be in range 48 .. 126'); + assert.doesNotThrow(() => { handler = parser.registerEscHandler({ final }, () => true); }, 'final must be in range 48 .. 126'); if (handler) handler.dispose(); } - chai.assert.throws(() => { parser.addEscHandler({final: '\x2f'}, () => {}); }, 'final must be in range 48 .. 126'); - chai.assert.throws(() => { parser.addEscHandler({final: '\x7f'}, () => {}); }, 'final must be in range 48 .. 126'); + assert.throws(() => { parser.registerEscHandler({ final: '\x2f' }, () => true); }, 'final must be in range 48 .. 126'); + assert.throws(() => { parser.registerEscHandler({ final: '\x7f' }, () => true); }, 'final must be in range 48 .. 126'); }); it('id calculation - should stacking prefix -> intermediate -> final', () => { - chai.expect(parser.identToString(parser.identifier({final: 'z'}))).eql('z'); - chai.expect(parser.identToString(parser.identifier({prefix: '?', final: 'z'}))).eql('?z'); - chai.expect(parser.identToString(parser.identifier({intermediates: '!', final: 'z'}))).eql('!z'); - chai.expect(parser.identToString(parser.identifier({prefix: '?', intermediates: '!', final: 'z'}))).eql('?!z'); - chai.expect(parser.identToString(parser.identifier({prefix: '?', intermediates: '!!', final: 'z'}))).eql('?!!z'); + assert.equal(parser.identToString(parser.identifier({ final: 'z' })), 'z'); + assert.equal(parser.identToString(parser.identifier({ prefix: '?', final: 'z' })), '?z'); + assert.equal(parser.identToString(parser.identifier({ intermediates: '!', final: 'z' })), '!z'); + assert.equal(parser.identToString(parser.identifier({ prefix: '?', intermediates: '!', final: 'z' })), '?!z'); + assert.equal(parser.identToString(parser.identifier({ prefix: '?', intermediates: '!!', final: 'z' })), '?!!z'); }); }); describe('identifier invocation', () => { it('ESC', () => { const callstack: string[] = []; - const h1 = parser.addEscHandler({final: 'z'}, () => { callstack.push('z'); }); - const h2 = parser.addEscHandler({intermediates: '!', final: 'z'}, () => { callstack.push('!z'); }); - const h3 = parser.addEscHandler({intermediates: '!!', final: 'z'}, () => { callstack.push('!!z'); }); + const h1 = parser.registerEscHandler({ final: 'z' }, () => { callstack.push('z'); return true; }); + const h2 = parser.registerEscHandler({ intermediates: '!', final: 'z' }, () => { callstack.push('!z'); return true; }); + const h3 = parser.registerEscHandler({ intermediates: '!!', final: 'z' }, () => { callstack.push('!!z'); return true; }); parse(parser, '\x1bz\x1b!z\x1b!!z'); h1.dispose(); h2.dispose(); h3.dispose(); parse(parser, '\x1bz\x1b!z\x1b!!z'); - chai.expect(callstack).eql(['z', '!z', '!!z']); + assert.deepEqual(callstack, ['z', '!z', '!!z']); }); it('CSI', () => { const callstack: any[] = []; - const h1 = parser.addCsiHandler({final: 'z'}, params => { callstack.push(['z', params.toArray()]); }); - const h2 = parser.addCsiHandler({intermediates: '!', final: 'z'}, params => { callstack.push(['!z', params.toArray()]); }); - const h3 = parser.addCsiHandler({intermediates: '!!', final: 'z'}, params => { callstack.push(['!!z', params.toArray()]); }); - const h4 = parser.addCsiHandler({prefix: '?', final: 'z'}, params => { callstack.push(['?z', params.toArray()]); }); - const h5 = parser.addCsiHandler({prefix: '?', intermediates: '!', final: 'z'}, params => { callstack.push(['?!z', params.toArray()]); }); - const h6 = parser.addCsiHandler({prefix: '?', intermediates: '!!', final: 'z'}, params => { callstack.push(['?!!z', params.toArray()]); }); + const h1 = parser.registerCsiHandler({ final: 'z' }, params => { callstack.push(['z', params.toArray()]); return true; }); + const h2 = parser.registerCsiHandler({ intermediates: '!', final: 'z' }, params => { callstack.push(['!z', params.toArray()]); return true; }); + const h3 = parser.registerCsiHandler({ intermediates: '!!', final: 'z' }, params => { callstack.push(['!!z', params.toArray()]); return true; }); + const h4 = parser.registerCsiHandler({ prefix: '?', final: 'z' }, params => { callstack.push(['?z', params.toArray()]); return true; }); + const h5 = parser.registerCsiHandler({ prefix: '?', intermediates: '!', final: 'z' }, params => { callstack.push(['?!z', params.toArray()]); return true; }); + const h6 = parser.registerCsiHandler({ prefix: '?', intermediates: '!!', final: 'z' }, params => { callstack.push(['?!!z', params.toArray()]); return true; }); parse(parser, '\x1b[1;z\x1b[1;!z\x1b[1;!!z\x1b[?1;z\x1b[?1;!z\x1b[?1;!!z'); h1.dispose(); h2.dispose(); @@ -1634,16 +1656,19 @@ describe('EscapeSequenceParser', function (): void { h5.dispose(); h6.dispose(); parse(parser, '\x1b[1;z\x1b[1;!z\x1b[1;!!z\x1b[?1;z\x1b[?1;!z\x1b[?1;!!z'); - chai.expect(callstack).eql([['z', [1, 0]], ['!z', [1, 0]], ['!!z', [1, 0]], ['?z', [1, 0]], ['?!z', [1, 0]], ['?!!z', [1, 0]]]); + assert.deepEqual( + callstack, + [['z', [1, 0]], ['!z', [1, 0]], ['!!z', [1, 0]], ['?z', [1, 0]], ['?!z', [1, 0]], ['?!!z', [1, 0]]] + ); }); it('DCS', () => { const callstack: any[] = []; - const h1 = parser.addDcsHandler({final: 'z'}, new DcsHandler((data, params) => { callstack.push(['z', params.toArray(), data]); })); - const h2 = parser.addDcsHandler({intermediates: '!', final: 'z'}, new DcsHandler((data, params) => { callstack.push(['!z', params.toArray(), data]); })); - const h3 = parser.addDcsHandler({intermediates: '!!', final: 'z'}, new DcsHandler((data, params) => { callstack.push(['!!z', params.toArray(), data]); })); - const h4 = parser.addDcsHandler({prefix: '?', final: 'z'}, new DcsHandler((data, params) => { callstack.push(['?z', params.toArray(), data]); })); - const h5 = parser.addDcsHandler({prefix: '?', intermediates: '!', final: 'z'}, new DcsHandler((data, params) => { callstack.push(['?!z', params.toArray(), data]); })); - const h6 = parser.addDcsHandler({prefix: '?', intermediates: '!!', final: 'z'}, new DcsHandler((data, params) => { callstack.push(['?!!z', params.toArray(), data]); })); + const h1 = parser.registerDcsHandler({ final: 'z' }, new DcsHandler((data, params) => { callstack.push(['z', params.toArray(), data]); return true; })); + const h2 = parser.registerDcsHandler({ intermediates: '!', final: 'z' }, new DcsHandler((data, params) => { callstack.push(['!z', params.toArray(), data]); return true; })); + const h3 = parser.registerDcsHandler({ intermediates: '!!', final: 'z' }, new DcsHandler((data, params) => { callstack.push(['!!z', params.toArray(), data]); return true; })); + const h4 = parser.registerDcsHandler({ prefix: '?', final: 'z' }, new DcsHandler((data, params) => { callstack.push(['?z', params.toArray(), data]); return true; })); + const h5 = parser.registerDcsHandler({ prefix: '?', intermediates: '!', final: 'z' }, new DcsHandler((data, params) => { callstack.push(['?!z', params.toArray(), data]); return true; })); + const h6 = parser.registerDcsHandler({ prefix: '?', intermediates: '!!', final: 'z' }, new DcsHandler((data, params) => { callstack.push(['?!!z', params.toArray(), data]); return true; })); parse(parser, '\x1bP1;zAB\x1b\\\x1bP1;!zAB\x1b\\\x1bP1;!!zAB\x1b\\\x1bP?1;zAB\x1b\\\x1bP?1;!zAB\x1b\\\x1bP?1;!!zAB\x1b\\'); h1.dispose(); h2.dispose(); @@ -1652,16 +1677,544 @@ describe('EscapeSequenceParser', function (): void { h5.dispose(); h6.dispose(); parse(parser, '\x1bP1;zAB\x1b\\\x1bP1;!zAB\x1b\\\x1bP1;!!zAB\x1b\\\x1bP?1;zAB\x1b\\\x1bP?1;!zAB\x1b\\\x1bP?1;!!zAB\x1b\\'); - chai.expect(callstack).eql([ - ['z', [1, 0], 'AB'], - ['!z', [1, 0], 'AB'], - ['!!z', [1, 0], 'AB'], - ['?z', [1, 0], 'AB'], - ['?!z', [1, 0], 'AB'], - ['?!!z', [1, 0], 'AB'] - ]); + assert.deepEqual( + callstack, + [ + ['z', [1, 0], 'AB'], + ['!z', [1, 0], 'AB'], + ['!!z', [1, 0], 'AB'], + ['?z', [1, 0], 'AB'], + ['?!z', [1, 0], 'AB'], + ['?!!z', [1, 0], 'AB'] + ] + ); }); }); }); // TODO: error conditions and error recovery (not implemented yet in parser) }); + + +/** + * async handler tests. + */ + +function parseSync(parser: TestEscapeSequenceParser, data: string): void | Promise { + const container = new Uint32Array(data.length); + const decoder = new StringToUtf32(); + return parser.parse(container, decoder.decode(data, container)); +} +async function parseP(parser: TestEscapeSequenceParser, data: string): Promise { + const container = new Uint32Array(data.length); + const decoder = new StringToUtf32(); + const len = decoder.decode(data, container); + let result: void | Promise; + let prev: boolean | undefined; + while (result = parser.parse(container, len, prev)) { + prev = await result; + } +} +function evalStackSaves(stackSaves: IParserStackState[], data: [number, ParserStackType, number][]): void { + assert.equal(stackSaves.length, data.length); + for (let i = 0; i < data.length; ++i) { + assert.equal(stackSaves[i].chunkPos, data[i][0]); + assert.equal(stackSaves[i].state, data[i][1]); + assert.equal(stackSaves[i].handlerPos, data[i][2]); + } +} +// helper similiar to assert.throws for async functions +async function throwsAsync(fn: () => Promise, message?: string | undefined): Promise { + let msg: string | undefined; + try { + await fn(); + } catch (e) { + if (e instanceof Error) { + msg = e.message; + } else if (typeof e === 'string') { + msg = e; + } + if (typeof message === 'string') { + assert.equal(msg, message); + } + return; + } + assert.throws(fn, message); +} + +describe('EscapeSequenceParser - async', () => { + // sequences: SGR 1;31 | hello SP | ESC %G | wor | ESC E | ld! | SGR 0 | EXE \r\n | $> | DCS 1;2 a [xyz] ST | OSC 1;foo=bar ST | FIN + // needed handlers: CSI m, PRINT, ESC %G, ESC E, EXE \r, EXE \n, OSC 1 + const INPUT = '\x1b[1;31mhello \x1b%Gwor\x1bEld!\x1b[0m\r\n$>\x1bP1;2axyz\x1b\\\x1b]1;foo=bar\x1b\\FIN'; + let RESULT: any[]; + let parser: TestEscapeSequenceParser; + const callstack: any[] = []; + function clearAccu(): void { + callstack.length = 0; + parser.trackedStack.length = 0; + } + beforeEach(() => { + RESULT = [ + ['SGR', [1, 31]], + ['PRINT', 'hello '], + ['ESC %G'], + ['PRINT', 'wor'], + ['ESC E'], + ['PRINT', 'ld!'], + ['SGR', [0]], + ['EXE \r'], + ['EXE \n'], + ['PRINT', '$>'], + ['DCS a', ['xyz', [1, 2]]], + ['OSC 1', 'foo=bar'], + ['PRINT', 'FIN'] + ]; + parser = new TestEscapeSequenceParser(); + parser.reset(); + parser.trackStackSavesOnPause(); + clearAccu(); + }); + describe('sync handlers should behave as before', () => { + beforeEach(() => { + parser.setPrintHandler((data, start, end) => { + let result = ''; + for (let i = start; i < end; ++i) { + result += stringFromCodePoint(data[i]); + } + callstack.push(['PRINT', result]); + }); + parser.registerCsiHandler({ final: 'm' }, params => { callstack.push(['SGR', params.toArray()]); return true; }); + parser.registerEscHandler({ intermediates: '%', final: 'G' }, () => { callstack.push(['ESC %G']); return true; }); + parser.registerEscHandler({ final: 'E' }, () => { callstack.push(['ESC E']); return true; }); + parser.setExecuteHandler('\r', () => { callstack.push(['EXE \r']); return true; }); + parser.setExecuteHandler('\n', () => { callstack.push(['EXE \n']); return true; }); + parser.registerOscHandler(1, new OscHandler(data => { callstack.push(['OSC 1', data]); return true; })); + parser.registerDcsHandler({final: 'a'}, new DcsHandler((data, params) => { callstack.push(['DCS a', [data, params.toArray()]]); return true;})); + }); + + it('sync handlers keep being parsed in sync mode', () => { + // note: if we have only sync handlers, a parse call should never return anything + assert.equal(!parseSync(parser, INPUT), true); + assert.equal(parser.parseStack.state, ParserStackType.NONE); // not paused + assert.equal(parser.trackedStack.length, 0); // never got paused + }); + it('correct result on sync parse call', () => { + parseSync(parser, INPUT); + assert.deepEqual(callstack, RESULT); + assert.equal(parser.trackedStack.length, 0); + }); + it('correct result on async parse call', async () => { + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT); + assert.equal(parser.trackedStack.length, 0); + }); + }); + describe('async handlers', () => { + beforeEach(() => { + parser.setPrintHandler((data, start, end) => { + let result = ''; + for (let i = start; i < end; ++i) { + result += stringFromCodePoint(data[i]); + } + callstack.push(['PRINT', result]); + }); + parser.registerCsiHandler({ final: 'm' }, async params => { callstack.push(['SGR', params.toArray()]); return true; }); + parser.registerEscHandler({ intermediates: '%', final: 'G' }, async () => { callstack.push(['ESC %G']); return true; }); + parser.registerEscHandler({ final: 'E' }, async () => { callstack.push(['ESC E']); return true; }); + parser.setExecuteHandler('\r', () => { callstack.push(['EXE \r']); return true; }); + parser.setExecuteHandler('\n', () => { callstack.push(['EXE \n']); return true; }); + parser.registerOscHandler(1, new OscHandler(async data => { callstack.push(['OSC 1', data]); return true; })); + parser.registerDcsHandler({final: 'a'}, new DcsHandler(async (data, params) => { callstack.push(['DCS a', [data, params.toArray()]]); return true;})); + }); + + it('sync parse call does not work anymore', () => { + assert.notEqual(!parseSync(parser, INPUT), true); + assert.notDeepEqual(callstack, RESULT); + // due to sync calling we should save exactly one saved stack + // proper continuation is not possible anymore, as we lost the promise resolve value + assert.equal(parser.trackedStack.length, 1); + }); + it('improper continuation should throw', async () => { + /** + * Explanation: + * The first sync call will stop at the first promise returned, + * but does not await its resolve value. + * The second sync call to parse will fail due to missing `promiseResult`, + * which is needed for correct continuation. + */ + assert.notEqual(!parseSync(parser, INPUT), true); + assert.notDeepEqual(callstack, RESULT); + assert.throws(() => parseSync(parser, INPUT), 'improper continuation due to previous async handler, giving up parsing'); + // keeps being broken for further parse calls (sync and async) + assert.throws(() => parseSync(parser, 'random'), 'improper continuation due to previous async handler, giving up parsing'); + await throwsAsync(() => parseP(parser, 'foobar'), 'improper continuation due to previous async handler, giving up parsing'); + // reset should lift the error condition + parser.reset(); + await parseP(parser, INPUT); // does not throw anymore + }); + it('correct result on awaited parse call', async () => { + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + }); + it('correct result on chunked awaited parse calls', async () => { + RESULT = [ + ['SGR', [1, 31]], + ['PRINT', 'h'], // due to single char input PRINT is split + ['PRINT', 'e'], + ['PRINT', 'l'], + ['PRINT', 'l'], + ['PRINT', 'o'], + ['PRINT', ' '], + ['ESC %G'], + ['PRINT', 'w'], + ['PRINT', 'o'], + ['PRINT', 'r'], + ['ESC E'], + ['PRINT', 'l'], + ['PRINT', 'd'], + ['PRINT', '!'], + ['SGR', [0]], + ['EXE \r'], + ['EXE \n'], + ['PRINT', '$'], + ['PRINT', '>'], + ['DCS a', ['xyz', [1, 2]]], + ['OSC 1', 'foo=bar'], + ['PRINT', 'F'], + ['PRINT', 'I'], + ['PRINT', 'N'] + ]; + + // split to single char input + for (let i = 0; i < INPUT.length; ++i) { + // Note: a single fully awaited parse call always ends in sync mode, + // which re-enables faster sync processing in the higher up callstack + await parseP(parser, INPUT[i]); + } + assert.deepEqual(callstack, RESULT); + evalStackSaves(parser.trackedStack, [ + [0, ParserStackType.CSI, 0], + [0, ParserStackType.ESC, 0], + [0, ParserStackType.ESC, 0], + [0, ParserStackType.CSI, 0], + [0, ParserStackType.DCS, 0], + [0, ParserStackType.OSC, 0] + ]); + }); + it('multiple async SGR handlers', async () => { + // register with fallback + const SGR2 = parser.registerCsiHandler({ final: 'm' }, async params => { callstack.push(['2# SGR', params.toArray()]); return false; }); + await parseP(parser, INPUT); + // should contain [2# SGR, SGR] call pairs + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# SGR') assert.equal(callstack[i + 1][0], 'SGR', 'Should fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 1], + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 1], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + SGR2.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + + // register without fallback + const SGR22 = parser.registerCsiHandler({ final: 'm' }, async params => { callstack.push(['2# SGR', params.toArray()]); return true; }); + await parseP(parser, INPUT); + // should only contain 2# SGR + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# SGR') assert.notEqual(callstack[i + 1][0], 'SGR', 'Should not fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 1], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 1], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + SGR22.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + }); + it('multiple async ESC handlers', async () => { + // register with fallback + const ESC2 = parser.registerEscHandler({ final: 'E' }, async () => { callstack.push(['2# ESC E']); return false; }); + await parseP(parser, INPUT); + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# ESC E') assert.equal(callstack[i + 1][0], 'ESC E', 'Should fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 1], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + ESC2.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + + // register without fallback + const ESC22 = parser.registerEscHandler({ final: 'E' }, async () => { callstack.push(['2# ESC E']); return true; }); + await parseP(parser, INPUT); + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# ESC E') assert.notEqual(callstack[i + 1][0], 'ESC E', 'Should not fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 1], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + ESC22.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + }); + it('sync/async SGR mixed', async () => { + // sync with fallback + const SGR2 = parser.registerCsiHandler({ final: 'm' }, params => { callstack.push(['2# SGR', params.toArray()]); return false; }); + // async with fallback + const SGR3 = parser.registerCsiHandler({ final: 'm' }, async params => { callstack.push(['3# SGR', params.toArray()]); return false; }); + await parseP(parser, INPUT); + // should contain [3# SGR, 2# SGR, SGR] call triples + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '3# SGR') { + assert.equal(callstack[i + 1][0], '2# SGR', 'Should fallback to next handler'); + assert.equal(callstack[i + 2][0], 'SGR', 'Should fallback to original handler'); + } + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 2], + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 2], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // dispose SGR2 (sync one) + SGR2.dispose(); + await parseP(parser, INPUT); + // should contain [3# SGR, SGR] call pairs + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '3# SGR') { + assert.equal(callstack[i + 1][0], 'SGR', 'Should fallback to original handler'); + } + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 1], + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 1], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // dispose SGR3 (async one) + SGR3.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + }); + it('multiple async OSC handlers', async () => { + // register with fallback + const OSC2 = parser.registerOscHandler(1, new OscHandler(async data => { callstack.push(['2# OSC 1', data]); return false; })); + await parseP(parser, INPUT); + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# OSC 1') assert.equal(callstack[i + 1][0], 'OSC 1', 'Should fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + OSC2.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + + // register without fallback + const OSC22 = parser.registerOscHandler(1, new OscHandler(async data => { callstack.push(['2# OSC 1', data]); return true; })); + await parseP(parser, INPUT); + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# OSC 1') assert.notEqual(callstack[i + 1][0], 'OSC 1', 'Should fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + OSC22.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + }); + it('multiple async DCS handlers', async () => { + // register with fallback + const DCS2 = parser.registerDcsHandler({final: 'a'}, new DcsHandler(async (data, params) => { callstack.push(['#2 DCS a', [data, params.toArray()]]); return false;})); + await parseP(parser, INPUT); + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# DCS a') assert.equal(callstack[i + 1][0], 'DCS a', 'Should fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + DCS2.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + + // register without fallback + const DCS22 = parser.registerDcsHandler({final: 'a'}, new DcsHandler(async (data, params) => { callstack.push(['#2 DCS a', [data, params.toArray()]]); return true;})); + await parseP(parser, INPUT); + for (let i = 0; i < callstack.length; ++i) { + const entry = callstack[i]; + if (entry[0] === '2# DCS a') assert.notEqual(callstack[i + 1][0], 'DCS a', 'Should fallback to original handler'); + } + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + // after dispose we should be back to RESULT + DCS22.dispose(); + await parseP(parser, INPUT); + assert.deepEqual(callstack, RESULT, 'Should not call custom handler'); + evalStackSaves(parser.trackedStack, [ + [6, ParserStackType.CSI, 0], + [15, ParserStackType.ESC, 0], + [20, ParserStackType.ESC, 0], + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] + ]); + clearAccu(); + }); + }); +}); diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 96d206b9..f20a7e91 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -3,7 +3,7 @@ * @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 { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType, IParserStackState, ParserStackType, ResumableHandlersType } from 'common/parser/Types'; import { ParserState, ParserAction } from 'common/parser/Constants'; import { Disposable } from 'common/Lifecycle'; import { IDisposable } from 'common/Types'; @@ -239,7 +239,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP // handler lookup containers protected _printHandler: PrintHandlerType; - protected _executeHandlers: {[flag: number]: ExecuteHandlerType}; + protected _executeHandlers: { [flag: number]: ExecuteHandlerType }; protected _csiHandlers: IHandlerCollection; protected _escHandlers: IHandlerCollection; protected _oscParser: IOscParser; @@ -253,6 +253,15 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP protected _escHandlerFb: EscFallbackHandlerType; protected _errorHandlerFb: (state: IParsingState) => IParsingState; + // parser stack save for async handler support + protected _parseStack: IParserStackState = { + state: ParserStackType.NONE, + handlers: [], + handlerPos: 0, + transition: 0, + chunkPos: 0 + }; + constructor( protected readonly _transitions: TransitionTable = VT500_TRANSITION_TABLE ) { @@ -280,7 +289,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._errorHandler = this._errorHandlerFb; // swallow 7bit ST (ESC+\) - this.setEscHandler({final: '\\'}, () => {}); + this.registerEscHandler({ final: '\\' }, () => true); } protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number { @@ -344,7 +353,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._printHandler = this._printHandlerFb; } - public addEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable { + public registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable { const ident = this._identifier(id, [0x30, 0x7e]); if (this._escHandlers[ident] === undefined) { this._escHandlers[ident] = []; @@ -360,9 +369,6 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } }; } - 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])]; } @@ -380,7 +386,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._executeHandlerFb = handler; } - public addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable { + public registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable { const ident = this._identifier(id); if (this._csiHandlers[ident] === undefined) { this._csiHandlers[ident] = []; @@ -396,9 +402,6 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } }; } - 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)]; } @@ -406,11 +409,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP 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 registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable { + return this._dcsParser.registerHandler(this._identifier(id), handler); } public clearDcsHandler(id: IFunctionIdentifier): void { this._dcsParser.clearHandler(this._identifier(id)); @@ -419,11 +419,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP 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 registerOscHandler(ident: number, handler: IOscHandler): IDisposable { + return this._oscParser.registerHandler(ident, handler); } public clearOscHandler(ident: number): void { this._oscParser.clearHandler(ident); @@ -439,6 +436,15 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._errorHandler = this._errorHandlerFb; } + /** + * Reset parser to initial values. + * + * This can also be used to lift the improper continuation error condition + * when dealing with async handlers. Use this only as a last resort to silence + * that error when the terminal has no pending data to be processed. Note that + * the interrupted async handler might continue its work in the future messing + * up the terminal state even further. + */ public reset(): void { this.currentState = this.initialState; this._oscParser.reset(); @@ -447,9 +453,31 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._params.addParam(0); // ZDM this._collect = 0; this.precedingCodepoint = 0; + // abort pending continuation from async handler + // Here the RESET type indicates, that the next parse call will + // ignore any saved stack, instead continues sync with next codepoint from GROUND + if (this._parseStack.state !== ParserStackType.NONE) { + this._parseStack.state = ParserStackType.RESET; + this._parseStack.handlers = []; // also release handlers ref + } } - + /** + * Async parse support. + */ + protected _preserveStack( + state: ParserStackType, + handlers: ResumableHandlersType, + handlerPos: number, + transition: number, + chunkPos: number + ): void { + this._parseStack.state = state; + this._parseStack.handlers = handlers; + this._parseStack.handlerPos = handlerPos; + this._parseStack.transition = transition; + this._parseStack.chunkPos = chunkPos; + } /** * Parse UTF32 codepoints in `data` up to `length`. @@ -464,23 +492,141 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP * - DCS_PARAM:PARAM * - OSC_STRING:OSC_PUT * - DCS_PASSTHROUGH:DCS_PUT + * + * Note on asynchronous handler support: + * Any handler returning a promise will be treated as asynchronous. + * To keep the in-band blocking working for async handlers, `parse` pauses execution, + * creates a stack save and returns the promise to the caller. + * For proper continuation of the paused state it is important + * to await the promise resolving. On resolve the parse must be repeated + * with the same chunk of data and the resolved value in `promiseResult` + * until no promise is returned. + * + * Important: With only sync handlers defined, parsing is completely synchronous as well. + * As soon as an async handler is involved, synchronous parsing is not possible anymore. + * + * Boilerplate for proper parsing of multiple chunks with async handlers: + * + * ```typescript + * async function parseMultipleChunks(chunks: Uint32Array[]): Promise { + * for (const chunk of chunks) { + * let result: void | Promise; + * let prev: boolean | undefined; + * while (result = parser.parse(chunk, chunk.length, prev)) { + * prev = await result; + * } + * } + * // finished parsing all chunks... + * } + * ``` */ - public parse(data: Uint32Array, length: number): void { + public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise { 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; + let start = 0; + let handlerResult: void | boolean | Promise; + + // resume from async handler + if (this._parseStack.state) { + // allow sync parser reset even in continuation mode + // Note: can be used to recover parser from improper continuation error below + if (this._parseStack.state === ParserStackType.RESET) { + this._parseStack.state = ParserStackType.NONE; + start = this._parseStack.chunkPos + 1; // continue with next codepoint in GROUND + } else { + if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) { + /** + * Reject further parsing on improper continuation after pausing. + * This is a really bad condition with screwed up execution order and prolly messed up + * terminal state, therefore we exit hard with an exception and reject any further parsing. + * + * Note: With `Terminal.write` usage this exception should never occur, as the top level + * calls are guaranteed to handle async conditions properly. If you ever encounter this + * exception in your terminal integration it indicates, that you injected data chunks to + * `InputHandler.parse` or `EscapeSequenceParser.parse` synchronously without waiting for + * continuation of a running async handler. + * + * It is possible to get rid of this error by calling `reset`. But dont rely on that, + * as the pending async handler still might mess up the terminal later. Instead fix the faulty + * async handling, so this error will not be thrown anymore. + */ + this._parseStack.state = ParserStackType.FAIL; + throw new Error('improper continuation due to previous async handler, giving up parsing'); + } + + // we have to resume the old handler loop if: + // - return value of the promise was `false` + // - handlers are not exhausted yet + const handlers = this._parseStack.handlers; + let handlerPos = this._parseStack.handlerPos - 1; + switch (this._parseStack.state) { + case ParserStackType.CSI: + if (promiseResult === false && handlerPos > -1) { + for (; handlerPos >= 0; handlerPos--) { + handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + } + } + this._parseStack.handlers = []; + break; + case ParserStackType.ESC: + if (promiseResult === false && handlerPos > -1) { + for (; handlerPos >= 0; handlerPos--) { + handlerResult = (handlers as EscHandlerType[])[handlerPos](); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + } + } + this._parseStack.handlers = []; + break; + case ParserStackType.DCS: + code = data[this._parseStack.chunkPos]; + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { + return handlerResult; + } + if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + case ParserStackType.OSC: + code = data[this._parseStack.chunkPos]; + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { + return handlerResult; + } + if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + } + // cleanup before continuing with the main sync loop + this._parseStack.state = ParserStackType.NONE; + start = this._parseStack.chunkPos + 1; + this.precedingCodepoint = 0; + this.currentState = this._parseStack.transition & TableAccess.TRANSITION_STATE_MASK; + } + } + + // continue with main sync loop // process input string - for (let i = 0; i < length; ++i) { + for (let i = start; i < length; ++i) { code = data[i]; // normal transition & action lookup - transition = table[currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)]; + transition = this._transitions.table[this.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 @@ -520,9 +666,9 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP { position: i, code, - currentState, - collect, - params, + currentState: this.currentState, + collect: this._collect, + params: this._params, abort: false }); if (inject.abort) return; @@ -530,16 +676,21 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP break; case ParserAction.CSI_DISPATCH: // Trigger CSI Handler - const handlers = this._csiHandlers[collect << 8 | code]; + const handlers = this._csiHandlers[this._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) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + handlerResult = handlers[j](this._params); + if (handlerResult === true) { break; + } else if (handlerResult instanceof Promise) { + this._preserveStack(ParserStackType.CSI, handlers, j, transition, i); + return handlerResult; } } if (j < 0) { - this._csiHandlerFb(collect << 8 | code, params); + this._csiHandlerFb(this._collect << 8 | code, this._params); } this.precedingCodepoint = 0; break; @@ -548,91 +699,98 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP do { switch (code) { case 0x3b: - params.addParam(0); // ZDM + this._params.addParam(0); // ZDM break; case 0x3a: - params.addSubParam(-1); + this._params.addSubParam(-1); break; default: // 0x30 - 0x39 - params.addDigit(code - 48); + this._params.addDigit(code - 48); } } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c); i--; break; case ParserAction.COLLECT: - collect <<= 8; - collect |= code; + this._collect <<= 8; + this._collect |= code; break; case ParserAction.ESC_DISPATCH: - const handlersEsc = this._escHandlers[collect << 8 | code]; + const handlersEsc = this._escHandlers[this._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) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + handlerResult = handlersEsc[jj](); + if (handlerResult === true) { break; + } else if (handlerResult instanceof Promise) { + this._preserveStack(ParserStackType.ESC, handlersEsc, jj, transition, i); + return handlerResult; } } if (jj < 0) { - this._escHandlerFb(collect << 8 | code); + this._escHandlerFb(this._collect << 8 | code); } this.precedingCodepoint = 0; break; case ParserAction.CLEAR: - params.reset(); - params.addParam(0); // ZDM - collect = 0; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; break; case ParserAction.DCS_HOOK: - dcs.hook(collect << 8 | code, params); + this._dcsParser.hook(this._collect << 8 | code, this._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); + this._dcsParser.put(data, i, j); i = j - 1; break; } } break; case ParserAction.DCS_UNHOOK: - dcs.unhook(code !== 0x18 && code !== 0x1a); + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a); + if (handlerResult) { + this._preserveStack(ParserStackType.DCS, [], 0, transition, i); + return handlerResult; + } if (code === 0x1b) transition |= ParserState.ESCAPE; - params.reset(); - params.addParam(0); // ZDM - collect = 0; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; this.precedingCodepoint = 0; break; case ParserAction.OSC_START: - osc.start(); + this._oscParser.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); + if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { + this._oscParser.put(data, i, j); i = j - 1; break; } } break; case ParserAction.OSC_END: - osc.end(code !== 0x18 && code !== 0x1a); + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a); + if (handlerResult) { + this._preserveStack(ParserStackType.OSC, [], 0, transition, i); + return handlerResult; + } if (code === 0x1b) transition |= ParserState.ESCAPE; - params.reset(); - params.addParam(0); // ZDM - collect = 0; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; this.precedingCodepoint = 0; break; } - currentState = transition & TableAccess.TRANSITION_STATE_MASK; + this.currentState = transition & TableAccess.TRANSITION_STATE_MASK; } - - // save collected intermediates - this._collect = collect; - - // save state - this.currentState = currentState; } } diff --git a/src/common/parser/OscParser.test.ts b/src/common/parser/OscParser.test.ts index 127bd83a..5c7f5777 100644 --- a/src/common/parser/OscParser.test.ts +++ b/src/common/parser/OscParser.test.ts @@ -23,11 +23,12 @@ class TestHandler implements IOscHandler { public put(data: Uint32Array, start: number, end: number): void { this.output.push([this.msg, this.id, 'PUT', utf32ToString(data, start, end)]); } - public end(success: boolean): void | boolean { + public end(success: boolean): boolean { this.output.push([this.msg, this.id, 'END', success]); if (this.returnFalse) { return false; } + return true; } } @@ -78,7 +79,7 @@ describe('OscParser', () => { }); describe('handler registration', () => { it('setOscHandler', () => { - parser.setHandler(1234, new TestHandler(1234, reports, 'th')); + parser.registerHandler(1234, new TestHandler(1234, reports, 'th')); parser.start(); let data = toUtf32('1234;Here comes'); parser.put(data, 0, data.length); @@ -94,7 +95,7 @@ describe('OscParser', () => { ]); }); it('clearOscHandler', () => { - parser.setHandler(1234, new TestHandler(1234, reports, 'th')); + parser.registerHandler(1234, new TestHandler(1234, reports, 'th')); parser.clearHandler(1234); parser.start(); let data = toUtf32('1234;Here comes'); @@ -111,8 +112,8 @@ describe('OscParser', () => { ]); }); it('addOscHandler', () => { - parser.setHandler(1234, new TestHandler(1234, reports, 'th1')); - parser.addHandler(1234, new TestHandler(1234, reports, 'th2')); + parser.registerHandler(1234, new TestHandler(1234, reports, 'th1')); + parser.registerHandler(1234, new TestHandler(1234, reports, 'th2')); parser.start(); let data = toUtf32('1234;Here comes'); parser.put(data, 0, data.length); @@ -131,8 +132,8 @@ describe('OscParser', () => { ]); }); it('addOscHandler with return false', () => { - parser.setHandler(1234, new TestHandler(1234, reports, 'th1')); - parser.addHandler(1234, new TestHandler(1234, reports, 'th2', true)); + parser.registerHandler(1234, new TestHandler(1234, reports, 'th1')); + parser.registerHandler(1234, new TestHandler(1234, reports, 'th2', true)); parser.start(); let data = toUtf32('1234;Here comes'); parser.put(data, 0, data.length); @@ -151,8 +152,8 @@ describe('OscParser', () => { ]); }); it('dispose handlers', () => { - parser.setHandler(1234, new TestHandler(1234, reports, 'th1')); - const dispo = parser.addHandler(1234, new TestHandler(1234, reports, 'th2', true)); + parser.registerHandler(1234, new TestHandler(1234, reports, 'th1')); + const dispo = parser.registerHandler(1234, new TestHandler(1234, reports, 'th2', true)); dispo.dispose(); parser.start(); let data = toUtf32('1234;Here comes'); @@ -170,7 +171,7 @@ describe('OscParser', () => { }); describe('OscHandlerFactory', () => { it('should be called once on end(true)', () => { - parser.setHandler(1234, new OscHandler(data => reports.push([1234, data]))); + parser.registerHandler(1234, new OscHandler(data => { reports.push([1234, data]); return true; })); parser.start(); let data = toUtf32('1234;Here comes'); parser.put(data, 0, data.length); @@ -180,7 +181,7 @@ describe('OscParser', () => { assert.deepEqual(reports, [[1234, 'Here comes the mouse!']]); }); it('should not be called on end(false)', () => { - parser.setHandler(1234, new OscHandler(data => reports.push([1234, data]))); + parser.registerHandler(1234, new OscHandler(data => { reports.push([1234, data]); return true; })); parser.start(); let data = toUtf32('1234;Here comes'); parser.put(data, 0, data.length); @@ -190,8 +191,8 @@ describe('OscParser', () => { assert.deepEqual(reports, []); }); it('should be disposable', () => { - parser.setHandler(1234, new OscHandler(data => reports.push(['one', data]))); - const dispo = parser.addHandler(1234, new OscHandler(data => reports.push(['two', data]))); + parser.registerHandler(1234, new OscHandler(data => { reports.push(['one', data]); return true; })); + const dispo = parser.registerHandler(1234, new OscHandler(data => { reports.push(['two', data]); return true; })); parser.start(); let data = toUtf32('1234;Here comes'); parser.put(data, 0, data.length); @@ -209,8 +210,8 @@ describe('OscParser', () => { assert.deepEqual(reports, [['two', 'Here comes the mouse!'], ['one', 'some other data']]); }); it('should respect return false', () => { - parser.setHandler(1234, new OscHandler(data => reports.push(['one', data]))); - parser.addHandler(1234, new OscHandler(data => { reports.push(['two', data]); return false; })); + parser.registerHandler(1234, new OscHandler(data => { reports.push(['one', data]); return true; })); + parser.registerHandler(1234, new OscHandler(data => { reports.push(['two', data]); return false; })); parser.start(); let data = toUtf32('1234;Here comes'); parser.put(data, 0, data.length); @@ -221,7 +222,7 @@ describe('OscParser', () => { }); it('should work up to payload limit', function(): void { this.timeout(10000); - parser.setHandler(1234, new OscHandler(data => reports.push([1234, data]))); + parser.registerHandler(1234, new OscHandler(data => { reports.push([1234, data]); return true; })); parser.start(); let data = toUtf32('1234;'); parser.put(data, 0, data.length); @@ -234,7 +235,7 @@ describe('OscParser', () => { }); it('should abort for payload limit +1', function(): void { this.timeout(10000); - parser.setHandler(1234, new OscHandler(data => reports.push([1234, data]))); + parser.registerHandler(1234, new OscHandler(data => { reports.push([1234, data]); return true; })); parser.start(); let data = toUtf32('1234;'); parser.put(data, 0, data.length); @@ -249,3 +250,204 @@ describe('OscParser', () => { }); }); }); + + +class TestHandlerAsync implements IOscHandler { + constructor(public id: number, public output: any[], public msg: string, public returnFalse: boolean = false) {} + public start(): void { + this.output.push([this.msg, this.id, 'START']); + } + public put(data: Uint32Array, start: number, end: number): void { + this.output.push([this.msg, this.id, 'PUT', utf32ToString(data, start, end)]); + } + public async end(success: boolean): Promise { + await new Promise(res => setTimeout(res, 20)); + this.output.push([this.msg, this.id, 'END', success]); + if (this.returnFalse) { + return false; + } + return true; + } +} +async function endP(parser: OscParser, success: boolean): Promise { + let result: void | Promise; + let prev: boolean | undefined; + while (result = parser.end(success, prev)) { + prev = await result; + } +} + +describe('OscParser - async tests', () => { + let parser: OscParser; + let reports: any[] = []; + beforeEach(() => { + reports = []; + parser = new OscParser(); + parser.setHandlerFallback((id, action, data) => { + reports.push([id, action, data]); + }); + }); + describe('sync and async mixed', () => { + describe('sync | async | sync', () => { + it('first should run, cleanup action for others', async () => { + parser.registerHandler(1234, new TestHandler(1234, reports, 's1')); + parser.registerHandler(1234, new TestHandlerAsync(1234, reports, 'a1')); + parser.registerHandler(1234, new TestHandler(1234, reports, 's2')); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await endP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['s2', 1234, 'START'], + ['a1', 1234, 'START'], + ['s1', 1234, 'START'], + ['s2', 1234, 'PUT', 'Here comes'], + ['a1', 1234, 'PUT', 'Here comes'], + ['s1', 1234, 'PUT', 'Here comes'], + ['s2', 1234, 'PUT', 'the mouse!'], + ['a1', 1234, 'PUT', 'the mouse!'], + ['s1', 1234, 'PUT', 'the mouse!'], + ['s2', 1234, 'END', true], + ['a1', 1234, 'END', false], + ['s1', 1234, 'END', false] + ]); + }); + it('all should run', async () => { + parser.registerHandler(1234, new TestHandler(1234, reports, 's1', true)); + parser.registerHandler(1234, new TestHandlerAsync(1234, reports, 'a1', true)); + parser.registerHandler(1234, new TestHandler(1234, reports, 's2', true)); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await endP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['s2', 1234, 'START'], + ['a1', 1234, 'START'], + ['s1', 1234, 'START'], + ['s2', 1234, 'PUT', 'Here comes'], + ['a1', 1234, 'PUT', 'Here comes'], + ['s1', 1234, 'PUT', 'Here comes'], + ['s2', 1234, 'PUT', 'the mouse!'], + ['a1', 1234, 'PUT', 'the mouse!'], + ['s1', 1234, 'PUT', 'the mouse!'], + ['s2', 1234, 'END', true], + ['a1', 1234, 'END', true], + ['s1', 1234, 'END', true] + ]); + }); + }); + describe('async | sync | async', () => { + it('first should run, cleanup action for others', async () => { + parser.registerHandler(1234, new TestHandlerAsync(1234, reports, 's1')); + parser.registerHandler(1234, new TestHandler(1234, reports, 'a1')); + parser.registerHandler(1234, new TestHandlerAsync(1234, reports, 's2')); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await endP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['s2', 1234, 'START'], + ['a1', 1234, 'START'], + ['s1', 1234, 'START'], + ['s2', 1234, 'PUT', 'Here comes'], + ['a1', 1234, 'PUT', 'Here comes'], + ['s1', 1234, 'PUT', 'Here comes'], + ['s2', 1234, 'PUT', 'the mouse!'], + ['a1', 1234, 'PUT', 'the mouse!'], + ['s1', 1234, 'PUT', 'the mouse!'], + ['s2', 1234, 'END', true], + ['a1', 1234, 'END', false], + ['s1', 1234, 'END', false] + ]); + }); + it('all should run', async () => { + parser.registerHandler(1234, new TestHandlerAsync(1234, reports, 's1', true)); + parser.registerHandler(1234, new TestHandler(1234, reports, 'a1', true)); + parser.registerHandler(1234, new TestHandlerAsync(1234, reports, 's2', true)); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32('the mouse!'); + parser.put(data, 0, data.length); + await endP(parser, true); + assert.deepEqual(reports, [ + // messages from TestHandler + ['s2', 1234, 'START'], + ['a1', 1234, 'START'], + ['s1', 1234, 'START'], + ['s2', 1234, 'PUT', 'Here comes'], + ['a1', 1234, 'PUT', 'Here comes'], + ['s1', 1234, 'PUT', 'Here comes'], + ['s2', 1234, 'PUT', 'the mouse!'], + ['a1', 1234, 'PUT', 'the mouse!'], + ['s1', 1234, 'PUT', 'the mouse!'], + ['s2', 1234, 'END', true], + ['a1', 1234, 'END', true], + ['s1', 1234, 'END', true] + ]); + }); + }); + describe('OscHandlerFactory', () => { + it('should be called once on end(true)', async () => { + parser.registerHandler(1234, new OscHandler(async data => { reports.push([1234, data]); return true; })); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + parser.end(true); + await endP(parser, true); + assert.deepEqual(reports, [[1234, 'Here comes the mouse!']]); + }); + it('should not be called on end(false)', async () => { + parser.registerHandler(1234, new OscHandler(async data => { reports.push([1234, data]); return true; })); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + await endP(parser, false); + assert.deepEqual(reports, []); + }); + it('should be disposable', async () => { + parser.registerHandler(1234, new OscHandler(async data => { reports.push(['one', data]); return true; })); + const dispo = parser.registerHandler(1234, new OscHandler(async data => { reports.push(['two', data]); return true; })); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + await endP(parser, true); + assert.deepEqual(reports, [['two', 'Here comes the mouse!']]); + dispo.dispose(); + parser.start(); + data = toUtf32('1234;some other'); + parser.put(data, 0, data.length); + data = toUtf32(' data'); + parser.put(data, 0, data.length); + await endP(parser, true); + assert.deepEqual(reports, [['two', 'Here comes the mouse!'], ['one', 'some other data']]); + }); + it('should respect return false', async () => { + parser.registerHandler(1234, new OscHandler(async data => { reports.push(['one', data]); return true; })); + parser.registerHandler(1234, new OscHandler(async data => { reports.push(['two', data]); return false; })); + parser.start(); + let data = toUtf32('1234;Here comes'); + parser.put(data, 0, data.length); + data = toUtf32(' the mouse!'); + parser.put(data, 0, data.length); + await endP(parser, true); + assert.deepEqual(reports, [['two', 'Here comes the mouse!'], ['one', 'Here comes the mouse!']]); + }); + }); + }); +}); diff --git a/src/common/parser/OscParser.ts b/src/common/parser/OscParser.ts index e8c5a801..32710aed 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -3,19 +3,26 @@ * @license MIT */ -import { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser } from 'common/parser/Types'; +import { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser, ISubParserStackState } from 'common/parser/Types'; import { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants'; import { utf32ToString } from 'common/input/TextDecoder'; import { IDisposable } from 'common/Types'; +const EMPTY_HANDLERS: IOscHandler[] = []; export class OscParser implements IOscParser { private _state = OscState.START; + private _active = EMPTY_HANDLERS; private _id = -1; private _handlers: IHandlerCollection = Object.create(null); private _handlerFb: OscFallbackHandlerType = () => { }; + private _stack: ISubParserStackState = { + paused: false, + loopPosition: 0, + fallThrough: false + }; - public addHandler(ident: number, handler: IOscHandler): IDisposable { + public registerHandler(ident: number, handler: IOscHandler): IDisposable { if (this._handlers[ident] === undefined) { this._handlers[ident] = []; } @@ -30,9 +37,6 @@ export class OscParser implements IOscParser { } }; } - public setHandler(ident: number, handler: IOscHandler): void { - this._handlers[ident] = [handler]; - } public clearHandler(ident: number): void { if (this._handlers[ident]) delete this._handlers[ident]; } @@ -42,58 +46,40 @@ export class OscParser implements IOscParser { public dispose(): void { this._handlers = Object.create(null); - this._handlerFb = () => {}; + this._handlerFb = () => { }; + this._active = EMPTY_HANDLERS; } public reset(): void { - // cleanup handlers if payload was already sent + // force cleanup handlers if payload was already sent if (this._state === OscState.PAYLOAD) { - this.end(false); + for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) { + this._active[j].end(false); + } } + this._stack.paused = false; + this._active = EMPTY_HANDLERS; this._id = -1; this._state = OscState.START; } private _start(): void { - const handlers = this._handlers[this._id]; - if (!handlers) { + this._active = this._handlers[this._id] || EMPTY_HANDLERS; + if (!this._active.length) { this._handlerFb(this._id, 'START'); } else { - for (let j = handlers.length - 1; j >= 0; j--) { - handlers[j].start(); + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].start(); } } } private _put(data: Uint32Array, start: number, end: number): void { - const handlers = this._handlers[this._id]; - if (!handlers) { + if (!this._active.length) { 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); + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].put(data, start, end); } } } @@ -101,7 +87,6 @@ export class OscParser implements IOscParser { public start(): void { // always reset leftover handlers this.reset(); - this._id = -1; this._state = OscState.ID; } @@ -144,7 +129,7 @@ export class OscParser implements IOscParser { * Whether the OSC got aborted or finished normally * is indicated by `success`. */ - public end(success: boolean): void { + public end(success: boolean, promiseResult: boolean = true): void | Promise { if (this._state === OscState.START) { return; } @@ -156,8 +141,49 @@ export class OscParser implements IOscParser { if (this._state === OscState.ID) { this._start(); } - this._end(success); + + if (!this._active.length) { + this._handlerFb(this._id, 'END', success); + } else { + let handlerResult: boolean | Promise = false; + let j = this._active.length - 1; + let fallThrough = false; + if (this._stack.paused) { + j = this._stack.loopPosition - 1; + handlerResult = promiseResult; + fallThrough = this._stack.fallThrough; + this._stack.paused = false; + } + if (!fallThrough && handlerResult === false) { + for (; j >= 0; j--) { + handlerResult = this._active[j].end(success); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = false; + return handlerResult; + } + } + j--; + } + // cleanup left over handlers + // we always have to call .end for proper cleanup, + // here we use `success` to indicate whether a handler should execute + for (; j >= 0; j--) { + handlerResult = this._active[j].end(false); + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } + } + } + } + this._active = EMPTY_HANDLERS; this._id = -1; this._state = OscState.START; } @@ -171,7 +197,7 @@ export class OscHandler implements IOscHandler { private _data = ''; private _hitLimit: boolean = false; - constructor(private _handler: (data: string) => any) {} + constructor(private _handler: (data: string) => boolean | Promise) { } public start(): void { this._data = ''; @@ -189,12 +215,21 @@ export class OscHandler implements IOscHandler { } } - public end(success: boolean): any { - let ret; + public end(success: boolean): boolean | Promise { + let ret: boolean | Promise = false; if (this._hitLimit) { ret = false; } else if (success) { ret = this._handler(this._data); + if (ret instanceof Promise) { + // need to hold data until `ret` got resolved + // dont care for errors, data will be freed anyway on next start + return ret.then(res => { + this._data = ''; + this._hitLimit = false; + return res; + }); + } } this._data = ''; this._hitLimit = false; diff --git a/src/common/parser/Types.d.ts b/src/common/parser/Types.d.ts index e2fac89f..3a621eab 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -6,6 +6,7 @@ import { IDisposable } from 'common/Types'; import { ParserState } from 'common/parser/Constants'; + /** sequence params serialized to js arrays */ export type ParamsArray = (number | number[])[]; @@ -69,7 +70,7 @@ export interface IParsingState { * CSI handler types. * Note: `params` is borrowed. */ -export type CsiHandlerType = (params: IParams) => boolean | void; +export type CsiHandlerType = (params: IParams) => boolean | Promise; export type CsiFallbackHandlerType = (ident: number, params: IParams) => void; /** @@ -93,20 +94,20 @@ export interface IDcsHandler { * execution of the command should depend on `success`. * To save memory also cleanup data structures here. */ - unhook(success: boolean): void | boolean; + unhook(success: boolean): boolean | Promise; } export type DcsFallbackHandlerType = (ident: number, action: 'HOOK' | 'PUT' | 'UNHOOK', payload?: any) => void; /** * ESC handler types. */ -export type EscHandlerType = () => boolean | void; +export type EscHandlerType = () => boolean | Promise; export type EscFallbackHandlerType = (identifier: number) => void; /** * EXECUTE handler types. */ -export type ExecuteHandlerType = () => boolean | void; +export type ExecuteHandlerType = () => boolean; export type ExecuteFallbackHandlerType = (ident: number) => void; /** @@ -129,7 +130,7 @@ export interface IOscHandler { * execution of the command should depend on `success`. * To save memory also cleanup data structures here. */ - end(success: boolean): void | boolean; + end(success: boolean): boolean | Promise; } export type OscFallbackHandlerType = (ident: number, action: 'START' | 'PUT' | 'END', payload?: any) => void; @@ -160,7 +161,7 @@ export interface IEscapeSequenceParser extends IDisposable { * Parse UTF32 codepoints in `data` up to `length`. * @param data The data to parse. */ - parse(data: Uint32Array, length: number): void; + parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise; /** * Get string from numercial function identifier `ident`. @@ -174,29 +175,25 @@ export interface IEscapeSequenceParser extends IDisposable { setPrintHandler(handler: PrintHandlerType): void; clearPrintHandler(): void; - setEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): void; + registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable; 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; + registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable; clearCsiHandler(id: IFunctionIdentifier): void; setCsiHandlerFallback(callback: CsiFallbackHandlerType): void; - addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable; - setDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): void; + registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable; clearDcsHandler(id: IFunctionIdentifier): void; setDcsHandlerFallback(handler: DcsFallbackHandlerType): void; - addDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable; - setOscHandler(ident: number, handler: IOscHandler): void; + registerOscHandler(ident: number, handler: IOscHandler): IDisposable; clearOscHandler(ident: number): void; setOscHandlerFallback(handler: OscFallbackHandlerType): void; - addOscHandler(ident: number, handler: IOscHandler): IDisposable; setErrorHandler(handler: (state: IParsingState) => IParsingState): void; clearErrorHandler(): void; @@ -209,8 +206,7 @@ export interface IEscapeSequenceParser extends IDisposable { */ export interface ISubParser extends IDisposable { reset(): void; - addHandler(ident: number, handler: T): IDisposable; - setHandler(ident: number, handler: T): void; + registerHandler(ident: number, handler: T): IDisposable; clearHandler(ident: number): void; setHandlerFallback(handler: U): void; put(data: Uint32Array, start: number, end: number): void; @@ -218,12 +214,12 @@ export interface ISubParser extends IDisposable { export interface IOscParser extends ISubParser { start(): void; - end(success: boolean): void; + end(success: boolean, promiseResult?: boolean): void | Promise; } export interface IDcsParser extends ISubParser { hook(ident: number, params: IParams): void; - unhook(success: boolean): void; + unhook(success: boolean, promiseResult?: boolean): void | Promise; } /** @@ -242,3 +238,37 @@ export interface IFunctionIdentifier { export interface IHandlerCollection { [key: string]: T[]; } + +/** + * Types for async parser support. + */ + +// type of saved stack state in parser +export const enum ParserStackType { + NONE = 0, + FAIL, + RESET, + CSI, + ESC, + OSC, + DCS +} + +// aggregate of resumable handler lists +export type ResumableHandlersType = CsiHandlerType[] | EscHandlerType[]; + +// saved stack state of the parser +export interface IParserStackState { + state: ParserStackType; + handlers: ResumableHandlersType; + handlerPos: number; + transition: number; + chunkPos: number; +} + +// saved stack state of subparser (OSC and DCS) +export interface ISubParserStackState { + paused: boolean; + loopPosition: number; + fallThrough: boolean; +} diff --git a/src/common/services/LogService.ts b/src/common/services/LogService.ts index 3c0ccaf1..de4e18f8 100644 --- a/src/common/services/LogService.ts +++ b/src/common/services/LogService.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { ILogService, IOptionsService } from 'common/services/Services'; +import { ILogService, IOptionsService, LogLevelEnum } from 'common/services/Services'; type LogType = (message?: any, ...optionalParams: any[]) => void; @@ -19,21 +19,12 @@ interface IConsole { // 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 optionsKeyToLogLevel: { [key: string]: LogLevelEnum } = { + debug: LogLevelEnum.DEBUG, + info: LogLevelEnum.INFO, + warn: LogLevelEnum.WARN, + error: LogLevelEnum.ERROR, + off: LogLevelEnum.OFF }; const LOG_PREFIX = 'xterm.js: '; @@ -41,7 +32,7 @@ const LOG_PREFIX = 'xterm.js: '; export class LogService implements ILogService { public serviceBrand: any; - private _logLevel!: LogLevel; + public logLevel: LogLevelEnum = LogLevelEnum.OFF; constructor( @IOptionsService private readonly _optionsService: IOptionsService @@ -55,7 +46,7 @@ export class LogService implements ILogService { } private _updateLogLevel(): void { - this._logLevel = optionsKeyToLogLevel[this._optionsService.options.logLevel]; + this.logLevel = optionsKeyToLogLevel[this._optionsService.options.logLevel]; } private _evalLazyOptionalParams(optionalParams: any[]): void { @@ -72,25 +63,25 @@ export class LogService implements ILogService { } public debug(message: string, ...optionalParams: any[]): void { - if (this._logLevel <= LogLevel.DEBUG) { + if (this.logLevel <= LogLevelEnum.DEBUG) { this._log(console.log, message, optionalParams); } } public info(message: string, ...optionalParams: any[]): void { - if (this._logLevel <= LogLevel.INFO) { + if (this.logLevel <= LogLevelEnum.INFO) { this._log(console.info, message, optionalParams); } } public warn(message: string, ...optionalParams: any[]): void { - if (this._logLevel <= LogLevel.WARN) { + if (this.logLevel <= LogLevelEnum.WARN) { this._log(console.warn, message, optionalParams); } } public error(message: string, ...optionalParams: any[]): void { - if (this._logLevel <= LogLevel.ERROR) { + if (this.logLevel <= LogLevelEnum.ERROR) { this._log(console.error, message, optionalParams); } } diff --git a/src/common/services/Services.ts b/src/common/services/Services.ts index c733e73e..1fbf57fb 100644 --- a/src/common/services/Services.ts +++ b/src/common/services/Services.ts @@ -161,6 +161,8 @@ export const ILogService = createDecorator('LogService'); export interface ILogService { serviceBrand: undefined; + logLevel: LogLevelEnum; + debug(message: any, ...optionalParams: any[]): void; info(message: any, ...optionalParams: any[]): void; warn(message: any, ...optionalParams: any[]): void; @@ -181,6 +183,13 @@ export interface IOptionsService { export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number; export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off'; +export enum LogLevelEnum { + DEBUG = 0, + INFO = 1, + WARN = 2, + ERROR = 3, + OFF = 4 +} export type RendererType = 'dom' | 'canvas'; export interface IPartialTerminalOptions { diff --git a/test/api/Parser.api.ts b/test/api/Parser.api.ts index 77101e23..7bd55544 100644 --- a/test/api/Parser.api.ts +++ b/test/api/Parser.api.ts @@ -14,8 +14,8 @@ let page: Page; const width = 800; const height = 600; -describe('Parser Integration Tests', function(): void { - before(async function(): Promise { +describe('Parser Integration Tests', function (): void { + before(async function (): Promise { const browserType = getBrowserType(); browser = await browserType.launch({ headless: process.argv.indexOf('--headless') !== -1 @@ -28,84 +28,189 @@ describe('Parser Integration Tests', function(): void { after(async () => browser.close()); - describe('addCsiHandler', () => { + describe('registerCsiHandler', () => { it('should call custom CSI handler with js array params', async () => { await page.evaluate(` window.term.reset(); window._customCsiHandlerParams = []; - const _customCsiHandler = window.term.parser.addCsiHandler({final: 'm'}, (params, collect) => { + const _customCsiHandler = window.term.parser.registerCsiHandler({final: 'm'}, (params, collect) => { window._customCsiHandlerParams.push(params); return false; }, ''); `); await writeSync(page, '\x1b[38;5;123mparams\x1b[38:2::50:100:150msubparams'); - assert.deepEqual(await page.evaluate(`(() => window._customCsiHandlerParams)();`), [[38, 5, 123], [38, [2, -1, 50, 100, 150]]]); + assert.deepEqual(await page.evaluate(`window._customCsiHandlerParams`), [ + [38, 5, 123], + [38, [2, -1, 50, 100, 150]] + ]); + }); + it('async', async () => { + await page.evaluate(` + window.term.reset(); + window._customCsiHandlerCallStack = []; + const _customCsiHandlerA = window.term.parser.registerCsiHandler({intermediates:'+', final: 'Z'}, params => { + window._customCsiHandlerCallStack.push(['A', params]); + return false; + }); + const _customCsiHandlerB = window.term.parser.registerCsiHandler({intermediates:'+', final: 'Z'}, async params => { + await new Promise(res => setTimeout(res, 50)); + window._customCsiHandlerCallStack.push(['B', params]); + return false; + }); + const _customCsiHandlerC = window.term.parser.registerCsiHandler({intermediates:'+', final: 'Z'}, params => { + window._customCsiHandlerCallStack.push(['C', params]); + return false; + }); + `); + await writeSync(page, '\x1b[1;2+Z'); + assert.deepEqual(await page.evaluate(`window._customCsiHandlerCallStack`), [ + ['C', [1, 2]], + ['B', [1, 2]], + ['A', [1, 2]] + ]); }); }); - describe('addDcsHandler', () => { + describe('registerDcsHandler', () => { it('should respects return value', async () => { await page.evaluate(` window.term.reset(); window._customDcsHandlerCallStack = []; - const _customDcsHandlerA = window.term.parser.addDcsHandler({intermediates:'+', final: 'p'}, (data, params) => { + const _customDcsHandlerA = window.term.parser.registerDcsHandler({intermediates:'+', final: 'p'}, (data, params) => { window._customDcsHandlerCallStack.push(['A', params, data]); return false; }); - const _customDcsHandlerB = window.term.parser.addDcsHandler({intermediates:'+', final: 'p'}, (data, params) => { + const _customDcsHandlerB = window.term.parser.registerDcsHandler({intermediates:'+', final: 'p'}, (data, params) => { window._customDcsHandlerCallStack.push(['B', params, data]); return true; }); - const _customDcsHandlerC = window.term.parser.addDcsHandler({intermediates:'+', final: 'p'}, (data, params) => { + const _customDcsHandlerC = window.term.parser.registerDcsHandler({intermediates:'+', final: 'p'}, (data, params) => { window._customDcsHandlerCallStack.push(['C', params, data]); return false; }); `); await writeSync(page, '\x1bP1;2+psome data\x1b\\\\'); - assert.deepEqual(await page.evaluate(`(() => window._customDcsHandlerCallStack)();`), [['C', [1, 2], 'some data'], ['B', [1, 2], 'some data']]); + assert.deepEqual(await page.evaluate(`window._customDcsHandlerCallStack`), [ + ['C', [1, 2], 'some data'], + ['B', [1, 2], 'some data'] + ]); + }); + it('async', async () => { + await page.evaluate(` + window.term.reset(); + window._customDcsHandlerCallStack = []; + const _customDcsHandlerA = window.term.parser.registerDcsHandler({intermediates:'+', final: 'q'}, (data, params) => { + window._customDcsHandlerCallStack.push(['A', params, data]); + return false; + }); + const _customDcsHandlerB = window.term.parser.registerDcsHandler({intermediates:'+', final: 'q'}, async (data, params) => { + await new Promise(res => setTimeout(res, 50)); + window._customDcsHandlerCallStack.push(['B', params, data]); + return false; + }); + const _customDcsHandlerC = window.term.parser.registerDcsHandler({intermediates:'+', final: 'q'}, (data, params) => { + window._customDcsHandlerCallStack.push(['C', params, data]); + return false; + }); + `); + await writeSync(page, '\x1bP1;2+qsome data\x1b\\\\'); + assert.deepEqual(await page.evaluate(`window._customDcsHandlerCallStack`), [ + ['C', [1, 2], 'some data'], + ['B', [1, 2], 'some data'], + ['A', [1, 2], 'some data'] + ]); }); }); - describe('addEscHandler', () => { + describe('registerEscHandler', () => { it('should respects return value', async () => { await page.evaluate(` window.term.reset(); window._customEscHandlerCallStack = []; - const _customEscHandlerA = window.term.parser.addEscHandler({intermediates:'(', final: 'B'}, () => { + const _customEscHandlerA = window.term.parser.registerEscHandler({intermediates:'(', final: 'B'}, () => { window._customEscHandlerCallStack.push('A'); return false; }); - const _customEscHandlerB = window.term.parser.addEscHandler({intermediates:'(', final: 'B'}, () => { + const _customEscHandlerB = window.term.parser.registerEscHandler({intermediates:'(', final: 'B'}, () => { window._customEscHandlerCallStack.push('B'); return true; }); - const _customEscHandlerC = window.term.parser.addEscHandler({intermediates:'(', final: 'B'}, () => { + const _customEscHandlerC = window.term.parser.registerEscHandler({intermediates:'(', final: 'B'}, () => { window._customEscHandlerCallStack.push('C'); return false; }); `); await writeSync(page, '\x1b(B'); - assert.deepEqual(await page.evaluate(`(() => window._customEscHandlerCallStack)();`), ['C', 'B']); + assert.deepEqual(await page.evaluate(`window._customEscHandlerCallStack`), ['C', 'B']); + }); + it('async', async () => { + await page.evaluate(` + window.term.reset(); + window._customEscHandlerCallStack = []; + const _customEscHandlerA = window.term.parser.registerEscHandler({intermediates:'(', final: 'Z'}, () => { + window._customEscHandlerCallStack.push('A'); + return false; + }); + const _customEscHandlerB = window.term.parser.registerEscHandler({intermediates:'(', final: 'Z'}, async () => { + await new Promise(res => setTimeout(res, 50)); + window._customEscHandlerCallStack.push('B'); + return false; + }); + const _customEscHandlerC = window.term.parser.registerEscHandler({intermediates:'(', final: 'Z'}, () => { + window._customEscHandlerCallStack.push('C'); + return false; + }); + `); + await writeSync(page, '\x1b(Z'); + assert.deepEqual(await page.evaluate(`window._customEscHandlerCallStack`), ['C', 'B', 'A']); }); }); - describe('addOscHandler', () => { + describe('registerOscHandler', () => { it('should respects return value', async () => { await page.evaluate(` window.term.reset(); window._customOscHandlerCallStack = []; - const _customOscHandlerA = window.term.parser.addOscHandler(1234, data => { + const _customOscHandlerA = window.term.parser.registerOscHandler(1234, data => { window._customOscHandlerCallStack.push(['A', data]); return false; }); - const _customOscHandlerB = window.term.parser.addOscHandler(1234, data => { + const _customOscHandlerB = window.term.parser.registerOscHandler(1234, data => { window._customOscHandlerCallStack.push(['B', data]); return true; }); - const _customOscHandlerC = window.term.parser.addOscHandler(1234, data => { + const _customOscHandlerC = window.term.parser.registerOscHandler(1234, data => { window._customOscHandlerCallStack.push(['C', data]); return false; }); `); await writeSync(page, '\x1b]1234;some data\x07'); - assert.deepEqual(await page.evaluate(`(() => window._customOscHandlerCallStack)();`), [['C', 'some data'], ['B', 'some data']]); + assert.deepEqual(await page.evaluate(`window._customOscHandlerCallStack`), [ + ['C', 'some data'], + ['B', 'some data'] + ]); + }); + it('async', async () => { + await page.evaluate(` + window.term.reset(); + window._customOscHandlerCallStack = []; + const _customOscHandlerA = window.term.parser.registerOscHandler(666, data => { + window._customOscHandlerCallStack.push(['A', data]); + return false; + }); + const _customOscHandlerB = window.term.parser.registerOscHandler(666, async data => { + await new Promise(res => setTimeout(res, 50)); + window._customOscHandlerCallStack.push(['B', data]); + return false; + }); + const _customOscHandlerC = window.term.parser.registerOscHandler(666, data => { + window._customOscHandlerCallStack.push(['C', data]); + return false; + }); + `); + await writeSync(page, '\x1b]666;some data\x07'); + assert.deepEqual(await page.evaluate(`window._customOscHandlerCallStack`), [ + ['C', 'some data'], + ['B', 'some data'], + ['A', 'some data'] + ]); }); }); }); diff --git a/test/benchmark/EscapeSequenceParser.benchmark.ts b/test/benchmark/EscapeSequenceParser.benchmark.ts index e4591dde..c2707f19 100644 --- a/test/benchmark/EscapeSequenceParser.benchmark.ts +++ b/test/benchmark/EscapeSequenceParser.benchmark.ts @@ -6,9 +6,11 @@ import { perfContext, before, beforeEach, ThroughputRuntimeCase } from 'xterm-be import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser'; import { C0, C1 } from 'common/data/EscapeSequences'; -import { IDcsHandler, IParams } from 'common/parser/Types'; +import { IDcsHandler, IOscHandler, IParams } from 'common/parser/Types'; import { OscHandler } from 'common/parser/OscParser'; +import { DcsHandler } from '../../out/common/parser/DcsParser'; +const SIZE = 5000000; function toUtf32(s: string): Uint32Array { const result = new Uint32Array(s.length); @@ -18,10 +20,16 @@ function toUtf32(s: string): Uint32Array { return result; } -class DcsHandler implements IDcsHandler { +class FastDcsHandler implements IDcsHandler { public hook(params: IParams): void {} public put(data: Uint32Array, start: number, end: number): void {} - public unhook(): void {} + public unhook(success: boolean): boolean { return true; } +} + +class FastOscHandler implements IOscHandler { + public start(): void {} + public put(data: Uint32Array, start: number, end: number): void {} + public end(success: boolean): boolean { return true; } } @@ -32,80 +40,81 @@ perfContext('Parser throughput - 50MB data', () => { beforeEach(() => { parser = new EscapeSequenceParser(); parser.setPrintHandler((data, start, end) => {}); - parser.setCsiHandler({final: '@'}, params => {}); - parser.setCsiHandler({final: 'A'}, params => {}); - parser.setCsiHandler({final: 'B'}, params => {}); - parser.setCsiHandler({final: 'C'}, params => {}); - parser.setCsiHandler({final: 'D'}, params => {}); - parser.setCsiHandler({final: 'E'}, params => {}); - parser.setCsiHandler({final: 'F'}, params => {}); - parser.setCsiHandler({final: 'G'}, params => {}); - parser.setCsiHandler({final: 'H'}, params => {}); - parser.setCsiHandler({final: 'I'}, params => {}); - parser.setCsiHandler({final: 'J'}, params => {}); - parser.setCsiHandler({final: 'K'}, params => {}); - parser.setCsiHandler({final: 'L'}, params => {}); - parser.setCsiHandler({final: 'M'}, params => {}); - parser.setCsiHandler({final: 'P'}, params => {}); - parser.setCsiHandler({final: 'S'}, params => {}); - parser.setCsiHandler({final: 'T'}, params => {}); - parser.setCsiHandler({final: 'X'}, params => {}); - parser.setCsiHandler({final: 'Z'}, params => {}); - parser.setCsiHandler({final: '`'}, params => {}); - parser.setCsiHandler({final: 'a'}, params => {}); - parser.setCsiHandler({final: 'b'}, params => {}); - parser.setCsiHandler({final: 'c'}, params => {}); - parser.setCsiHandler({final: 'd'}, params => {}); - parser.setCsiHandler({final: 'e'}, params => {}); - parser.setCsiHandler({final: 'f'}, params => {}); - parser.setCsiHandler({final: 'g'}, params => {}); - parser.setCsiHandler({final: 'h'}, params => {}); - parser.setCsiHandler({final: 'l'}, params => {}); - parser.setCsiHandler({final: 'm'}, params => {}); - parser.setCsiHandler({final: 'n'}, params => {}); - parser.setCsiHandler({final: 'p'}, params => {}); - parser.setCsiHandler({final: 'q'}, params => {}); - parser.setCsiHandler({final: 'r'}, params => {}); - parser.setCsiHandler({final: 's'}, params => {}); - parser.setCsiHandler({final: 'u'}, params => {}); - parser.setExecuteHandler(C0.BEL, () => {}); - parser.setExecuteHandler(C0.LF, () => {}); - parser.setExecuteHandler(C0.VT, () => {}); - parser.setExecuteHandler(C0.FF, () => {}); - parser.setExecuteHandler(C0.CR, () => {}); - parser.setExecuteHandler(C0.BS, () => {}); - parser.setExecuteHandler(C0.HT, () => {}); - parser.setExecuteHandler(C0.SO, () => {}); - parser.setExecuteHandler(C0.SI, () => {}); - parser.setExecuteHandler(C1.IND, () => {}); - parser.setExecuteHandler(C1.NEL, () => {}); - parser.setExecuteHandler(C1.HTS, () => {}); - parser.setOscHandler(0, new OscHandler((data) => {})); - parser.setOscHandler(2, new OscHandler((data) => {})); - parser.setEscHandler({final: '7'}, () => {}); - parser.setEscHandler({final: '8'}, () => {}); - parser.setEscHandler({final: 'D'}, () => {}); - parser.setEscHandler({final: 'E'}, () => {}); - parser.setEscHandler({final: 'H'}, () => {}); - parser.setEscHandler({final: 'M'}, () => {}); - parser.setEscHandler({final: '='}, () => {}); - parser.setEscHandler({final: '>'}, () => {}); - parser.setEscHandler({final: 'c'}, () => {}); - parser.setEscHandler({final: 'n'}, () => {}); - parser.setEscHandler({final: 'o'}, () => {}); - parser.setEscHandler({final: '|'}, () => {}); - parser.setEscHandler({final: '}'}, () => {}); - parser.setEscHandler({final: '~'}, () => {}); - parser.setEscHandler({intermediates: '%', final: '@'}, () => {}); - parser.setEscHandler({intermediates: '%', final: 'G'}, () => {}); - parser.setDcsHandler({final: 'q'}, new DcsHandler()); + parser.registerCsiHandler({final: '@'}, params => true); + parser.registerCsiHandler({final: 'A'}, params => true); + parser.registerCsiHandler({final: 'B'}, params => true); + parser.registerCsiHandler({final: 'C'}, params => true); + parser.registerCsiHandler({final: 'D'}, params => true); + parser.registerCsiHandler({final: 'E'}, params => true); + parser.registerCsiHandler({final: 'F'}, params => true); + parser.registerCsiHandler({final: 'G'}, params => true); + parser.registerCsiHandler({final: 'H'}, params => true); + parser.registerCsiHandler({final: 'I'}, params => true); + parser.registerCsiHandler({final: 'J'}, params => true); + parser.registerCsiHandler({final: 'K'}, params => true); + parser.registerCsiHandler({final: 'L'}, params => true); + parser.registerCsiHandler({final: 'M'}, params => true); + parser.registerCsiHandler({final: 'P'}, params => true); + parser.registerCsiHandler({final: 'S'}, params => true); + parser.registerCsiHandler({final: 'T'}, params => true); + parser.registerCsiHandler({final: 'X'}, params => true); + parser.registerCsiHandler({final: 'Z'}, params => true); + parser.registerCsiHandler({final: '`'}, params => true); + parser.registerCsiHandler({final: 'a'}, params => true); + parser.registerCsiHandler({final: 'b'}, params => true); + parser.registerCsiHandler({final: 'c'}, params => true); + parser.registerCsiHandler({final: 'd'}, params => true); + parser.registerCsiHandler({final: 'e'}, params => true); + parser.registerCsiHandler({final: 'f'}, params => true); + parser.registerCsiHandler({final: 'g'}, params => true); + parser.registerCsiHandler({final: 'h'}, params => true); + parser.registerCsiHandler({final: 'l'}, params => true); + parser.registerCsiHandler({final: 'm'}, params => true); + parser.registerCsiHandler({final: 'n'}, params => true); + parser.registerCsiHandler({final: 'p'}, params => true); + parser.registerCsiHandler({final: 'q'}, params => true); + parser.registerCsiHandler({final: 'r'}, params => true); + parser.registerCsiHandler({final: 's'}, params => true); + parser.registerCsiHandler({final: 'u'}, params => true); + parser.setExecuteHandler(C0.BEL, () => true); + parser.setExecuteHandler(C0.LF, () => true); + parser.setExecuteHandler(C0.VT, () => true); + parser.setExecuteHandler(C0.FF, () => true); + parser.setExecuteHandler(C0.CR, () => true); + parser.setExecuteHandler(C0.BS, () => true); + parser.setExecuteHandler(C0.HT, () => true); + parser.setExecuteHandler(C0.SO, () => true); + parser.setExecuteHandler(C0.SI, () => true); + parser.setExecuteHandler(C1.IND, () => true); + parser.setExecuteHandler(C1.NEL, () => true); + parser.setExecuteHandler(C1.HTS, () => true); + parser.registerOscHandler(0, new OscHandler(data => true)); + parser.registerOscHandler(1, new FastOscHandler()); + parser.registerEscHandler({final: '7'}, () => true); + parser.registerEscHandler({final: '8'}, () => true); + parser.registerEscHandler({final: 'D'}, () => true); + parser.registerEscHandler({final: 'E'}, () => true); + parser.registerEscHandler({final: 'H'}, () => true); + parser.registerEscHandler({final: 'M'}, () => true); + parser.registerEscHandler({final: '='}, () => true); + parser.registerEscHandler({final: '>'}, () => true); + parser.registerEscHandler({final: 'c'}, () => true); + parser.registerEscHandler({final: 'n'}, () => true); + parser.registerEscHandler({final: 'o'}, () => true); + parser.registerEscHandler({final: '|'}, () => true); + parser.registerEscHandler({final: '}'}, () => true); + parser.registerEscHandler({final: '~'}, () => true); + parser.registerEscHandler({intermediates: '%', final: '@'}, () => true); + parser.registerEscHandler({intermediates: '%', final: 'G'}, () => true); + parser.registerDcsHandler({final: 'p'}, new DcsHandler(data => true)); + parser.registerDcsHandler({final: 'q'}, new FastDcsHandler()); }); perfContext('PRINT - a', () => { before(() => { const data = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -120,7 +129,7 @@ perfContext('Parser throughput - 50MB data', () => { before(() => { const data = '\n\n\n\n\n\n\n'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -135,7 +144,7 @@ perfContext('Parser throughput - 50MB data', () => { before(() => { const data = '\x1bE\x1bE\x1bE\x1bE\x1bE\x1bE\x1bE\x1bE\x1bE\x1bE'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -150,7 +159,7 @@ perfContext('Parser throughput - 50MB data', () => { before(() => { const data = '\x1b%G\x1b%G\x1b%G\x1b%G\x1b%G\x1b%G\x1b%G\x1b%G\x1b%G\x1b%G'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -165,7 +174,7 @@ perfContext('Parser throughput - 50MB data', () => { before(() => { const data = '\x1b[A\x1b[A\x1b[A\x1b[A\x1b[A\x1b[A\x1b[A\x1b[A\x1b[A\x1b[A'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -180,7 +189,7 @@ perfContext('Parser throughput - 50MB data', () => { before(() => { const data = '\x1b[?p\x1b[?p\x1b[?p\x1b[?p\x1b[?p\x1b[?p\x1b[?p\x1b[?p\x1b[?p\x1b[?p'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -195,7 +204,7 @@ perfContext('Parser throughput - 50MB data', () => { before(() => { const data = '\x1b[1;2m\x1b[1;2m\x1b[1;2m\x1b[1;2m\x1b[1;2m\x1b[1;2m\x1b[1;2m\x1b[1;2m\x1b[1;2m\x1b[1;2m'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -210,7 +219,7 @@ perfContext('Parser throughput - 50MB data', () => { before(() => { const data = '\x1b[1;2;3;4;5;6;7;8;9;0m\x1b[1;2;3;4;5;6;7;8;9;0m\x1b[1;2;3;4;5;6;7;8;9;0m'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -221,11 +230,11 @@ perfContext('Parser throughput - 50MB data', () => { }, {fork: true}).showAverageThroughput(); }); - perfContext('OSC (short) - OSC 0;hi ST', () => { + perfContext('OSC string interface (short seq) - OSC 0;hi ST', () => { before(() => { const data = '\x1b]0;hi\x1b\\\x1b]0;hi\x1b\\\x1b]0;hi\x1b\\\x1b]0;hi\x1b\\x1b]0;hi\x1b\\'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -236,11 +245,11 @@ perfContext('Parser throughput - 50MB data', () => { }, {fork: true}).showAverageThroughput(); }); - perfContext('OSC (long) - OSC 0; ST', () => { + perfContext('OSC string interface (long seq) - OSC 0; ST', () => { before(() => { const data = '\x1b]0;Lorem ipsum dolor sit amet, consetetur sadipscing elitr.\x1b\\'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -251,11 +260,41 @@ perfContext('Parser throughput - 50MB data', () => { }, {fork: true}).showAverageThroughput(); }); - perfContext('DCS (short)', () => { + perfContext('OSC class interface (short seq) - OSC 0;hi ST', () => { before(() => { - const data = '\x1bPq~~\x1b\\'; + const data = '\x1b]1;hi\x1b\\\x1b]1;hi\x1b\\\x1b]1;hi\x1b\\\x1b]1;hi\x1b\\x1b]1;hi\x1b\\'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { + content += data; + } + parsed = toUtf32(content); + }); + new ThroughputRuntimeCase('', () => { + parser.parse(parsed, parsed.length); + return {payloadSize: parsed.length}; + }, {fork: true}).showAverageThroughput(); + }); + + perfContext('OSC class interface (long seq) - OSC 0; ST', () => { + before(() => { + const data = '\x1b]1;Lorem ipsum dolor sit amet, consetetur sadipscing elitr.\x1b\\'; + let content = ''; + while (content.length < SIZE) { + content += data; + } + parsed = toUtf32(content); + }); + new ThroughputRuntimeCase('', () => { + parser.parse(parsed, parsed.length); + return {payloadSize: parsed.length}; + }, {fork: true}).showAverageThroughput(); + }); + + perfContext('DCS string interface (short seq)', () => { + before(() => { + const data = '\x1bPphi\x1b\\\x1bPphi\x1b\\\x1bPphi\x1b\\\x1bPphi\x1b\\\x1bPphi\x1b\\'; + let content = ''; + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); @@ -266,11 +305,41 @@ perfContext('Parser throughput - 50MB data', () => { }, {fork: true}).showAverageThroughput(); }); - perfContext('DCS (long)', () => { + perfContext('DCS string interface (long seq)', () => { before(() => { - const data = '\x1bPq#0;2;0;0;0#1;2;100;100;0#2;2;0;100;0#1~~@@vv@@~~@@~~$#2??}}GG}}??}}??-#1!14@\x1b\\'; + const data = '\x1bPpLorem ipsum dolor sit amet, consetetur sadipscing elitr.\x1b\\'; let content = ''; - while (content.length < 50000000) { + while (content.length < SIZE) { + content += data; + } + parsed = toUtf32(content); + }); + new ThroughputRuntimeCase('', async () => { + parser.parse(parsed, parsed.length); + return {payloadSize: parsed.length}; + }, {fork: true}).showAverageThroughput(); + }); + + perfContext('DCS class interface (short seq)', () => { + before(() => { + const data = '\x1bPqhi\x1b\\\x1bPqhi\x1b\\\x1bPqhi\x1b\\\x1bPqhi\x1b\\\x1bPqhi\x1b\\'; + let content = ''; + while (content.length < SIZE) { + content += data; + } + parsed = toUtf32(content); + }); + new ThroughputRuntimeCase('', async () => { + parser.parse(parsed, parsed.length); + return {payloadSize: parsed.length}; + }, {fork: true}).showAverageThroughput(); + }); + + perfContext('DCS class interface (long seq)', () => { + before(() => { + const data = '\x1bPqLorem ipsum dolor sit amet, consetetur sadipscing elitr.\x1b\\'; + let content = ''; + while (content.length < SIZE) { content += data; } parsed = toUtf32(content); diff --git a/test/benchmark/Terminal.benchmark.ts b/test/benchmark/Terminal.benchmark.ts index 76139cb6..40a3c208 100644 --- a/test/benchmark/Terminal.benchmark.ts +++ b/test/benchmark/Terminal.benchmark.ts @@ -29,7 +29,7 @@ perfContext('Terminal: ls -lR /usr/lib', () => { chunks.push(data as unknown as Buffer); length += data.length; }); - await new Promise(resolve => p.on('exit', () => resolve())); + await new Promise(resolve => p.on('exit', () => resolve())); contentUtf8 = Buffer.concat(chunks, length); // translate to content string const buffer = new Uint32Array(contentUtf8.length); @@ -44,24 +44,24 @@ perfContext('Terminal: ls -lR /usr/lib', () => { } }); - perfContext('write', () => { + perfContext('write/string/async', () => { let terminal: Terminal; before(() => { terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000}); }); - new ThroughputRuntimeCase('', () => { - terminal.writeSync(content); + new ThroughputRuntimeCase('', async () => { + await new Promise(res => terminal.write(content, res)); return {payloadSize: contentUtf8.length}; }, {fork: false}).showAverageThroughput(); }); - perfContext('writeUtf8', () => { + perfContext('write/Utf8/async', () => { let terminal: Terminal; before(() => { terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000}); }); - new ThroughputRuntimeCase('', () => { - terminal.writeSync(content); + new ThroughputRuntimeCase('', async () => { + await new Promise(res => terminal.write(content, res)); return {payloadSize: contentUtf8.length}; }, {fork: false}).showAverageThroughput(); }); diff --git a/typings/xterm.d.ts b/typings/xterm.d.ts index d860ddfa..cab9bdcc 100644 --- a/typings/xterm.d.ts +++ b/typings/xterm.d.ts @@ -1501,6 +1501,23 @@ declare module 'xterm' { /** * Allows hooking into the parser for custom handling of escape sequences. + * + * Note on sync vs. async handlers: + * xterm.js implements all parser actions with synchronous handlers. + * In general custom handlers should also operate in sync mode wherever + * possible to keep the parser fast. + * Still the exposed interfaces allow to register async handlers by returning + * a `Promise`. Here the parser will pause input processing until + * the promise got resolved or rejected (in-band blocking). This "full stop" + * on the input chain allows to implement backpressure from a certain async + * action while the terminal state will not progress any further from input. + * It does not mean that the terminal state will not change at all in between, + * as user actions like resize or reset are still processed immediately. + * It is an error to assume a stable terminal state while giving back control + * in between, e.g. by multiple chained `then` calls. + * Downside of an async handler is a rather bad throughput performance, + * thus use async handlers only as a last resort or for actions that have + * to rely on async interfaces itself. */ export interface IParser { /** @@ -1510,12 +1527,11 @@ declare module 'xterm' { * @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 `true` if the sequence was handled, `false` if the parser should try + * a previous handler. The most recently added handler is tried first. * @return An IDisposable you can call to remove this handler. */ - registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable; + registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise): IDisposable; /** * Adds a handler for DCS escape sequences. @@ -1529,12 +1545,11 @@ declare module 'xterm' { * 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 `true` if the sequence was handled, `false` if the parser should try + * a previous handler. The most recently added handler is tried first. * @return An IDisposable you can call to remove this handler. */ - registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable; + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise): IDisposable; /** * Adds a handler for ESC escape sequences. @@ -1542,12 +1557,11 @@ declare module 'xterm' { * 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 `true` if the sequence was handled, `false` if the parser should try + * a previous handler. The most recently added handler is tried first. * @return An IDisposable you can call to remove this handler. */ - registerEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable; + registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise): IDisposable; /** * Adds a handler for OSC escape sequences. @@ -1560,12 +1574,11 @@ declare module 'xterm' { * 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 `true` if the sequence was handled, `false` if the parser should try + * a previous handler. The most recently added handler is tried first. * @return An IDisposable you can call to remove this handler. */ - registerOscHandler(ident: number, callback: (data: string) => boolean): IDisposable; + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable; } /** diff --git a/yarn.lock b/yarn.lock index 8d8c9dd3..9b49f8db 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4820,9 +4820,9 @@ xterm-benchmark@^0.1.3: typescript "^3.5.1" y18n@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b" - integrity sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w== + version "4.0.1" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.1.tgz#8db2b83c31c5d75099bb890b23f3094891e247d4" + integrity sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ== yargs-parser@13.1.2, yargs-parser@^13.1.2: version "13.1.2"