From edee1a106788e839651c1bc12269bd375d695d0d Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Sun, 13 Sep 2020 21:33:32 +0800 Subject: [PATCH 01/89] Handle alt screen --- .../src/SerializeAddon.ts | 28 +++++++++++++--- .../test/SerializeAddon.api.ts | 32 +++++++++++++++++++ 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index dad6aa4f..ba366c37 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -11,6 +11,11 @@ function constrain(value: number, low: number, high: number): number { return Math.max(low, Math.min(value, high)); } +interface ISerializeOptions { + withAlternate?: boolean; + +} + // TODO: Refine this template class later abstract class BaseSerializeHandler { constructor(private _buffer: IBuffer) { } @@ -167,7 +172,7 @@ export class SerializeAddon implements ITerminalAddon { this._terminal = terminal; } - public serialize(rows?: number): string { + public serialize(rows?: number, options: ISerializeOptions = {}): string { // TODO: Add re-position cursor support // TODO: Add word wrap mode support // TODO: Add combinedData support @@ -175,12 +180,25 @@ export class SerializeAddon implements ITerminalAddon { 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' || !(options?.withAlternate ?? false)) { + const maxRows = this._terminal.buffer.active.length; + const handler = new StringSerializeHandler(this._terminal.buffer.active); - rows = (rows === undefined) ? maxRows : constrain(rows, 0, maxRows); + rows = (rows === undefined) ? maxRows : constrain(rows, 0, maxRows); - return handler.serialize(maxRows - rows, maxRows); + return handler.serialize(maxRows - rows, maxRows); + } + + const maxNormalRows = this._terminal.buffer.normal.length; + const maxAltRows = this._terminal.buffer.alternate.length; + const normalHandler = new StringSerializeHandler(this._terminal.buffer.normal); + const altHandler = new StringSerializeHandler(this._terminal.buffer.alternate); + const normalRows = (rows === undefined) ? maxNormalRows : constrain(rows, 0, maxNormalRows); + const altRows = (rows === undefined) ? maxAltRows : constrain(rows, 0, maxAltRows); + + return normalHandler.serialize(maxNormalRows - normalRows, maxNormalRows) + + '\u001b[?1049h\u001b[H' + + altHandler.serialize(maxAltRows - altRows, maxAltRows); } 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..32e816a1 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -299,6 +299,38 @@ 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(JSON.stringify(await page.evaluate(`window.term.buffer.active.type`)), '"alternate"'); + assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true });`)), 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(JSON.stringify(await page.evaluate(`window.term.buffer.active === window.term.buffer.alt`)), 'false'); + assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true });`)), JSON.stringify(expected.join('\r\n'))); + }); }); function newArray(initial: T | ((index: number) => T), count: number): T[] { From 881a4a0dbb838231d9ed44450e539bd426d44417 Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Tue, 15 Sep 2020 17:58:56 +0800 Subject: [PATCH 02/89] Try implement cursor restortion --- .../src/SerializeAddon.ts | 110 ++++++++++++++---- demo/client.ts | 2 +- 2 files changed, 89 insertions(+), 23 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index ba366c37..e03707e0 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -13,7 +13,7 @@ function constrain(value: number, low: number, high: number): number { interface ISerializeOptions { withAlternate?: boolean; - + withCursor?: boolean; } // TODO: Refine this template class later @@ -26,7 +26,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); @@ -51,7 +51,7 @@ 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 _beforeSerialize(rows: number, startRow: number, endRow: number): void { } protected _afterSerialize(): void { } protected _serializeString(): string { return ''; } } @@ -82,12 +82,16 @@ class StringSerializeHandler extends BaseSerializeHandler { private _currentRow: string = ''; private _nullCellCount: number = 0; - constructor(buffer: IBuffer) { - super(buffer); + private _lastContentCellRow: number = 0; + private _lastContentCellCol: number = 0; + + constructor(private _buffer1: IBuffer,private _terminal: Terminal, private _option: ISerializeOptions = {}) { + super(_buffer1); } - protected _beforeSerialize(rows: number): void { + protected _beforeSerialize(rows: number, start: number, end: number): void { this._allRows = new Array(rows); + this._lastContentCellRow = start; } protected _rowEnd(row: number): void { @@ -147,6 +151,9 @@ class StringSerializeHandler extends BaseSerializeHandler { } else if (this._nullCellCount > 0) { this._currentRow += `\x1b[${this._nullCellCount}C`; this._nullCellCount = 0; + } else { + this._lastContentCellRow = row; + this._lastContentCellCol = col + cell.getWidth(); } this._currentRow += cell.getChars(); @@ -154,12 +161,71 @@ class StringSerializeHandler extends BaseSerializeHandler { protected _serializeString(): string { let rowEnd = this._allRows.length; + for (; rowEnd > 0; rowEnd--) { if (this._allRows[rowEnd - 1]) { break; } } - return this._allRows.slice(0, rowEnd).join('\r\n'); + + let content = this._allRows.slice(0, rowEnd).join('\r\n'); + + if (this._option.withCursor) { + const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY; + const realCursorCol = this._buffer1.cursorX; + + const hasScroll = this._buffer1.length > this._terminal.rows!; + const hasEmptyLine = hasScroll ? (this._buffer1.length - 1 > this._lastContentCellRow) : (realCursorRow > this._lastContentCellRow); + const cursorMoved = + hasScroll + ? hasEmptyLine + ? (realCursorCol !== 0 || realCursorRow !== this._buffer1.length - 1) + : (realCursorRow !== this._lastContentCellRow || realCursorCol !== this._lastContentCellCol) + : hasEmptyLine + // we don't need to check the row because empty row count are based on cursor + ? realCursorCol !== 0 + : (realCursorRow !== this._lastContentCellRow || realCursorCol !== this._lastContentCellCol); + + 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`; + } + }; + + // Fix empty lines + if (hasEmptyLine) { + if (hasScroll) { + content += '\r\n'.repeat(this._buffer1.length - 1 - this._lastContentCellRow); + } else { + content += '\r\n'.repeat(realCursorRow - this._lastContentCellRow); + } + } + + if (cursorMoved) { + if (hasEmptyLine) { + if (hasScroll) { + moveRight(realCursorCol); + moveDown(realCursorRow - (this._buffer1.length - 1)); + } else { + moveRight(realCursorCol); + } + } else { + moveDown(realCursorRow - this._lastContentCellRow); + moveRight(realCursorCol - this._lastContentCellCol); + } + } + } + + return content; } } @@ -172,6 +238,15 @@ export class SerializeAddon implements ITerminalAddon { this._terminal = terminal; } + private _getString(buffer: IBuffer, rows?: number, option?: ISerializeOptions): string { + const maxRows = buffer.length; + const handler = new StringSerializeHandler(buffer, this._terminal!, option); + const correctRows = (rows === undefined) ? maxRows : constrain(rows, 0, maxRows); + const result = handler.serialize(maxRows - correctRows, maxRows); + + return result; + } + public serialize(rows?: number, options: ISerializeOptions = {}): string { // TODO: Add re-position cursor support // TODO: Add word wrap mode support @@ -180,25 +255,16 @@ export class SerializeAddon implements ITerminalAddon { throw new Error('Cannot use addon until it has been loaded'); } - if (this._terminal.buffer.active.type === 'normal' || !(options?.withAlternate ?? false)) { - const maxRows = this._terminal.buffer.active.length; - const handler = new StringSerializeHandler(this._terminal.buffer.active); - - rows = (rows === undefined) ? maxRows : constrain(rows, 0, maxRows); - - return handler.serialize(maxRows - rows, maxRows); + if (this._terminal.buffer.active.type === 'normal' || !(options.withAlternate ?? false)) { + return this._getString(this._terminal.buffer.active, rows, options); } - const maxNormalRows = this._terminal.buffer.normal.length; - const maxAltRows = this._terminal.buffer.alternate.length; - const normalHandler = new StringSerializeHandler(this._terminal.buffer.normal); - const altHandler = new StringSerializeHandler(this._terminal.buffer.alternate); - const normalRows = (rows === undefined) ? maxNormalRows : constrain(rows, 0, maxNormalRows); - const altRows = (rows === undefined) ? maxAltRows : constrain(rows, 0, maxAltRows); + const normalScreenContent = this._getString(this._terminal.buffer.normal, rows, options); + const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, rows, options); - return normalHandler.serialize(maxNormalRows - normalRows, maxNormalRows) + return normalScreenContent + '\u001b[?1049h\u001b[H' - + altHandler.serialize(maxAltRows - altRows, maxAltRows); + + alternativeScreenContent; } public dispose(): void { } diff --git a/demo/client.ts b/demo/client.ts index 6efa181a..509b73a9 100644 --- a/demo/client.ts +++ b/demo/client.ts @@ -413,7 +413,7 @@ function updateTerminalSize(): void { } function serializeButtonHandler(): void { - const output = addons.serialize.instance.serialize(); + const output = addons.serialize.instance.serialize(undefined, { withAlternate: true, withCursor: true }); const outputString = JSON.stringify(output); document.getElementById('serialize-output').innerText = outputString; From 00a8b80ef729c9ed89a44288425c592601be8df1 Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Wed, 16 Sep 2020 14:28:08 +0800 Subject: [PATCH 03/89] Implement cursor adn alt screen. Fix background serialize --- .../src/SerializeAddon.ts | 168 +++++++++++++++--- .../test/SerializeAddon.api.ts | 18 ++ 2 files changed, 161 insertions(+), 25 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index e03707e0..3113777e 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -82,8 +82,16 @@ class StringSerializeHandler extends BaseSerializeHandler { private _currentRow: string = ''; private _nullCellCount: number = 0; - private _lastContentCellRow: number = 0; - private _lastContentCellCol: number = 0; + // this is a null cell for reference for checking whether background is empty or not + private _nullCell: IBufferCell = this._buffer1.getNullCell(); + + // 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(); + + private _lastCursorRow: number = 0; + private _lastCursorCol: number = 0; constructor(private _buffer1: IBuffer,private _terminal: Terminal, private _option: ISerializeOptions = {}) { super(_buffer1); @@ -91,16 +99,35 @@ class StringSerializeHandler extends BaseSerializeHandler { protected _beforeSerialize(rows: number, start: number, end: number): void { this._allRows = new Array(rows); - this._lastContentCellRow = start; + this._lastCursorRow = start; } protected _rowEnd(row: number): 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._nullCell)) { + // use clear right to set background. + // use move right to move cursor. + this._currentRow += `\x1b[${this._nullCellCount}X`; + + // set the cursor back because we aren't there + this._lastCursorRow = row; + this._lastCursorCol = this._terminal.cols - this._nullCellCount; + + this._nullCellCount = 0; + + // perform a style reset before next line, + // because scroll when having background set will change the whole background of next line. + this._currentRow += `\x1b[m`; + // FIXME: we just get a new one because we can't reset it. + this._cursorStyle = this._buffer1.getNullCell(); + } + this._allRows[this._rowIndex++] = this._currentRow; 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); @@ -108,7 +135,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(); @@ -140,23 +169,76 @@ 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() === ''; + + // this cell don't have content and style + const isNullCell = cell.getWidth() === 1 && cell.getChars() === '' && cell.isAttributeDefault(); + + 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. + // use move right to move cursor. + if (equalBg(this._cursorStyle, this._nullCell)) { + this._currentRow += `\x1b[${this._nullCellCount}C`; + } else { + this._currentRow += `\x1b[${this._nullCellCount}X`; + this._currentRow += `\x1b[${this._nullCellCount}C`; + } + this._nullCellCount = 0; + } + this._currentRow += `\x1b[${sgrSeq.join(';')}m`; + + // update the last cursor style + this._buffer1.getLine(row)?.getCell(col, this._cursorStyle); } - // 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 { - this._lastContentCellRow = row; - this._lastContentCellCol = col + cell.getWidth(); + 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._nullCell)) { + 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(); + if (!isNullCell) { + this._lastCursorRow = row; + this._lastCursorCol = col + cell.getWidth(); + } } protected _serializeString(): string { @@ -170,21 +252,21 @@ class StringSerializeHandler extends BaseSerializeHandler { let content = this._allRows.slice(0, rowEnd).join('\r\n'); - if (this._option.withCursor) { + if (this._option.withCursor ?? true) { const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY; const realCursorCol = this._buffer1.cursorX; const hasScroll = this._buffer1.length > this._terminal.rows!; - const hasEmptyLine = hasScroll ? (this._buffer1.length - 1 > this._lastContentCellRow) : (realCursorRow > this._lastContentCellRow); + const hasEmptyLine = hasScroll ? (this._buffer1.length - 1 > this._lastCursorRow) : (realCursorRow > this._lastCursorRow); const cursorMoved = hasScroll ? hasEmptyLine ? (realCursorCol !== 0 || realCursorRow !== this._buffer1.length - 1) - : (realCursorRow !== this._lastContentCellRow || realCursorCol !== this._lastContentCellCol) + : (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol) : hasEmptyLine // we don't need to check the row because empty row count are based on cursor ? realCursorCol !== 0 - : (realCursorRow !== this._lastContentCellRow || realCursorCol !== this._lastContentCellCol); + : (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol); const moveRight = (offset: number): void => { if (offset > 0) { @@ -204,9 +286,9 @@ class StringSerializeHandler extends BaseSerializeHandler { // Fix empty lines if (hasEmptyLine) { if (hasScroll) { - content += '\r\n'.repeat(this._buffer1.length - 1 - this._lastContentCellRow); + content += '\r\n'.repeat(this._buffer1.length - 1 - this._lastCursorRow); } else { - content += '\r\n'.repeat(realCursorRow - this._lastContentCellRow); + content += '\r\n'.repeat(realCursorRow - this._lastCursorRow); } } @@ -219,8 +301,8 @@ class StringSerializeHandler extends BaseSerializeHandler { moveRight(realCursorCol); } } else { - moveDown(realCursorRow - this._lastContentCellRow); - moveRight(realCursorCol - this._lastContentCellCol); + moveDown(realCursorRow - this._lastCursorRow); + moveRight(realCursorCol - this._lastCursorCol); } } } @@ -247,15 +329,51 @@ export class SerializeAddon implements ITerminalAddon { return result; } + public inspectBuffer(buffer: IBuffer): { x: number, y: number, data: any[][] } { + const lines: any[] = []; + const cell = buffer.getNullCell(); + + for (let i = 0; i < buffer.length; i++) { + const line = []; + const bufferLine = buffer.getLine(i)!; + for (let j = 0; j < bufferLine.length; j++) { + const cellData: any = {}; + bufferLine.getCell(j, cell)!; + cellData.getBgColor = cell.getBgColor(); + cellData.getBgColorMode = cell.getBgColorMode(); + cellData.getChars = cell.getChars(); + cellData.getCode = cell.getCode(); + cellData.getFgColor = cell.getFgColor(); + cellData.getFgColorMode = cell.getFgColorMode(); + cellData.getWidth = cell.getWidth(); + cellData.isAttributeDefault = cell.isAttributeDefault(); + cellData.isBlink = cell.isBlink(); + cellData.isBold = cell.isBold(); + cellData.isDim = cell.isDim(); + cellData.isInverse = cell.isInverse(); + cellData.isInvisible = cell.isInvisible(); + + line.push(cellData); + } + + lines.push(line); + } + + return { + x: buffer.cursorX, + y: buffer.cursorY, + data: lines + }; + } + public serialize(rows?: number, options: ISerializeOptions = {}): string { - // TODO: Add re-position cursor support // TODO: Add word wrap mode support // TODO: Add combinedData support if (!this._terminal) { throw new Error('Cannot use addon until it has been loaded'); } - if (this._terminal.buffer.active.type === 'normal' || !(options.withAlternate ?? false)) { + if (this._terminal.buffer.active.type === 'normal' || !(options.withAlternate ?? true)) { return this._getString(this._terminal.buffer.active, rows, options); } diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 32e816a1..a63e386b 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -331,6 +331,24 @@ describe('SerializeAddon', () => { assert.equal(JSON.stringify(await page.evaluate(`window.term.buffer.active === window.term.buffer.alt`)), 'false'); assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true });`)), 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 writeSync(page, lines.join('\\r\\n')); + const originalBuffer = await page.evaluate(`serializeAddon.inspectBuffer(term.buffer.normal);`); + const result = await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true, withCursor: true });`); + + await writeSync(page, '\' +' + JSON.stringify('\x1bc' + result) + '+ \''); + const newBuffer = await page.evaluate(`serializeAddon.inspectBuffer(term.buffer.normal);`); + + assert.deepEqual(originalBuffer, newBuffer); + }); }); function newArray(initial: T | ((index: number) => T), count: number): T[] { From 8518b354a71c6ef3fb1b2e7c5fed51ff04be401a Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Wed, 16 Sep 2020 14:45:14 +0800 Subject: [PATCH 04/89] Fix test that breaks by the option change --- .../src/SerializeAddon.ts | 14 ++++++++------ .../test/SerializeAddon.api.ts | 19 ++++++++++--------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 3113777e..2363e326 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -320,10 +320,11 @@ export class SerializeAddon implements ITerminalAddon { this._terminal = terminal; } - private _getString(buffer: IBuffer, rows?: number, option?: ISerializeOptions): string { + private _getString(buffer: IBuffer, scrollback?: number, option?: ISerializeOptions): string { const maxRows = buffer.length; const handler = new StringSerializeHandler(buffer, this._terminal!, option); - const correctRows = (rows === undefined) ? maxRows : constrain(rows, 0, maxRows); + + const correctRows = (scrollback === undefined) ? maxRows : constrain(scrollback + this!._terminal!.rows, 0, maxRows); const result = handler.serialize(maxRows - correctRows, maxRows); return result; @@ -366,7 +367,7 @@ export class SerializeAddon implements ITerminalAddon { }; } - public serialize(rows?: number, options: ISerializeOptions = {}): string { + public serialize(scrollback?: number, options: ISerializeOptions = {}): string { // TODO: Add word wrap mode support // TODO: Add combinedData support if (!this._terminal) { @@ -374,11 +375,12 @@ export class SerializeAddon implements ITerminalAddon { } if (this._terminal.buffer.active.type === 'normal' || !(options.withAlternate ?? true)) { - return this._getString(this._terminal.buffer.active, rows, options); + return this._getString(this._terminal.buffer.active, scrollback, options); } - const normalScreenContent = this._getString(this._terminal.buffer.normal, rows, options); - const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, rows, options); + const normalScreenContent = this._getString(this._terminal.buffer.normal, scrollback, options); + // alt screen don't have scrollback + const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, undefined, options); return normalScreenContent + '\u001b[?1049h\u001b[H' diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index a63e386b..0401953d 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -39,7 +39,7 @@ describe('SerializeAddon', () => { assert.equal(await page.evaluate(`serializeAddon.serialize();`), ''); }); - it('trim last empty lines', async function(): Promise { + it('preserve last empty lines', async function(): Promise { const cols = 10; const lines = [ '', @@ -55,7 +55,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 +67,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 { From 10282e4cb1d0d1d0a26cefa679afeb0cda82479e Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Wed, 16 Sep 2020 14:54:15 +0800 Subject: [PATCH 05/89] Move the test util to static method --- .../src/SerializeAddon.ts | 43 ++++++++++--------- .../test/SerializeAddon.api.ts | 5 ++- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 2363e326..32cab90c 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -330,7 +330,28 @@ export class SerializeAddon implements ITerminalAddon { return result; } - public inspectBuffer(buffer: IBuffer): { x: number, y: number, data: any[][] } { + public serialize(scrollback?: number, options: ISerializeOptions = {}): string { + // TODO: Add word wrap mode support + // TODO: Add combinedData support + if (!this._terminal) { + throw new Error('Cannot use addon until it has been loaded'); + } + + if (this._terminal.buffer.active.type === 'normal' || !(options.withAlternate ?? true)) { + return this._getString(this._terminal.buffer.active, scrollback, options); + } + + const normalScreenContent = this._getString(this._terminal.buffer.normal, scrollback, options); + // alt screen don't have scrollback + const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, undefined, options); + + return normalScreenContent + + '\u001b[?1049h\u001b[H' + + alternativeScreenContent; + } + + // this is a util used only for test + private static _inspectBuffer(buffer: IBuffer): { x: number, y: number, data: any[][] } { const lines: any[] = []; const cell = buffer.getNullCell(); @@ -367,25 +388,5 @@ export class SerializeAddon implements ITerminalAddon { }; } - public serialize(scrollback?: number, options: ISerializeOptions = {}): string { - // TODO: Add word wrap mode support - // TODO: Add combinedData support - if (!this._terminal) { - throw new Error('Cannot use addon until it has been loaded'); - } - - if (this._terminal.buffer.active.type === 'normal' || !(options.withAlternate ?? true)) { - return this._getString(this._terminal.buffer.active, scrollback, options); - } - - const normalScreenContent = this._getString(this._terminal.buffer.normal, scrollback, options); - // alt screen don't have scrollback - const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, undefined, options); - - 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 0401953d..281a3154 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -342,11 +342,12 @@ describe('SerializeAddon', () => { ]; await writeSync(page, lines.join('\\r\\n')); - const originalBuffer = await page.evaluate(`serializeAddon.inspectBuffer(term.buffer.normal);`); + const originalBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const result = await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true, withCursor: true });`); await writeSync(page, '\' +' + JSON.stringify('\x1bc' + result) + '+ \''); - const newBuffer = await page.evaluate(`serializeAddon.inspectBuffer(term.buffer.normal);`); + const newBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); assert.deepEqual(originalBuffer, newBuffer); }); From 6c0163009051652ac8348ddcc03067e8da713d86 Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Wed, 16 Sep 2020 15:13:30 +0800 Subject: [PATCH 06/89] Remove the unused options --- .../src/SerializeAddon.ts | 117 +++++++++--------- .../test/SerializeAddon.api.ts | 6 +- demo/client.ts | 2 +- 3 files changed, 60 insertions(+), 65 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 32cab90c..f4dcf35b 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -11,11 +11,6 @@ function constrain(value: number, low: number, high: number): number { return Math.max(low, Math.min(value, high)); } -interface ISerializeOptions { - withAlternate?: boolean; - withCursor?: boolean; -} - // TODO: Refine this template class later abstract class BaseSerializeHandler { constructor(private _buffer: IBuffer) { } @@ -93,7 +88,7 @@ class StringSerializeHandler extends BaseSerializeHandler { private _lastCursorRow: number = 0; private _lastCursorCol: number = 0; - constructor(private _buffer1: IBuffer,private _terminal: Terminal, private _option: ISerializeOptions = {}) { + constructor(private _buffer1: IBuffer,private _terminal: Terminal) { super(_buffer1); } @@ -252,61 +247,61 @@ class StringSerializeHandler extends BaseSerializeHandler { let content = this._allRows.slice(0, rowEnd).join('\r\n'); - if (this._option.withCursor ?? true) { - const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY; - const realCursorCol = this._buffer1.cursorX; + // restore the cursor + const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY; + const realCursorCol = this._buffer1.cursorX; - const hasScroll = this._buffer1.length > this._terminal.rows!; - const hasEmptyLine = hasScroll ? (this._buffer1.length - 1 > this._lastCursorRow) : (realCursorRow > this._lastCursorRow); - const cursorMoved = - hasScroll - ? hasEmptyLine - ? (realCursorCol !== 0 || realCursorRow !== this._buffer1.length - 1) - : (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol) - : hasEmptyLine - // we don't need to check the row because empty row count are based on cursor - ? realCursorCol !== 0 - : (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol); + const hasScroll = this._buffer1.length > this._terminal.rows!; + const hasEmptyLine = hasScroll ? (this._buffer1.length - 1 > this._lastCursorRow) : (realCursorRow > this._lastCursorRow); + const cursorMoved = + hasScroll + ? hasEmptyLine + ? (realCursorCol !== 0 || realCursorRow !== this._buffer1.length - 1) + : (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol) + : hasEmptyLine + // we don't need to check the row because empty row count are based on cursor + ? realCursorCol !== 0 + : (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`; - } - }; - - // Fix empty lines - if (hasEmptyLine) { - if (hasScroll) { - content += '\r\n'.repeat(this._buffer1.length - 1 - this._lastCursorRow); - } else { - content += '\r\n'.repeat(realCursorRow - this._lastCursorRow); - } + 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) { - if (hasEmptyLine) { - if (hasScroll) { - moveRight(realCursorCol); - moveDown(realCursorRow - (this._buffer1.length - 1)); - } else { - moveRight(realCursorCol); - } - } else { - moveDown(realCursorRow - this._lastCursorRow); - moveRight(realCursorCol - this._lastCursorCol); - } + // Fix empty lines + if (hasEmptyLine) { + if (hasScroll) { + content += '\r\n'.repeat(this._buffer1.length - 1 - this._lastCursorRow); + } else { + content += '\r\n'.repeat(realCursorRow - this._lastCursorRow); } } + if (cursorMoved) { + if (hasEmptyLine) { + if (hasScroll) { + moveRight(realCursorCol); + moveDown(realCursorRow - (this._buffer1.length - 1)); + } else { + moveRight(realCursorCol); + } + } else { + moveDown(realCursorRow - this._lastCursorRow); + moveRight(realCursorCol - this._lastCursorCol); + } + } + + return content; } } @@ -320,9 +315,9 @@ export class SerializeAddon implements ITerminalAddon { this._terminal = terminal; } - private _getString(buffer: IBuffer, scrollback?: number, option?: ISerializeOptions): string { + private _getString(buffer: IBuffer, scrollback?: number): string { const maxRows = buffer.length; - const handler = new StringSerializeHandler(buffer, this._terminal!, option); + 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); @@ -330,20 +325,20 @@ export class SerializeAddon implements ITerminalAddon { return result; } - public serialize(scrollback?: number, options: ISerializeOptions = {}): string { + public serialize(scrollback?: number): string { // TODO: Add word wrap mode support // TODO: Add combinedData support if (!this._terminal) { throw new Error('Cannot use addon until it has been loaded'); } - if (this._terminal.buffer.active.type === 'normal' || !(options.withAlternate ?? true)) { - return this._getString(this._terminal.buffer.active, scrollback, options); + if (this._terminal.buffer.active.type === 'normal') { + return this._getString(this._terminal.buffer.active, scrollback); } - const normalScreenContent = this._getString(this._terminal.buffer.normal, scrollback, options); + const normalScreenContent = this._getString(this._terminal.buffer.normal, scrollback); // alt screen don't have scrollback - const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, undefined, options); + const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, undefined); return normalScreenContent + '\u001b[?1049h\u001b[H' diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 281a3154..2e570120 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -314,7 +314,7 @@ describe('SerializeAddon', () => { await writeSync(page, lines.join('\\r\\n')); assert.equal(JSON.stringify(await page.evaluate(`window.term.buffer.active.type`)), '"alternate"'); - assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true });`)), JSON.stringify(expected.join('\r\n'))); + assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize();`)), JSON.stringify(expected.join('\r\n'))); }); it('serialize without alt screen correctly', async () => { @@ -330,7 +330,7 @@ describe('SerializeAddon', () => { await writeSync(page, lines.join('\\r\\n')); assert.equal(JSON.stringify(await page.evaluate(`window.term.buffer.active === window.term.buffer.alt`)), 'false'); - assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true });`)), JSON.stringify(expected.join('\r\n'))); + assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize();`)), JSON.stringify(expected.join('\r\n'))); }); it('serialize with background', async () => { @@ -344,7 +344,7 @@ describe('SerializeAddon', () => { await writeSync(page, lines.join('\\r\\n')); const originalBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); - const result = await page.evaluate(`serializeAddon.serialize(undefined, { withAlternate: true, withCursor: true });`); + const result = await page.evaluate(`serializeAddon.serialize();`); await writeSync(page, '\' +' + JSON.stringify('\x1bc' + result) + '+ \''); const newBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); diff --git a/demo/client.ts b/demo/client.ts index 509b73a9..6efa181a 100644 --- a/demo/client.ts +++ b/demo/client.ts @@ -413,7 +413,7 @@ function updateTerminalSize(): void { } function serializeButtonHandler(): void { - const output = addons.serialize.instance.serialize(undefined, { withAlternate: true, withCursor: true }); + const output = addons.serialize.instance.serialize(); const outputString = JSON.stringify(output); document.getElementById('serialize-output').innerText = outputString; From b89227d365f6e6e6062115c62ec8ba4491f926b3 Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Wed, 16 Sep 2020 22:47:23 +0800 Subject: [PATCH 07/89] Workaround firefox bug that yield -0 on bit op --- .../xterm-addon-serialize/test/SerializeAddon.api.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 2e570120..4d90f3c5 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -14,6 +14,8 @@ let page: Page; const width = 800; const height = 600; +const writeRawSync = (page: any, str: string): Promise => writeSync(page, '\' +' + JSON.stringify(str) + '+ \''); + describe('SerializeAddon', () => { before(async function(): Promise { const browserType = getBrowserType(); @@ -344,12 +346,14 @@ describe('SerializeAddon', () => { await writeSync(page, lines.join('\\r\\n')); const originalBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); - const result = await page.evaluate(`serializeAddon.serialize();`); - - await writeSync(page, '\' +' + JSON.stringify('\x1bc' + result) + '+ \''); + const result = await page.evaluate(`serializeAddon.serialize();`) as string; + await page.evaluate(`term.reset();`); + await writeRawSync(page, result); const newBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); - assert.deepEqual(originalBuffer, newBuffer); + // 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)); }); }); From 6904dc50092d979f47108d1fd89f2bfbf7fcd4e6 Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Fri, 18 Sep 2020 00:36:10 +0800 Subject: [PATCH 08/89] Handle BCE + line scroll Using an additional field for store the current background and compare against it to generate proper color sequence --- .../xterm-addon-serialize/src/MyBufferCell.ts | 96 +++++++++++++++++++ .../src/SerializeAddon.ts | 51 +++++----- .../test/SerializeAddon.api.ts | 27 ++++++ 3 files changed, 148 insertions(+), 26 deletions(-) create mode 100644 addons/xterm-addon-serialize/src/MyBufferCell.ts diff --git a/addons/xterm-addon-serialize/src/MyBufferCell.ts b/addons/xterm-addon-serialize/src/MyBufferCell.ts new file mode 100644 index 00000000..56efcb3c --- /dev/null +++ b/addons/xterm-addon-serialize/src/MyBufferCell.ts @@ -0,0 +1,96 @@ +import { IBufferCell } from 'xterm'; + +/** + * This is a dummy buffer cell to hold data from real buffer cell + */ +export class MyBufferCell implements IBufferCell { + constructor (private _cell: IBufferCell) {} + private _width: number = this._cell.getWidth(); + private _chars: string = this._cell.getChars(); + private _code: number = this._cell.getCode(); + private _fgColorMode: number = this._cell.getFgColorMode(); + private _bgColorMode: number = this._cell.getBgColorMode(); + private _fgColor: number = this._cell.getFgColor(); + private _bgColor: number = this._cell.getBgColor(); + private _bold: number = this._cell.isBold(); + private _italic: number = this._cell.isItalic(); + private _dim: number = this._cell.isDim(); + private _underline: number = this._cell.isUnderline(); + private _blink: number = this._cell.isBlink(); + private _inverse: number = this._cell.isInverse(); + private _invisible: number = this._cell.isInvisible(); + private _fgRGB: boolean = this._cell.isFgRGB(); + private _bgRGB: boolean = this._cell.isBgRGB(); + private _fgPalette: boolean = this._cell.isFgPalette(); + private _bgPallette: boolean = this._cell.isBgPalette(); + private _fgDefault: boolean = this._cell.isFgDefault(); + private _bgDefault: boolean = this._cell.isBgDefault(); + private _attributeDefault: boolean = this._cell.isAttributeDefault(); + public getWidth(): number { + return this._width; + } + public getChars(): string { + return this._chars; + } + public getCode(): number { + return this._code; + } + public getFgColorMode(): number { + return this._fgColorMode; + } + public getBgColorMode(): number { + return this._bgColorMode; + } + public getFgColor(): number { + return this._fgColor; + } + public getBgColor(): number { + return this._bgColor; + } + public isBold(): number { + return this._bold; + } + public isItalic(): number { + return this._italic; + } + public isDim(): number { + return this._dim; + } + public isUnderline(): number { + return this._underline; + } + public isBlink(): number { + return this._blink; + } + public isInverse(): number { + return this._inverse; + } + public isInvisible(): number { + return this._invisible; + } + public isFgRGB(): boolean { + return this._fgRGB; + } + public isBgRGB(): boolean { + return this._bgRGB; + } + public isFgPalette(): boolean { + return this._fgPalette; + } + public isBgPalette(): boolean { + return this._bgPallette; + } + public isFgDefault(): boolean { + return this._fgDefault; + } + public isBgDefault(): boolean { + return this._bgDefault; + } + public isAttributeDefault(): boolean { + return this._attributeDefault; + } + + public static from(cell: IBufferCell): MyBufferCell { + return new MyBufferCell(cell); + } +} diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index f4dcf35b..9518fcbf 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -6,6 +6,7 @@ */ import { Terminal, ITerminalAddon, IBuffer, IBufferCell } from 'xterm'; +import { MyBufferCell } from './MyBufferCell'; function constrain(value: number, low: number, high: number): number { return Math.max(low, Math.min(value, high)); @@ -36,7 +37,7 @@ abstract class BaseSerializeHandler { oldCell = c; } } - this._rowEnd(row); + this._rowEnd(row, row === endRow - 1); } this._afterSerialize(); @@ -45,7 +46,7 @@ abstract class BaseSerializeHandler { } protected _nextCell(cell: IBufferCell, oldCell: IBufferCell, row: number, col: number): void { } - protected _rowEnd(row: 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,20 +72,23 @@ 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 _currentRow: string = ''; private _nullCellCount: number = 0; - // this is a null cell for reference for checking whether background is empty or not - private _nullCell: IBufferCell = this._buffer1.getNullCell(); - // 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(); + // this is a null cell for reference for checking whether background is empty or not + private _backgroundCell: MyBufferCell = MyBufferCell.from(this._cursorStyle); + + private _firstRow: number = 0; private _lastCursorRow: number = 0; private _lastCursorCol: number = 0; @@ -95,26 +99,21 @@ class StringSerializeHandler extends BaseSerializeHandler { protected _beforeSerialize(rows: number, start: number, end: number): void { this._allRows = new Array(rows); this._lastCursorRow = start; + this._firstRow = start; } - protected _rowEnd(row: number): void { + 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._nullCell)) { + if (this._nullCellCount > 0 && !equalBg(this._cursorStyle, this._backgroundCell)) { // use clear right to set background. // use move right to move cursor. this._currentRow += `\x1b[${this._nullCellCount}X`; + } - // set the cursor back because we aren't there - this._lastCursorRow = row; - this._lastCursorCol = this._terminal.cols - this._nullCellCount; - - this._nullCellCount = 0; - - // perform a style reset before next line, - // because scroll when having background set will change the whole background of next line. - this._currentRow += `\x1b[m`; - // FIXME: we just get a new one because we can't reset it. - this._cursorStyle = this._buffer1.getNullCell(); + if (!isLastRow) { + if (row - this._firstRow >= this._terminal.rows) { + this._backgroundCell = MyBufferCell.from(this._cursorStyle); + } } this._allRows[this._rowIndex++] = this._currentRow; @@ -178,9 +177,6 @@ class StringSerializeHandler extends BaseSerializeHandler { // this cell don't have content const isEmptyCell = cell.getChars() === ''; - // this cell don't have content and style - const isNullCell = cell.getWidth() === 1 && cell.getChars() === '' && cell.isAttributeDefault(); - 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. @@ -194,7 +190,7 @@ class StringSerializeHandler extends BaseSerializeHandler { if (this._nullCellCount > 0) { // use clear right to set background. // use move right to move cursor. - if (equalBg(this._cursorStyle, this._nullCell)) { + if (equalBg(this._cursorStyle, this._backgroundCell)) { this._currentRow += `\x1b[${this._nullCellCount}C`; } else { this._currentRow += `\x1b[${this._nullCellCount}X`; @@ -203,6 +199,9 @@ class StringSerializeHandler extends BaseSerializeHandler { this._nullCellCount = 0; } + this._lastCursorRow = row; + this._lastCursorCol = col; + this._currentRow += `\x1b[${sgrSeq.join(';')}m`; // update the last cursor style @@ -219,7 +218,7 @@ class StringSerializeHandler extends BaseSerializeHandler { // 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._nullCell)) { + if (equalBg(this._cursorStyle, this._backgroundCell)) { this._currentRow += `\x1b[${this._nullCellCount}C`; } else { this._currentRow += `\x1b[${this._nullCellCount}X`; @@ -227,10 +226,10 @@ class StringSerializeHandler extends BaseSerializeHandler { } this._nullCellCount = 0; } - this._currentRow += cell.getChars(); - } - if (!isNullCell) { + this._currentRow += cell.getChars(); + + // update cursor this._lastCursorRow = row; this._lastCursorCol = col + cell.getWidth(); } diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 4d90f3c5..afbe3b39 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -355,6 +355,33 @@ describe('SerializeAddon', () => { // and firefox have a bug that output -0 for unknown reason assert.equal(JSON.stringify(originalBuffer), JSON.stringify(newBuffer)); }); + + 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 writeSync(page, lines.join('\\r\\n')); + const originalBuffer = await page.evaluate(`SerializeAddon._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(`SerializeAddon._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)); + }); }); function newArray(initial: T | ((index: number) => T), count: number): T[] { From 84dfe8fcccb283656216e03933cebe2623d236b5 Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Fri, 18 Sep 2020 01:20:41 +0800 Subject: [PATCH 09/89] CLearup comment --- addons/xterm-addon-serialize/src/SerializeAddon.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 9518fcbf..a05250cf 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -106,7 +106,6 @@ class StringSerializeHandler extends BaseSerializeHandler { // 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. - // use move right to move cursor. this._currentRow += `\x1b[${this._nullCellCount}X`; } @@ -189,13 +188,11 @@ class StringSerializeHandler extends BaseSerializeHandler { // before update the style, we need to fill empty cell back if (this._nullCellCount > 0) { // use clear right to set background. - // use move right to move cursor. - if (equalBg(this._cursorStyle, this._backgroundCell)) { - this._currentRow += `\x1b[${this._nullCellCount}C`; - } else { + if (!equalBg(this._cursorStyle, this._backgroundCell)) { this._currentRow += `\x1b[${this._nullCellCount}X`; - this._currentRow += `\x1b[${this._nullCellCount}C`; } + // use move right to move cursor. + this._currentRow += `\x1b[${this._nullCellCount}C`; this._nullCellCount = 0; } From d7ed109f9d65b86599cd35eae517407486137757 Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Fri, 18 Sep 2020 15:21:59 +0800 Subject: [PATCH 10/89] Support the isWrapped handling --- .../src/SerializeAddon.ts | 165 +++++++++++------- .../test/SerializeAddon.api.ts | 104 +++++++---- 2 files changed, 174 insertions(+), 95 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index a05250cf..025f1833 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -77,6 +77,7 @@ function equalFlags(cell1: IBufferCell, cell2: IBufferCell): boolean { 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; @@ -91,6 +92,8 @@ class StringSerializeHandler extends BaseSerializeHandler { 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); @@ -98,6 +101,7 @@ class StringSerializeHandler extends BaseSerializeHandler { protected _beforeSerialize(rows: number, start: number, end: number): void { this._allRows = new Array(rows); + this._lastContentCursorRow = start; this._lastCursorRow = start; this._firstRow = start; } @@ -109,13 +113,82 @@ class StringSerializeHandler extends BaseSerializeHandler { this._currentRow += `\x1b[${this._nullCellCount}X`; } + let rowSeparator = ''; + + // handle row separator if (!isLastRow) { + // Enable BCE if (row - this._firstRow >= this._terminal.rows) { this._backgroundCell = MyBufferCell.from(this._cursorStyle); } + + // 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)!; + const thisRowLastSecondChar = currentLine.getCell(currentLine.length - 2)!; + const nextRowFirstChar = nextLine.getCell(0)!; + const isNextRowFirstCharDoubleWidth = nextRowFirstChar.getWidth() > 1; + + // validate whether this line wrap is ever possible + let isValid = false; + + if ( + nextRowFirstChar.getChars() && + isNextRowFirstCharDoubleWidth ? this._nullCellCount <= 1 : this._nullCellCount <= 0 + ) { + if ( + (thisRowLastChar.getChars() || thisRowLastChar.getWidth() === 0) && + equalBg(thisRowLastChar, nextRowFirstChar) + ) { + isValid = true; + } + + if ( + isNextRowFirstCharDoubleWidth && + (thisRowLastSecondChar.getChars() || thisRowLastSecondChar.getWidth() === 0) && + 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'; + + // do these because we filled the last several null slot, which we shouldn't + if (this._nullCellCount > 0) { + 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'; + } + + // force commit the cursor position + this._lastCursorRow = row + 1; + this._lastCursorCol = 0; + } + } } - this._allRows[this._rowIndex++] = this._currentRow; + this._allRows[this._rowIndex] = this._currentRow; + this._allRowSeparators[this._rowIndex++] = rowSeparator; this._currentRow = ''; this._nullCellCount = 0; } @@ -196,8 +269,8 @@ class StringSerializeHandler extends BaseSerializeHandler { this._nullCellCount = 0; } - this._lastCursorRow = row; - this._lastCursorCol = col; + this._lastContentCursorRow = this._lastCursorRow = row; + this._lastContentCursorCol = this._lastCursorCol = col; this._currentRow += `\x1b[${sgrSeq.join(';')}m`; @@ -227,37 +300,36 @@ class StringSerializeHandler extends BaseSerializeHandler { this._currentRow += cell.getChars(); // update cursor - this._lastCursorRow = row; - this._lastCursorCol = col + cell.getWidth(); + 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 = this._allRows.slice(0, rowEnd).join('\r\n'); + let content = ''; + + for (let i = 0; i < rowEnd; i++) { + content += this._allRows[i]; + if (i + 1 < rowEnd) { + content += this._allRowSeparators[i]; + } + } // restore the cursor const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY; const realCursorCol = this._buffer1.cursorX; - const hasScroll = this._buffer1.length > this._terminal.rows!; - const hasEmptyLine = hasScroll ? (this._buffer1.length - 1 > this._lastCursorRow) : (realCursorRow > this._lastCursorRow); - const cursorMoved = - hasScroll - ? hasEmptyLine - ? (realCursorCol !== 0 || realCursorRow !== this._buffer1.length - 1) - : (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol) - : hasEmptyLine - // we don't need to check the row because empty row count are based on cursor - ? realCursorCol !== 0 - : (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol); + const cursorMoved = (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol); const moveRight = (offset: number): void => { if (offset > 0) { @@ -274,27 +346,9 @@ class StringSerializeHandler extends BaseSerializeHandler { } }; - // Fix empty lines - if (hasEmptyLine) { - if (hasScroll) { - content += '\r\n'.repeat(this._buffer1.length - 1 - this._lastCursorRow); - } else { - content += '\r\n'.repeat(realCursorRow - this._lastCursorRow); - } - } - if (cursorMoved) { - if (hasEmptyLine) { - if (hasScroll) { - moveRight(realCursorCol); - moveDown(realCursorRow - (this._buffer1.length - 1)); - } else { - moveRight(realCursorCol); - } - } else { - moveDown(realCursorRow - this._lastCursorRow); - moveRight(realCursorCol - this._lastCursorCol); - } + moveDown(realCursorRow - this._lastCursorRow); + moveRight(realCursorCol - this._lastCursorCol); } @@ -322,7 +376,6 @@ export class SerializeAddon implements ITerminalAddon { } public serialize(scrollback?: number): string { - // TODO: Add word wrap mode support // TODO: Add combinedData support if (!this._terminal) { throw new Error('Cannot use addon until it has been loaded'); @@ -344,32 +397,14 @@ export class SerializeAddon implements ITerminalAddon { // this is a util used only for test private static _inspectBuffer(buffer: IBuffer): { x: number, y: number, data: any[][] } { const lines: any[] = []; - const cell = buffer.getNullCell(); for (let i = 0; i < buffer.length; i++) { - const line = []; - const bufferLine = buffer.getLine(i)!; - for (let j = 0; j < bufferLine.length; j++) { - const cellData: any = {}; - bufferLine.getCell(j, cell)!; - cellData.getBgColor = cell.getBgColor(); - cellData.getBgColorMode = cell.getBgColorMode(); - cellData.getChars = cell.getChars(); - cellData.getCode = cell.getCode(); - cellData.getFgColor = cell.getFgColor(); - cellData.getFgColorMode = cell.getFgColorMode(); - cellData.getWidth = cell.getWidth(); - cellData.isAttributeDefault = cell.isAttributeDefault(); - cellData.isBlink = cell.isBlink(); - cellData.isBold = cell.isBold(); - cellData.isDim = cell.isDim(); - cellData.isInverse = cell.isInverse(); - cellData.isInvisible = cell.isInvisible(); + /** + * Do this intentionally to get content of underlining source + */ + const bufferLine = (buffer.getLine(i)! as any)._line; - line.push(cellData); - } - - lines.push(line); + lines.push(JSON.stringify(bufferLine)); } return { diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index afbe3b39..4bf6d1b5 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -16,6 +16,20 @@ 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(`SerializeAddon._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(`SerializeAddon._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(); @@ -35,12 +49,54 @@ describe('SerializeAddon', () => { 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(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + + await page.evaluate(`term.reset();`); + await writeRawSync(page, '67890'); + const buffer2 = await page.evaluate(`SerializeAddon._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(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + + await page.evaluate(`term.reset();`); + await writeRawSync(page, '1234567890n12345'); + const buffer4 = await page.evaluate(`SerializeAddon._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('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 = [ @@ -281,15 +337,8 @@ describe('SerializeAddon', () => { '中文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中文中文', - '中' - ]; 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 () => { @@ -315,7 +364,7 @@ describe('SerializeAddon', () => { ]; await writeSync(page, lines.join('\\r\\n')); - assert.equal(JSON.stringify(await page.evaluate(`window.term.buffer.active.type`)), '"alternate"'); + 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'))); }); @@ -331,7 +380,7 @@ describe('SerializeAddon', () => { ]; await writeSync(page, lines.join('\\r\\n')); - assert.equal(JSON.stringify(await page.evaluate(`window.term.buffer.active === window.term.buffer.alt`)), 'false'); + 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'))); }); @@ -343,17 +392,7 @@ describe('SerializeAddon', () => { `2${CLEAR_RIGHT(9)}` ]; - await writeSync(page, lines.join('\\r\\n')); - const originalBuffer = await page.evaluate(`SerializeAddon._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(`SerializeAddon._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)); + await testNormalScreenEqual(page, lines.join('\r\n')); }); it('cause the BCE on scroll', async () => { @@ -369,18 +408,23 @@ describe('SerializeAddon', () => { `\u001b[44m${CLEAR_RIGHT(5)}1111111111111111` ]; - await writeSync(page, lines.join('\\r\\n')); - const originalBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + await testNormalScreenEqual(page, lines.join('\r\n')); + }); + it('handle invalid wrap', 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 result = await page.evaluate(`serializeAddon.serialize();`) as string; + const padLines = newArray( + (index: number) => digitsString(10, index), + 10 + ); - await page.evaluate(`term.reset();`); - await writeRawSync(page, result); - const newBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const lines = [ + `\u001b[44m${CLEAR_RIGHT(5)}123456789012345${MOVE_UP(1)}${CLEAR_RIGHT(5)}${MOVE_DOWN(1)}` + ]; - // 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)); + await testNormalScreenEqual(page, lines.join('\r\n')); }); }); From aee1629c258939d9034f066bba1a91b99df8dc6b Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Fri, 18 Sep 2020 21:02:56 +0800 Subject: [PATCH 11/89] Reuse the cell object to redice gc --- addons/xterm-addon-serialize/src/SerializeAddon.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 025f1833..dd34f780 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -106,6 +106,9 @@ class StringSerializeHandler extends BaseSerializeHandler { this._firstRow = start; } + 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)) { @@ -135,9 +138,9 @@ class StringSerializeHandler extends BaseSerializeHandler { this._lastCursorCol = 0; } else { rowSeparator = ''; - const thisRowLastChar = currentLine.getCell(currentLine.length - 1)!; - const thisRowLastSecondChar = currentLine.getCell(currentLine.length - 2)!; - const nextRowFirstChar = nextLine.getCell(0)!; + 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 From 47be9a2df4b7238c303357c658068d55a8a5ea68 Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Fri, 18 Sep 2020 22:02:30 +0800 Subject: [PATCH 12/89] Fix another error about impossible wrap --- .../src/SerializeAddon.ts | 5 ++ .../test/SerializeAddon.api.ts | 50 +++++++++++++++++-- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index dd34f780..ec8c6d0d 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -181,6 +181,11 @@ class StringSerializeHandler extends BaseSerializeHandler { rowSeparator += `\x1b[${this._nullCellCount}X`; rowSeparator += `\x1b[${currentLine.length - this._nullCellCount}D`; rowSeparator += '\x1b[B'; + + // This is content even it is invisible + // without this, wrap will be missing + this._lastContentCursorRow = row + 1; + this._lastContentCursorCol = 0; } // force commit the cursor position diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 4bf6d1b5..5dc29d0d 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -335,7 +335,12 @@ 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) + // 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();`), lines.join('\r\n')); @@ -410,21 +415,58 @@ describe('SerializeAddon', () => { await testNormalScreenEqual(page, lines.join('\r\n')); }); - it('handle invalid wrap', async () => { + + 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 = [ - `\u001b[44m${CLEAR_RIGHT(5)}123456789012345${MOVE_UP(1)}${CLEAR_RIGHT(5)}${MOVE_DOWN(1)}` + 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('\r\n')); + await testNormalScreenEqual(page, lines.join('')); }); }); From 0cb38cfdcbe67eb99625b3f78205ccd2ea4b49d5 Mon Sep 17 00:00:00 2001 From: Martin Sander Date: Thu, 14 Jan 2021 23:08:34 +0100 Subject: [PATCH 13/89] fire onSelectionChange on empty selection Fire the onSelectionChange event when a selection is cleared by single-clicking somewhere inside the terminal area. fixes #3193. This also slightly changes the behaviour when re-selecting the same area in the terminal. Before, this fired onSelectionChange, but it does not anymore, even when changing the direction of the selection. --- src/browser/services/SelectionService.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/browser/services/SelectionService.ts b/src/browser/services/SelectionService.ts index a3d8d12c..9e7d6531 100644 --- a/src/browser/services/SelectionService.ts +++ b/src/browser/services/SelectionService.ts @@ -105,6 +105,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; } @@ -681,7 +684,26 @@ export class SelectionService extends Disposable implements ISelectionService { this._coreService.triggerDataEvent(sequence, true); } } - } else if (this.hasSelection) { + } else { + this._fireIfSelectionChanged(); + } + } + + private _fireIfSelectionChanged(): void { + const hasSelection = this.hasSelection; + if (!hasSelection && !this._oldHasSelection) { + return; + } + + const start = this._model.finalSelectionStart; + const end = this._model.finalSelectionEnd; + + if (start?.[0] !== this._oldSelectionStart?.[0] || start?.[1] !== this._oldSelectionStart?.[1] || + end?.[0] !== this._oldSelectionEnd?.[0] || end?.[1] !== this._oldSelectionEnd?.[1]) { + + this._oldSelectionStart = start; + this._oldSelectionEnd = end; + this._oldHasSelection = hasSelection; this._onSelectionChange.fire(); } } From 66c80d8b788dae552df63f3df7a32e198767ae8e Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Fri, 15 Jan 2021 09:39:34 -0800 Subject: [PATCH 14/89] Simplify checks Co-authored-by: Megan Rogge --- src/browser/services/SelectionService.ts | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/browser/services/SelectionService.ts b/src/browser/services/SelectionService.ts index 9e7d6531..f4c8f58c 100644 --- a/src/browser/services/SelectionService.ts +++ b/src/browser/services/SelectionService.ts @@ -690,16 +690,26 @@ export class SelectionService extends Disposable implements ISelectionService { } private _fireIfSelectionChanged(): void { + // Fire if there is no selection const hasSelection = this.hasSelection; - if (!hasSelection && !this._oldHasSelection) { + if (!hasSelection) { + if (this._oldHasSelection) { + this._onSelectionChange.fire(); + } return; } const start = this._model.finalSelectionStart; const end = this._model.finalSelectionEnd; - if (start?.[0] !== this._oldSelectionStart?.[0] || start?.[1] !== this._oldSelectionStart?.[1] || - end?.[0] !== this._oldSelectionEnd?.[0] || end?.[1] !== this._oldSelectionEnd?.[1]) { + // 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._oldSelectionStart = start; this._oldSelectionEnd = end; From c6f93701f542862f1534c57795146b62b004125f Mon Sep 17 00:00:00 2001 From: Martin Sander Date: Sat, 16 Jan 2021 10:06:55 +0100 Subject: [PATCH 15/89] fire onSelectionChange on right click select fixes #3216. --- src/browser/Clipboard.ts | 4 ++-- src/browser/services/SelectionService.ts | 11 +++++++++-- src/browser/services/Services.ts | 3 +-- 3 files changed, 12 insertions(+), 6 deletions(-) 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/services/SelectionService.ts b/src/browser/services/SelectionService.ts index f4c8f58c..7feaf9eb 100644 --- a/src/browser/services/SelectionService.ts +++ b/src/browser/services/SelectionService.ts @@ -293,7 +293,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; @@ -316,7 +316,7 @@ 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): void { const coords = this._getMouseBufferCoords(event); if (coords) { this._selectWordAt(coords, false); @@ -759,6 +759,13 @@ export class SelectionService extends Disposable implements ISelectionService { this.refresh(); } + public rightClickSelect(ev: MouseEvent): void { + if (!this._isClickInSelection(ev)) { + this._selectWordAtCursor(ev); + this._fireIfSelectionChanged(); + } + } + /** * 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; From bc1048062dda8d64020309c425a5bb8094c37490 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Wed, 20 Jan 2021 20:05:14 +0100 Subject: [PATCH 16/89] early version of async support for CSI and ESC handlers --- src/common/CoreTerminal.ts | 2 +- src/common/InputHandler.ts | 66 +++++++++++--- src/common/input/WriteBuffer.ts | 65 +++++++++++-- src/common/parser/EscapeSequenceParser.ts | 106 +++++++++++++++++++++- src/common/parser/Types.d.ts | 2 +- test/benchmark/Terminal.benchmark.ts | 36 ++++++-- 6 files changed, 245 insertions(+), 32 deletions(-) diff --git a/src/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index 2f636349..11e71bad 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -109,7 +109,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 { diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index 626e1fe2..32428c77 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -333,7 +333,7 @@ export class InputHandler extends Disposable implements IInputHandler { 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: 'm'}, (params => this.charAttributes(params)) as (p: any) => void); 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)); @@ -454,10 +454,43 @@ export class InputHandler extends Disposable implements IInputHandler { super.dispose(); } - public parse(data: string | Uint8Array): void { + // FIXME: cleanup async handling + private _parseStack = { + paused: false, + cursorStartX: 0, + cursorStartY: 0, + decodedLength: 0, + position: 0 + }; + + 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; + } + + 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)) { + 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 +502,33 @@ 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); + 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); + return result; + } + } } buffer = this._bufferService.buffer; diff --git a/src/common/input/WriteBuffer.ts b/src/common/input/WriteBuffer.ts index c7d82458..c6178024 100644 --- a/src/common/input/WriteBuffer.ts +++ b/src/common/input/WriteBuffer.ts @@ -37,8 +37,9 @@ export class WriteBuffer { private _pendingData = 0; private _bufferOffset = 0; - constructor(private _action: (data: string | Uint8Array) => void) { } + constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise) { } + // FIXME: does not work that way anymore with async handlers!!! 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 @@ -76,16 +77,64 @@ export class WriteBuffer { this._callbacks.push(callback); } - protected _innerWrite(): void { - const startTime = Date.now(); + protected _innerWrite(d: number = 0, promiseResult: boolean = true): void { + let result: void | Promise; + const startTime = d || Date.now(); while (this._writeBuffer.length > this._bufferOffset) { const data = this._writeBuffer[this._bufferOffset]; - const cb = this._callbacks[this._bufferOffset]; - this._bufferOffset++; - this._action(data); - this._pendingData -= data.length; + if (result = this._action(data, promiseResult)) { + /** + * 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). + * FIXME: No clear exception handling rules for sync handlers yet (will exit whole processing?). + */ + + /** + * 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); + + result.then(continuation, err => { setTimeout(() => { throw err; }); continuation(true); }); + 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,7 +148,7 @@ 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 = []; diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 96d206b9..daf9e6eb 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -449,7 +449,45 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this.precedingCodepoint = 0; } + // FIXME: cleanup async handling + private _parseStack: { + paused: boolean; + type: 'ESC' | 'CSI'; // FIXME: support for DCS and OSC + handlers: CsiHandlerType[] | EscHandlerType[]; + handlerPos: number; + transition: number; + currentState: ParserState; + collect: number; + pos: number; + } = { + paused: false, + type: 'ESC', + handlers: [], + handlerPos: 0, + transition: 0, + currentState: 0, + collect: 0, + pos: 0 + }; + private _preserveStack( + type: 'ESC' | 'CSI', + handlers: CsiHandlerType[] | EscHandlerType[], + handlerPos: number, + transition: number, + currentState: ParserState, + collect: number, + pos: number + ): void { + this._parseStack.paused = true; + this._parseStack.type = type; + this._parseStack.handlers = handlers; + this._parseStack.handlerPos = handlerPos; + this._parseStack.transition = transition; + this._parseStack.currentState = currentState; + this._parseStack.collect = collect; + this._parseStack.pos = pos; + } /** * Parse UTF32 codepoints in `data` up to `length`. @@ -465,7 +503,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP * - OSC_STRING:OSC_PUT * - DCS_PASSTHROUGH:DCS_PUT */ - 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; @@ -475,8 +513,58 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP const params = this._params; const table: Uint8Array = this._transitions.table; + let res: any; + let start = 0; + if (this._parseStack.paused) { + const handlers = this._parseStack.handlers; + let handlerPos = this._parseStack.handlerPos - 1; + transition = this._parseStack.transition; + currentState = this._parseStack.currentState; + collect = this._parseStack.collect; + start = this._parseStack.pos; + + // we have to resume the old handler loop if: + // - return value of the promise was `false` + // - handlers are not exhausted yet + // FIXME: removing handlers from within a handler of the same sequence + // is not supported atm (also true for sync handlers)!! + if (promiseResult === false && handlerPos > -1) { + switch (this._parseStack.type) { + case 'CSI': + for (; handlerPos >= 0; handlerPos--) { + if ((res = (handlers as CsiHandlerType[])[handlerPos](params)) !== false) { + if (res instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return res; + } + break; + } + } + break; + case 'ESC': + for (; handlerPos >= 0; handlerPos--) { + if ((res = (handlers as EscHandlerType[])[handlerPos]()) !== false) { + if (res instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return res; + } + break; + } + } + break; + } + } + // cleanup before continuing with the main loop + this.precedingCodepoint = 0; + this._parseStack.paused = false; + start++; + currentState = transition & TableAccess.TRANSITION_STATE_MASK; + } + + // console.log('startPos', start, length); + // process input string - for (let i = 0; i < length; ++i) { + for (let i = start; i < length; ++i) { code = data[i]; // normal transition & action lookup @@ -534,7 +622,13 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP 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) { + // FIXME: remove setHandler interface, always use addHandler with proper return value in true|false + // background - result of undefined leads to nonsense instanceof Promise test below + if ((res = handlers[j](params)) !== false) { + if (res && res instanceof Promise) { + this._preserveStack('CSI', handlers, j, transition, currentState, collect, i); + return res; + } break; } } @@ -568,7 +662,11 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP let jj = handlersEsc ? handlersEsc.length - 1 : -1; for (; jj >= 0; jj--) { // undefined or true means success and to stop bubbling - if (handlersEsc[jj]() !== false) { + if ((res = handlersEsc[jj]()) !== false) { + if (res && res instanceof Promise) { + this._preserveStack('ESC', handlersEsc, jj, transition, currentState, collect, i); + return res; + } break; } } diff --git a/src/common/parser/Types.d.ts b/src/common/parser/Types.d.ts index e2fac89f..8d55c51a 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -160,7 +160,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`. diff --git a/test/benchmark/Terminal.benchmark.ts b/test/benchmark/Terminal.benchmark.ts index 76139cb6..7d0f5d84 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,46 @@ perfContext('Terminal: ls -lR /usr/lib', () => { } }); - perfContext('write', () => { + // perfContext('write/string/sync', () => { + // let terminal: Terminal; + // before(() => { + // terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000}); + // }); + // new ThroughputRuntimeCase('', () => { + // terminal.writeSync(content); + // return {payloadSize: contentUtf8.length}; + // }, {fork: false}).showAverageThroughput(); + // }); + // + // perfContext('write/Utf8/sync', () => { + // let terminal: Terminal; + // before(() => { + // terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000}); + // }); + // new ThroughputRuntimeCase('', () => { + // terminal.writeSync(content); + // return {payloadSize: contentUtf8.length}; + // }, {fork: false}).showAverageThroughput(); + // }); + + 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(); }); From c50c134e25b78693787366ae3c1af6461fae920c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Wed, 20 Jan 2021 23:03:55 +0100 Subject: [PATCH 17/89] simplify parser handler interface: - remove setHandler - apply boolean return to ESC|CSI|OSC|DCS handlers (rewrite empty return defaulting to true) - rename addHandler to registerHandler --- src/common/InputHandler.ts | 418 ++++++++++-------- src/common/parser/DcsParser.test.ts | 35 +- src/common/parser/DcsParser.ts | 12 +- .../parser/EscapeSequenceParser.test.ts | 197 +++++---- src/common/parser/EscapeSequenceParser.ts | 26 +- src/common/parser/OscParser.test.ts | 35 +- src/common/parser/OscParser.ts | 11 +- src/common/parser/Types.d.ts | 25 +- .../EscapeSequenceParser.benchmark.ts | 136 +++--- 9 files changed, 476 insertions(+), 419 deletions(-) diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index 626e1fe2..60c1e357 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -146,36 +146,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; } } @@ -297,53 +303,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 +373,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 +415,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,7 +453,7 @@ 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 { @@ -642,35 +648,35 @@ export class InputHandler extends Disposable implements IInputHandler { public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): 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. */ public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable { - return this._parser.addDcsHandler(id, new DcsHandler(callback)); + return this._parser.registerDcsHandler(id, new DcsHandler(callback)); } /** * Forward addEscHandler from parser. */ public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable { - return this._parser.addEscHandler(id, callback); + return this._parser.registerEscHandler(id, callback); } /** * Forward addOscHandler from parser. */ public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable { - return this._parser.addOscHandler(ident, new OscHandler(callback)); + return this._parser.registerOscHandler(ident, new OscHandler(callback)); } /** @@ -681,8 +687,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 +702,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 +724,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._dirtyRowService.markDirty(buffer.y); this._onLineFeed.fire(); + return true; } /** @@ -725,8 +733,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 +749,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 +758,7 @@ export class InputHandler extends Disposable implements IInputHandler { if (buffer.x > 0) { buffer.x--; } - return; + return true; } // reverse wrap-around is enabled @@ -790,6 +799,7 @@ export class InputHandler extends Disposable implements IInputHandler { } } this._restrictCursor(); + return true; } /** @@ -798,15 +808,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 +827,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 +839,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 +888,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 +896,7 @@ export class InputHandler extends Disposable implements IInputHandler { } else { this._moveCursor(0, -(params.params[0] || 1)); } + return true; } /** @@ -892,7 +906,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 +914,7 @@ export class InputHandler extends Disposable implements IInputHandler { } else { this._moveCursor(0, params.params[0] || 1); } + return true; } /** @@ -908,8 +923,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 +934,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 +947,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 +961,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 +973,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 +987,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 +1004,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 +1015,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 +1026,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 +1038,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 +1051,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 +1067,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 +1083,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 +1099,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 +1111,7 @@ export class InputHandler extends Disposable implements IInputHandler { while (param--) { buffer.x = buffer.prevStop(); } + return true; } @@ -1140,7 +1170,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 +1217,7 @@ export class InputHandler extends Disposable implements IInputHandler { } break; } + return true; } /** @@ -1211,7 +1242,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 +1256,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } this._dirtyRowService.markDirty(this._bufferService.buffer.y); + return true; } /** @@ -1236,7 +1268,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 +1276,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 +1292,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 +1304,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 +1312,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 +1329,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 +1343,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 +1355,7 @@ export class InputHandler extends Disposable implements IInputHandler { ); this._dirtyRowService.markDirty(this._bufferService.buffer.y); } + return true; } /** @@ -1334,7 +1369,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 +1381,7 @@ export class InputHandler extends Disposable implements IInputHandler { ); this._dirtyRowService.markDirty(this._bufferService.buffer.y); } + return true; } /** @@ -1356,7 +1392,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 +1403,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 +1411,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 +1422,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 +1443,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 +1455,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1438,10 +1477,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 +1489,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1461,10 +1501,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 +1513,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1484,10 +1525,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 +1537,7 @@ export class InputHandler extends Disposable implements IInputHandler { line.isWrapped = false; } this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom); + return true; } /** @@ -1506,7 +1548,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 +1560,7 @@ export class InputHandler extends Disposable implements IInputHandler { ); this._dirtyRowService.markDirty(this._bufferService.buffer.y); } + return true; } /** @@ -1547,9 +1590,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 +1601,7 @@ export class InputHandler extends Disposable implements IInputHandler { data[i] = this._parser.precedingCodepoint; } this.print(data, 0, data.length); + return true; } /** @@ -1585,15 +1629,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 +1665,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 +1683,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 +1711,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 +1722,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } /** @@ -1791,7 +1838,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 +1931,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } @@ -1907,7 +1955,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 +1966,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } /** @@ -2029,7 +2078,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 +2155,7 @@ export class InputHandler extends Disposable implements IInputHandler { break; } } + return true; } /** @@ -2298,12 +2348,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 +2452,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._logService.debug('Unknown SGR attribute: %d.', p); } } + return true; } /** @@ -2429,7 +2480,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 +2493,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 +2524,7 @@ export class InputHandler extends Disposable implements IInputHandler { // this.handler(C0.ESC + '[?50n'); break; } + return true; } /** @@ -2493,7 +2546,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 +2564,7 @@ export class InputHandler extends Disposable implements IInputHandler { // reset DECOM this._coreService.decPrivateModes.origin = false; + return true; } /** @@ -2532,7 +2586,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 +2604,7 @@ export class InputHandler extends Disposable implements IInputHandler { } const isBlinking = param % 2 === 1; this._optionsService.options.cursorBlink = isBlinking; + return true; } /** @@ -2559,7 +2614,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 +2627,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._bufferService.buffer.scrollBottom = bottom - 1; this._setCursor(0, 0); } + return true; } /** @@ -2604,9 +2660,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 +2706,7 @@ export class InputHandler extends Disposable implements IInputHandler { } break; } + return true; } @@ -2661,12 +2718,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 +2736,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 +2746,7 @@ export class InputHandler extends Disposable implements IInputHandler { this._charsetService.charset = this._bufferService.buffer.savedCharset; } this._restrictCursor(); + return true; } @@ -2701,17 +2760,19 @@ 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 { @@ -2743,7 +2804,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 +2812,7 @@ export class InputHandler extends Disposable implements IInputHandler { else { this._logService.warn(`Expected format ;rgb:// but got data: ${data}`); } + return true; } /** @@ -2762,9 +2824,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 +2835,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 +2847,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 +2860,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 +2882,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 +2903,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 +2914,7 @@ export class InputHandler extends Disposable implements IInputHandler { buffer.y = this._bufferService.rows - 1; } this._restrictCursor(); + return true; } /** @@ -2860,8 +2927,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 +2941,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 +2956,7 @@ export class InputHandler extends Disposable implements IInputHandler { buffer.y--; this._restrictCursor(); // quickfix to not run out of bounds } + return true; } /** @@ -2895,9 +2964,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 +2994,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 +3007,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 +3027,6 @@ export class InputHandler extends Disposable implements IInputHandler { } this._dirtyRowService.markAllDirty(); this._setCursor(0, 0); + return true; } } diff --git a/src/common/parser/DcsParser.test.ts b/src/common/parser/DcsParser.test.ts index dbabb4fa..cf174139 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) { diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index a09fd68c..8b934942 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -22,7 +22,7 @@ export class DcsParser implements IDcsParser { this._handlerFb = () => {}; } - public addHandler(ident: number, handler: IDcsHandler): IDisposable { + public registerHandler(ident: number, handler: IDcsHandler): IDisposable { if (this._handlers[ident] === undefined) { this._handlers[ident] = []; } @@ -38,10 +38,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]; } @@ -112,7 +108,7 @@ export class DcsHandler implements IDcsHandler { private _params: IParams | undefined; private _hitLimit: boolean = false; - constructor(private _handler: (data: string, params: IParams) => any) {} + constructor(private _handler: (data: string, params: IParams) => boolean) {} public hook(params: IParams): void { this._params = params.clone(); @@ -131,8 +127,8 @@ export class DcsHandler implements IDcsHandler { } } - public unhook(success: boolean): any { - let ret; + public unhook(success: boolean): boolean { + let ret = false; if (this._hitLimit) { ret = false; } else if (success) { diff --git a/src/common/parser/EscapeSequenceParser.test.ts b/src/common/parser/EscapeSequenceParser.test.ts index 4934d346..468dc934 100644 --- a/src/common/parser/EscapeSequenceParser.test.ts +++ b/src/common/parser/EscapeSequenceParser.test.ts @@ -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 { @@ -1206,11 +1206,13 @@ describe('EscapeSequenceParser', function (): void { chai.expect(print).equal(''); }); it('ESC handler', function (): void { - parser2.setEscHandler({intermediates: '%', final: 'G'}, function (): void { + 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']); @@ -1226,49 +1228,49 @@ describe('EscapeSequenceParser', function (): void { }); 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']); }); 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']); }); 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']); }); 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']); }); 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]); }); 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']); }); 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); @@ -1276,8 +1278,9 @@ describe('EscapeSequenceParser', function (): void { }); }); it('CSI handler', function (): void { - parser2.setCsiHandler({final: 'm'}, function (params: IParams): void { + 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], '']]); @@ -1290,16 +1293,16 @@ describe('EscapeSequenceParser', function (): void { 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], '']]); }); 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], '']]); @@ -1307,9 +1310,9 @@ describe('EscapeSequenceParser', function (): void { 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], '']]); @@ -1318,9 +1321,9 @@ describe('EscapeSequenceParser', function (): void { 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'); @@ -1328,16 +1331,16 @@ describe('EscapeSequenceParser', function (): void { }); 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]); }); 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], '']]); @@ -1345,8 +1348,8 @@ describe('EscapeSequenceParser', function (): void { }); 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); @@ -1355,11 +1358,13 @@ describe('EscapeSequenceParser', function (): void { }); }); it('EXECUTE handler', function (): void { - parser2.setExecuteHandler('\n', function (): void { + 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']); @@ -1370,8 +1375,9 @@ describe('EscapeSequenceParser', function (): void { chai.expect(exe).eql(['\n']); }); it('OSC handler', function (): void { - parser2.setOscHandler(1, new OscHandler(function (data: string): void { + 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']]); @@ -1384,16 +1390,16 @@ describe('EscapeSequenceParser', function (): void { 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']]); }); 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']]); @@ -1401,9 +1407,9 @@ describe('EscapeSequenceParser', function (): void { 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']]); @@ -1412,9 +1418,9 @@ describe('EscapeSequenceParser', function (): void { 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'); @@ -1422,16 +1428,16 @@ describe('EscapeSequenceParser', function (): void { }); 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]); }); 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']]); @@ -1439,8 +1445,8 @@ describe('EscapeSequenceParser', function (): void { }); 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); @@ -1449,7 +1455,7 @@ describe('EscapeSequenceParser', function (): void { }); }); it('DCS handler', function (): void { - parser2.setDcsHandler({intermediates: '+', final: 'p'}, { + parser2.registerDcsHandler({intermediates: '+', final: 'p'}, { hook: function (params: IParams): void { dcs.push(['hook', '', params.toArray(), 0]); }, @@ -1460,8 +1466,9 @@ 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'); @@ -1482,54 +1489,54 @@ describe('EscapeSequenceParser', function (): void { 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']]); }); 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']]); }); 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']]); }); 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']]); }); 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]); }); 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']]); }); 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); @@ -1591,11 +1598,11 @@ describe('EscapeSequenceParser', function (): void { 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'); + chai.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'); + chai.assert.throws(() => { parser.registerEscHandler({final: '\x2f'}, () => true); }, 'final must be in range 48 .. 126'); + chai.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'); @@ -1608,9 +1615,9 @@ describe('EscapeSequenceParser', function (): void { 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(); @@ -1620,12 +1627,12 @@ describe('EscapeSequenceParser', function (): void { }); 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(); @@ -1638,12 +1645,12 @@ describe('EscapeSequenceParser', function (): void { }); 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(); diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 96d206b9..3ffcd2d5 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -280,7 +280,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 +344,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 +360,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 +377,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 +393,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 +400,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 +410,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); diff --git a/src/common/parser/OscParser.test.ts b/src/common/parser/OscParser.test.ts index 127bd83a..e2c8641c 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); diff --git a/src/common/parser/OscParser.ts b/src/common/parser/OscParser.ts index e8c5a801..3a9ae19a 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -15,7 +15,7 @@ export class OscParser implements IOscParser { private _handlers: IHandlerCollection = Object.create(null); private _handlerFb: OscFallbackHandlerType = () => { }; - public addHandler(ident: number, handler: IOscHandler): IDisposable { + public registerHandler(ident: number, handler: IOscHandler): IDisposable { if (this._handlers[ident] === undefined) { this._handlers[ident] = []; } @@ -30,9 +30,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]; } @@ -171,7 +168,7 @@ export class OscHandler implements IOscHandler { private _data = ''; private _hitLimit: boolean = false; - constructor(private _handler: (data: string) => any) {} + constructor(private _handler: (data: string) => boolean) {} public start(): void { this._data = ''; @@ -189,8 +186,8 @@ export class OscHandler implements IOscHandler { } } - public end(success: boolean): any { - let ret; + public end(success: boolean): boolean { + let ret = false; if (this._hitLimit) { ret = false; } else if (success) { diff --git a/src/common/parser/Types.d.ts b/src/common/parser/Types.d.ts index e2fac89f..b325d025 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -69,7 +69,7 @@ export interface IParsingState { * CSI handler types. * Note: `params` is borrowed. */ -export type CsiHandlerType = (params: IParams) => boolean | void; +export type CsiHandlerType = (params: IParams) => boolean; export type CsiFallbackHandlerType = (ident: number, params: IParams) => void; /** @@ -93,20 +93,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; } export type DcsFallbackHandlerType = (ident: number, action: 'HOOK' | 'PUT' | 'UNHOOK', payload?: any) => void; /** * ESC handler types. */ -export type EscHandlerType = () => boolean | void; +export type EscHandlerType = () => boolean; 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 +129,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; } export type OscFallbackHandlerType = (ident: number, action: 'START' | 'PUT' | 'END', payload?: any) => void; @@ -174,29 +174,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 +205,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; diff --git a/test/benchmark/EscapeSequenceParser.benchmark.ts b/test/benchmark/EscapeSequenceParser.benchmark.ts index e4591dde..88bfefe5 100644 --- a/test/benchmark/EscapeSequenceParser.benchmark.ts +++ b/test/benchmark/EscapeSequenceParser.benchmark.ts @@ -21,7 +21,7 @@ function toUtf32(s: string): Uint32Array { class DcsHandler implements IDcsHandler { public hook(params: IParams): void {} public put(data: Uint32Array, start: number, end: number): void {} - public unhook(): void {} + public unhook(): boolean { return true; } } @@ -32,73 +32,73 @@ 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(2, new OscHandler(data => true)); + 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: 'q'}, new DcsHandler()); }); perfContext('PRINT - a', () => { From d67faff92ac04aee5b9f6dcc7bcf84dce8e0bb3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 21 Jan 2021 11:38:47 +0100 Subject: [PATCH 18/89] simplify return eval --- src/common/parser/DcsParser.ts | 2 +- src/common/parser/EscapeSequenceParser.ts | 23 +++++++++++++++++++---- src/common/parser/OscParser.ts | 2 +- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index 8b934942..f501fe25 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -84,7 +84,7 @@ export class DcsParser implements IDcsParser { } else { let j = this._active.length - 1; for (; j >= 0; j--) { - if (this._active[j].unhook(success) !== false) { + if (this._active[j].unhook(success)) { break; } } diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 3ffcd2d5..065cd1d9 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -521,8 +521,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP const handlers = this._csiHandlers[collect << 8 | code]; let j = handlers ? handlers.length - 1 : -1; for (; j >= 0; j--) { - // undefined or true means success and to stop bubbling - if (handlers[j](params) !== false) { + // true means success and to stop bubbling + if (handlers[j](params)) { break; } } @@ -555,8 +555,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP const handlersEsc = this._escHandlers[collect << 8 | code]; let jj = handlersEsc ? handlersEsc.length - 1 : -1; for (; jj >= 0; jj--) { - // undefined or true means success and to stop bubbling - if (handlersEsc[jj]() !== false) { + // true means success and to stop bubbling + if (handlersEsc[jj]()) { break; } } @@ -582,6 +582,21 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP i = j - 1; break; } + if (++j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { + dcs.put(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { + dcs.put(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { + dcs.put(data, i, j); + i = j - 1; + break; + } } break; case ParserAction.DCS_UNHOOK: diff --git a/src/common/parser/OscParser.ts b/src/common/parser/OscParser.ts index 3a9ae19a..ff5e7074 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -83,7 +83,7 @@ export class OscParser implements IOscParser { } else { let j = handlers.length - 1; for (; j >= 0; j--) { - if (handlers[j].end(success) !== false) { + if (handlers[j].end(success)) { break; } } From 9d0200252baffc87369964c6109adc91dd3546c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 21 Jan 2021 13:05:57 +0100 Subject: [PATCH 19/89] fix possible OSC handler bug skipping the fallback handler --- src/common/parser/OscParser.ts | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/common/parser/OscParser.ts b/src/common/parser/OscParser.ts index ff5e7074..e7edac66 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -8,9 +8,11 @@ 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 = () => { }; @@ -40,6 +42,7 @@ export class OscParser implements IOscParser { public dispose(): void { this._handlers = Object.create(null); this._handlerFb = () => {}; + this._active = EMPTY_HANDLERS; } public reset(): void { @@ -47,28 +50,28 @@ export class OscParser implements IOscParser { if (this._state === OscState.PAYLOAD) { this.end(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); + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].put(data, start, end); } } } @@ -77,20 +80,19 @@ export class OscParser implements IOscParser { // 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) { + if (!this._active.length) { this._handlerFb(this._id, 'END', success); } else { - let j = handlers.length - 1; + let j = this._active.length - 1; for (; j >= 0; j--) { - if (handlers[j].end(success)) { + if (this._active[j].end(success)) { break; } } j--; // cleanup left over handlers for (; j >= 0; j--) { - handlers[j].end(false); + this._active[j].end(false); } } } @@ -98,7 +100,6 @@ export class OscParser implements IOscParser { public start(): void { // always reset leftover handlers this.reset(); - this._id = -1; this._state = OscState.ID; } @@ -155,6 +156,7 @@ export class OscParser implements IOscParser { } this._end(success); } + this._active = EMPTY_HANDLERS; this._id = -1; this._state = OscState.START; } From dd5b295219d9b788175a3da201d1982ded169ca3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 21 Jan 2021 13:08:01 +0100 Subject: [PATCH 20/89] release active handler list on dispose in DcsHandler --- src/common/parser/DcsParser.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index f501fe25..3a692ca0 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -20,6 +20,7 @@ export class DcsParser implements IDcsParser { public dispose(): void { this._handlers = Object.create(null); this._handlerFb = () => {}; + this._active = EMPTY_HANDLERS; } public registerHandler(ident: number, handler: IDcsHandler): IDisposable { From 3f659a15da246f1c19517829363cb7fb3d34f374 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 21 Jan 2021 15:58:03 +0100 Subject: [PATCH 21/89] minor fixes: - better perf for short DCS without params (8 times faster) - test perf for class and string based interfaces of OSC and DCS separately - undo wrong commit on parser --- src/common/parser/DcsParser.ts | 16 ++- src/common/parser/EscapeSequenceParser.ts | 17 +-- .../EscapeSequenceParser.benchmark.ts | 115 ++++++++++++++---- 3 files changed, 105 insertions(+), 43 deletions(-) diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index 3a692ca0..2fa28992 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -100,19 +100,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) => boolean) {} 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; } @@ -133,9 +141,9 @@ export class DcsHandler implements IDcsHandler { if (this._hitLimit) { ret = false; } else if (success) { - ret = this._handler(this._data, this._params || new Params()); + ret = this._handler(this._data, this._params); } - this._params = undefined; + this._params = EMPTY_PARAMS; this._data = ''; this._hitLimit = false; return ret; diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 065cd1d9..9a403feb 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -582,21 +582,6 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP i = j - 1; break; } - if (++j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { - dcs.put(data, i, j); - i = j - 1; - break; - } - if (++j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { - dcs.put(data, i, j); - i = j - 1; - break; - } - if (++j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { - dcs.put(data, i, j); - i = j - 1; - break; - } } break; case ParserAction.DCS_UNHOOK: @@ -613,7 +598,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP 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)) { + if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code < NON_ASCII_PRINTABLE)) { osc.put(data, i, j); i = j - 1; break; diff --git a/test/benchmark/EscapeSequenceParser.benchmark.ts b/test/benchmark/EscapeSequenceParser.benchmark.ts index 88bfefe5..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(): boolean { return true; } + 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; } } @@ -81,7 +89,7 @@ perfContext('Parser throughput - 50MB data', () => { parser.setExecuteHandler(C1.NEL, () => true); parser.setExecuteHandler(C1.HTS, () => true); parser.registerOscHandler(0, new OscHandler(data => true)); - parser.registerOscHandler(2, new OscHandler(data => true)); + parser.registerOscHandler(1, new FastOscHandler()); parser.registerEscHandler({final: '7'}, () => true); parser.registerEscHandler({final: '8'}, () => true); parser.registerEscHandler({final: 'D'}, () => true); @@ -98,14 +106,15 @@ perfContext('Parser throughput - 50MB data', () => { parser.registerEscHandler({final: '~'}, () => true); parser.registerEscHandler({intermediates: '%', final: '@'}, () => true); parser.registerEscHandler({intermediates: '%', final: 'G'}, () => true); - parser.registerDcsHandler({final: 'q'}, new DcsHandler()); + 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); From 554b4a82240343c7e568daaa7587b7aafbc967ba Mon Sep 17 00:00:00 2001 From: Martin Sander Date: Thu, 21 Jan 2021 22:55:25 +0100 Subject: [PATCH 22/89] Store old selection when firing onSelectionChange --- src/browser/services/SelectionService.ts | 29 +++++++++++++----------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/browser/services/SelectionService.ts b/src/browser/services/SelectionService.ts index 7feaf9eb..3b993876 100644 --- a/src/browser/services/SelectionService.ts +++ b/src/browser/services/SelectionService.ts @@ -685,23 +685,22 @@ export class SelectionService extends Disposable implements ISelectionService { } } } else { - this._fireIfSelectionChanged(); + this._fireEventIfSelectionChanged(); } } - private _fireIfSelectionChanged(): void { - // Fire if there is no selection - const hasSelection = this.hasSelection; + 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._onSelectionChange.fire(); + this._fireOnSelectionChange(start, end, hasSelection); } return; } - const start = this._model.finalSelectionStart; - const end = this._model.finalSelectionEnd; - // Sanity check, these should not be undefined as there is a selection if (!start || !end) { return; @@ -711,13 +710,17 @@ export class SelectionService extends Disposable implements ISelectionService { start[0] !== this._oldSelectionStart[0] || start[1] !== this._oldSelectionStart[1] || end[0] !== this._oldSelectionEnd[0] || end[1] !== this._oldSelectionEnd[1])) { - this._oldSelectionStart = start; - this._oldSelectionEnd = end; - this._oldHasSelection = hasSelection; - this._onSelectionChange.fire(); + 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 @@ -762,7 +765,7 @@ export class SelectionService extends Disposable implements ISelectionService { public rightClickSelect(ev: MouseEvent): void { if (!this._isClickInSelection(ev)) { this._selectWordAtCursor(ev); - this._fireIfSelectionChanged(); + this._fireEventIfSelectionChanged(); } } From 4a1bdad7590e87e03653db15c8743a48be3cc6af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Fri, 22 Jan 2021 19:48:50 +0100 Subject: [PATCH 23/89] fix tests for async handlers in inputhandler --- src/common/InputHandler.test.ts | 1038 ++++++++++++++++--------------- 1 file changed, 526 insertions(+), 512 deletions(-) diff --git a/src/common/InputHandler.test.ts b/src/common/InputHandler.test.ts index 4c0d8559..ebc0df6a 100644 --- a/src/common/InputHandler.test.ts +++ b/src/common/InputHandler.test.ts @@ -41,6 +41,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 +130,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,15 +146,15 @@ 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'); @@ -171,15 +183,15 @@ describe('InputHandler', () => { expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + ' '); expect(line1.translateToString(true)).equals(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'); @@ -211,14 +223,14 @@ describe('InputHandler', () => { expect(line1.translateToString(false)).equals(Array(bufferService.cols - 9).join('a') + ' '); expect(line1.translateToString(true)).equals(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; @@ -239,12 +251,12 @@ describe('InputHandler', () => { expect(bufferService.buffer.lines.get(2)!.translateToString(false)).equals(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; @@ -272,7 +284,7 @@ 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; @@ -300,7 +312,7 @@ 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; @@ -328,9 +340,9 @@ 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 @@ -343,9 +355,9 @@ 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 @@ -358,45 +370,45 @@ describe('InputHandler', () => { }); 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'); + it('should handle DECSET/DECRST 47 (alt screen buffer)', async () => { + await handler.parseP('\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'); // Text color of 'TEST' should be red expect((bufferService.buffer.lines.get(1)!.loadCell(4, new CellData()).getFgColor())).to.equal(1); }); - it('should handle DECSET/DECRST 1047 (alt screen buffer)', () => { - handler.parse('\x1b[?1047h\r\n\x1b[31mJUNK\x1b[?1047lTEST'); + it('should handle DECSET/DECRST 1047 (alt screen buffer)', async () => { + await handler.parseP('\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'); // Text color of 'TEST' should be red expect((bufferService.buffer.lines.get(1)!.loadCell(4, new CellData()).getFgColor())).to.equal(1); }); - it('should handle DECSET/DECRST 1048 (alt screen cursor)', () => { - handler.parse('\x1b[?1048h\r\n\x1b[31mJUNK\x1b[?1048lTEST'); + it('should handle DECSET/DECRST 1048 (alt screen cursor)', async () => { + await handler.parseP('\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'); // Text color of 'TEST' should be default @@ -404,166 +416,166 @@ describe('InputHandler', () => { // Text color of 'JUNK' should be red expect((bufferService.buffer.lines.get(1)!.loadCell(0, new CellData()).getFgColor())).to.equal(1); }); - it('should handle DECSET/DECRST 1049 (alt screen buffer+cursor)', () => { - handler.parse('\x1b[?1049h\r\n\x1b[31mJUNK\x1b[?1049lTEST'); + it('should handle DECSET/DECRST 1049 (alt screen buffer+cursor)', async () => { + await handler.parseP('\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(''); // Text color of 'TEST' should be default expect(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg).to.equal(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'); + 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'); expect(bufferService.buffer.translateBufferLineToString(0, true)).to.equal('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'); + await handler.parseP('\x1b[?1049h\x1b[uTEST'); expect(bufferService.buffer.translateBufferLineToString(1, true)).to.equal('TEST'); // Text color of 'TEST' should be red expect((bufferService.buffer.lines.get(1)!.loadCell(0, new CellData()).getFgColor())).to.equal(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); }); }); 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 +585,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 +731,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 +1105,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 +1137,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 +1215,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 +1407,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 +1485,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 +1558,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 +1568,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 +1600,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 +1620,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 +1657,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); }); }); @@ -1733,15 +1745,17 @@ 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\\'); }); }); }); From adfeffec764caffe4bfcca15014350f6ea650573 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Fri, 22 Jan 2021 21:17:34 +0100 Subject: [PATCH 24/89] deprecate writeSync --- src/browser/Terminal.test.ts | 471 +++++++++++++++++----------------- src/browser/TestUtils.test.ts | 3 + src/common/CoreTerminal.ts | 10 + 3 files changed, 254 insertions(+), 230 deletions(-) diff --git a/src/browser/Terminal.test.ts b/src/browser/Terminal.test.ts index 8626be09..2e09f719 100644 --- a/src/browser/Terminal.test.ts +++ b/src/browser/Terminal.test.ts @@ -55,22 +55,30 @@ 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 => { @@ -178,10 +186,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 +233,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 +283,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 +306,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 +320,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 +341,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 +385,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,12 +727,12 @@ 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); @@ -731,25 +741,25 @@ describe('Terminal', () => { 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)); + await term.writeP(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(''); term.reset(); } }); - it('2 characters per cell over line end with autowrap', () => { + it('2 characters per cell over line end with autowrap', 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('a' + high + String.fromCharCode(i)); + await term.writeP('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); @@ -757,17 +767,17 @@ describe('Terminal', () => { term.reset(); } }); - it('2 characters per cell over line end without autowrap', () => { + it('2 characters per cell over line end without autowrap', 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('\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); @@ -775,12 +785,11 @@ describe('Terminal', () => { term.reset(); } }); - it('splitted surrogates', () => { + it('splitted surrogates', async () => { 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); @@ -793,16 +802,16 @@ 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); }); - 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); @@ -812,8 +821,8 @@ describe('Terminal', () => { expect(cell.getChars().length).eql(0); expect(cell.getWidth()).eql(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'); @@ -825,8 +834,8 @@ describe('Terminal', () => { expect(cell.getChars().length).eql(2); expect(cell.getWidth()).eql(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'); @@ -842,19 +851,19 @@ describe('Terminal', () => { describe('unicode - fullwidth characters', () => { const cell = new CellData(); - it('cursor movement even', () => { + it('cursor movement even', async () => { expect(term.buffer.x).eql(0); - term.writeSync('¥'); + await term.writeP('¥'); expect(term.buffer.x).eql(2); }); - it('cursor movement odd', () => { + it('cursor movement odd', async () => { term.buffer.x = 1; expect(term.buffer.x).eql(1); - term.writeSync('¥'); + await term.writeP('¥'); expect(term.buffer.x).eql(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) { @@ -872,9 +881,9 @@ describe('Terminal', () => { expect(cell.getChars().length).eql(1); expect(cell.getWidth()).eql(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)) { @@ -896,9 +905,9 @@ describe('Terminal', () => { expect(cell.getChars().length).eql(1); expect(cell.getWidth()).eql(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)) { @@ -920,8 +929,8 @@ describe('Terminal', () => { expect(cell.getChars().length).eql(2); expect(cell.getWidth()).eql(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) { @@ -939,9 +948,9 @@ describe('Terminal', () => { expect(cell.getChars().length).eql(2); expect(cell.getWidth()).eql(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)) { @@ -963,8 +972,8 @@ describe('Terminal', () => { expect(cell.getChars().length).eql(3); expect(cell.getWidth()).eql(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) { @@ -986,24 +995,24 @@ describe('Terminal', () => { 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'); + await term.writeP('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'); }); - 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('¥¥¥'); + await term.writeP('¥¥¥'); 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(''); @@ -1011,17 +1020,17 @@ describe('Terminal', () => { expect(term.buffer.lines.get(0)!.loadCell(15, cell).getChars()).eql(''); expect(term.buffer.lines.get(0)!.loadCell(79, cell).getChars()).eql('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'); + await term.writeP('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'); + await term.writeP('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('¥'); @@ -1043,85 +1052,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 +1144,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 +1155,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 +1175,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 +1187,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 +1207,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 +1219,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 +1234,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 +1246,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 +1265,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 +1276,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 +1286,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 +1303,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 +1314,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 +1332,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,7 +1355,7 @@ describe('Terminal', () => { 'aaaaaaaaaa', 'aaaaaaaaaa' ]; - terminal.writeSync(data.join('')); + await terminal.writeP(data.join('')); // brute force test with insane values expect(() => { for (let overscan = 0; overscan < 20; ++overscan) { @@ -1362,7 +1373,7 @@ describe('Terminal', () => { }); 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 +1381,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,22 +1401,22 @@ 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'); + await termNotConverting.writeP('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'); @@ -1413,7 +1424,7 @@ describe('Terminal', () => { // converting const termConverting = new TestTerminal({cols: 15, rows: 10, convertEol: true}); - termConverting.writeSync('Hello\nWorld'); + await termConverting.writeP('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'); @@ -1434,54 +1445,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 +1505,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 +1553,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 +1577,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 +1593,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/TestUtils.test.ts b/src/browser/TestUtils.test.ts index 6a4b4a0d..38f9c8f1 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 { diff --git a/src/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index 11e71bad..e67a1f26 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -125,7 +125,17 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { this._writeBuffer.write(data, callback); } + /** + * 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): void { + console.error('writeSync is unreliable and will be removed soon.'); this._writeBuffer.writeSync(data); } From 22d777c9f96c263377003cce82244a19a21f7209 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Fri, 22 Jan 2021 21:24:54 +0100 Subject: [PATCH 25/89] make linter happy --- src/common/CoreTerminal.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index e67a1f26..7b45a172 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -127,11 +127,11 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { /** * 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): void { From b07ca8bb2422d6ea5d4fb45527e5f715626bdf4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Fri, 22 Jan 2021 21:34:12 +0100 Subject: [PATCH 26/89] fix timeout issue on macos --- src/browser/Terminal.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/browser/Terminal.test.ts b/src/browser/Terminal.test.ts index 2e09f719..fe5b0bd5 100644 --- a/src/browser/Terminal.test.ts +++ b/src/browser/Terminal.test.ts @@ -753,7 +753,8 @@ describe('Terminal', () => { term.reset(); } }); - it('2 characters per cell over line end with autowrap', async () => { + 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) { @@ -767,7 +768,8 @@ describe('Terminal', () => { term.reset(); } }); - it('2 characters per cell over line end without autowrap', async () => { + 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) { @@ -785,7 +787,8 @@ describe('Terminal', () => { term.reset(); } }); - it('splitted surrogates', async () => { + 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) { From 354f3e03a2bb3aa364bef6346971b50dcd63b7ea Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Sat, 23 Jan 2021 10:19:03 +0800 Subject: [PATCH 27/89] Fix: inconsistent styles Co-authored-by: Daniel Imms --- addons/xterm-addon-serialize/src/SerializeAddon.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index ec8c6d0d..9641dc20 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -95,7 +95,7 @@ class StringSerializeHandler extends BaseSerializeHandler { private _lastContentCursorRow: number = 0; private _lastContentCursorCol: number = 0; - constructor(private _buffer1: IBuffer,private _terminal: Terminal) { + constructor(private _buffer1: IBuffer, private _terminal: Terminal) { super(_buffer1); } @@ -201,7 +201,7 @@ class StringSerializeHandler extends BaseSerializeHandler { this._nullCellCount = 0; } - private _diffStyle (cell: IBufferCell, oldCell: IBufferCell): number[] { + private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): number[] { const sgrSeq: number[] = []; const fgChanged = !equalFg(cell, oldCell); const bgChanged = !equalBg(cell, oldCell); @@ -337,7 +337,7 @@ class StringSerializeHandler extends BaseSerializeHandler { const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY; const realCursorCol = this._buffer1.cursorX; - const cursorMoved = (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol); + const cursorMoved = (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol); const moveRight = (offset: number): void => { if (offset > 0) { From cd501f9dcc445737160b982876146de0c67cb1ba Mon Sep 17 00:00:00 2001 From: mmis1000 Date: Sat, 23 Jan 2021 10:20:03 +0800 Subject: [PATCH 28/89] Update addons/xterm-addon-serialize/src/MyBufferCell.ts Co-authored-by: Daniel Imms --- addons/xterm-addon-serialize/src/MyBufferCell.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/addons/xterm-addon-serialize/src/MyBufferCell.ts b/addons/xterm-addon-serialize/src/MyBufferCell.ts index 56efcb3c..d635a424 100644 --- a/addons/xterm-addon-serialize/src/MyBufferCell.ts +++ b/addons/xterm-addon-serialize/src/MyBufferCell.ts @@ -4,7 +4,7 @@ import { IBufferCell } from 'xterm'; * This is a dummy buffer cell to hold data from real buffer cell */ export class MyBufferCell implements IBufferCell { - constructor (private _cell: IBufferCell) {} + constructor(private _cell: IBufferCell) {} private _width: number = this._cell.getWidth(); private _chars: string = this._cell.getChars(); private _code: number = this._cell.getCode(); From a2480bae51b86a368cea3784b4bcb07e9e139caa Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Sat, 23 Jan 2021 11:57:08 +0800 Subject: [PATCH 29/89] Remove dummy buffer cell in favor of just remember the location --- .../xterm-addon-serialize/src/MyBufferCell.ts | 96 ------------------- .../src/SerializeAddon.ts | 18 +++- 2 files changed, 14 insertions(+), 100 deletions(-) delete mode 100644 addons/xterm-addon-serialize/src/MyBufferCell.ts diff --git a/addons/xterm-addon-serialize/src/MyBufferCell.ts b/addons/xterm-addon-serialize/src/MyBufferCell.ts deleted file mode 100644 index d635a424..00000000 --- a/addons/xterm-addon-serialize/src/MyBufferCell.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { IBufferCell } from 'xterm'; - -/** - * This is a dummy buffer cell to hold data from real buffer cell - */ -export class MyBufferCell implements IBufferCell { - constructor(private _cell: IBufferCell) {} - private _width: number = this._cell.getWidth(); - private _chars: string = this._cell.getChars(); - private _code: number = this._cell.getCode(); - private _fgColorMode: number = this._cell.getFgColorMode(); - private _bgColorMode: number = this._cell.getBgColorMode(); - private _fgColor: number = this._cell.getFgColor(); - private _bgColor: number = this._cell.getBgColor(); - private _bold: number = this._cell.isBold(); - private _italic: number = this._cell.isItalic(); - private _dim: number = this._cell.isDim(); - private _underline: number = this._cell.isUnderline(); - private _blink: number = this._cell.isBlink(); - private _inverse: number = this._cell.isInverse(); - private _invisible: number = this._cell.isInvisible(); - private _fgRGB: boolean = this._cell.isFgRGB(); - private _bgRGB: boolean = this._cell.isBgRGB(); - private _fgPalette: boolean = this._cell.isFgPalette(); - private _bgPallette: boolean = this._cell.isBgPalette(); - private _fgDefault: boolean = this._cell.isFgDefault(); - private _bgDefault: boolean = this._cell.isBgDefault(); - private _attributeDefault: boolean = this._cell.isAttributeDefault(); - public getWidth(): number { - return this._width; - } - public getChars(): string { - return this._chars; - } - public getCode(): number { - return this._code; - } - public getFgColorMode(): number { - return this._fgColorMode; - } - public getBgColorMode(): number { - return this._bgColorMode; - } - public getFgColor(): number { - return this._fgColor; - } - public getBgColor(): number { - return this._bgColor; - } - public isBold(): number { - return this._bold; - } - public isItalic(): number { - return this._italic; - } - public isDim(): number { - return this._dim; - } - public isUnderline(): number { - return this._underline; - } - public isBlink(): number { - return this._blink; - } - public isInverse(): number { - return this._inverse; - } - public isInvisible(): number { - return this._invisible; - } - public isFgRGB(): boolean { - return this._fgRGB; - } - public isBgRGB(): boolean { - return this._bgRGB; - } - public isFgPalette(): boolean { - return this._fgPalette; - } - public isBgPalette(): boolean { - return this._bgPallette; - } - public isFgDefault(): boolean { - return this._fgDefault; - } - public isBgDefault(): boolean { - return this._bgDefault; - } - public isAttributeDefault(): boolean { - return this._attributeDefault; - } - - public static from(cell: IBufferCell): MyBufferCell { - return new MyBufferCell(cell); - } -} diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 9641dc20..60fe9624 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -6,7 +6,6 @@ */ import { Terminal, ITerminalAddon, IBuffer, IBufferCell } from 'xterm'; -import { MyBufferCell } from './MyBufferCell'; function constrain(value: number, low: number, high: number): number { return Math.max(low, Math.min(value, high)); @@ -86,8 +85,14 @@ class StringSerializeHandler extends BaseSerializeHandler { // 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: MyBufferCell = MyBufferCell.from(this._cursorStyle); + private _backgroundCell: IBufferCell = this._buffer1.getNullCell(); private _firstRow: number = 0; private _lastCursorRow: number = 0; @@ -122,7 +127,7 @@ class StringSerializeHandler extends BaseSerializeHandler { if (!isLastRow) { // Enable BCE if (row - this._firstRow >= this._terminal.rows) { - this._backgroundCell = MyBufferCell.from(this._cursorStyle); + this._buffer1.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol, this._backgroundCell); } // Fetch current line @@ -283,7 +288,12 @@ class StringSerializeHandler extends BaseSerializeHandler { this._currentRow += `\x1b[${sgrSeq.join(';')}m`; // update the last cursor style - this._buffer1.getLine(row)?.getCell(col, this._cursorStyle); + const line = this._buffer1.getLine(row); + if (line !== undefined) { + line.getCell(col, this._cursorStyle); + this._cursorStyleRow = row; + this._cursorStyleCol = col; + } } /** From db8e449a8a47b18b6ab9d2d439f550664918f17a Mon Sep 17 00:00:00 2001 From: nishant-d <58689354+nishant-d@users.noreply.github.com> Date: Sat, 23 Jan 2021 09:35:43 +0530 Subject: [PATCH 30/89] added Devtron's usages --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0e7df5ac..b46b7e93 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ 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. [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. From 079702282cb048a23d5d861f1a40336b1ace8e40 Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Sat, 23 Jan 2021 12:26:30 +0800 Subject: [PATCH 31/89] SerializeAddon: move test util into seperate file --- .../src/SerializeAddon.ts | 20 -------------- .../test/SerializeAddon.api.ts | 12 ++++----- .../test/SerializeAddonTestUtil.ts | 27 +++++++++++++++++++ demo/client.ts | 3 +++ 4 files changed, 36 insertions(+), 26 deletions(-) create mode 100644 addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 60fe9624..25fa9ad2 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -412,25 +412,5 @@ export class SerializeAddon implements ITerminalAddon { + alternativeScreenContent; } - // this is a util used only for test - private static _inspectBuffer(buffer: IBuffer): { x: number, y: number, data: any[][] } { - const lines: any[] = []; - - for (let i = 0; i < buffer.length; i++) { - /** - * Do this intentionally to get content of underlining source - */ - const bufferLine = (buffer.getLine(i)! as any)._line; - - lines.push(JSON.stringify(bufferLine)); - } - - return { - x: buffer.cursorX, - y: buffer.cursorY, - data: lines - }; - } - public dispose(): void { } } diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 5dc29d0d..339ac162 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -18,12 +18,12 @@ const writeRawSync = (page: any, str: string): Promise => writeSync(page, const testNormalScreenEqual = async (page: any, str: string): Promise => { await writeRawSync(page, str); - const originalBuffer = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const originalBuffer = await page.evaluate(`SerializeAddonTestUtil.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(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const newBuffer = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); // chai decides -0 and 0 are different number... // and firefox have a bug that output -0 for unknown reason @@ -51,11 +51,11 @@ describe('SerializeAddon', () => { it('produce different output when we call test util with different text', async function(): Promise { await writeRawSync(page, '12345'); - const buffer1 = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const buffer1 = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); await page.evaluate(`term.reset();`); await writeRawSync(page, '67890'); - const buffer2 = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const buffer2 = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); assert.throw(() => { assert.equal(JSON.stringify(buffer1), JSON.stringify(buffer2)); @@ -64,11 +64,11 @@ describe('SerializeAddon', () => { 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(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const buffer3 = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); await page.evaluate(`term.reset();`); await writeRawSync(page, '1234567890n12345'); - const buffer4 = await page.evaluate(`SerializeAddon._inspectBuffer(term.buffer.normal);`); + const buffer4 = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); assert.throw(() => { assert.equal(JSON.stringify(buffer3), JSON.stringify(buffer4)); diff --git a/addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts b/addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts new file mode 100644 index 00000000..23ac2237 --- /dev/null +++ b/addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBuffer } from 'xterm'; +export class SerializeAddonTestUtil { + // this is a util used only for test + public static inspectBuffer(buffer: IBuffer): { x: number, y: number, data: any[][] } { + const lines: any[] = []; + + for (let i = 0; i < buffer.length; i++) { + /** + * Do this intentionally to get content of underlining source + */ + const bufferLine = (buffer.getLine(i)! as any)._line; + + lines.push(JSON.stringify(bufferLine)); + } + + return { + x: buffer.cursorX, + y: buffer.cursorY, + data: lines + }; + } +} diff --git a/demo/client.ts b/demo/client.ts index 93b7c26c..27d1c297 100644 --- a/demo/client.ts +++ b/demo/client.ts @@ -13,6 +13,7 @@ import { AttachAddon } from '../addons/xterm-addon-attach/out/AttachAddon'; import { FitAddon } from '../addons/xterm-addon-fit/out/FitAddon'; import { SearchAddon, ISearchOptions } from '../addons/xterm-addon-search/out/SearchAddon'; import { SerializeAddon } from '../addons/xterm-addon-serialize/out/SerializeAddon'; +import { SerializeAddonTestUtil } from '../addons/xterm-addon-serialize/out-test/SerializeAddonTestUtil'; import { WebLinksAddon } from '../addons/xterm-addon-web-links/out/WebLinksAddon'; import { WebglAddon } from '../addons/xterm-addon-webgl/out/WebglAddon'; import { Unicode11Addon } from '../addons/xterm-addon-unicode11/out/Unicode11Addon'; @@ -38,6 +39,7 @@ export interface IWindowWithTerminal extends Window { FitAddon?: typeof FitAddon; SearchAddon?: typeof SearchAddon; SerializeAddon?: typeof SerializeAddon; + SerializeAddonTestUtil?: typeof SerializeAddonTestUtil; WebLinksAddon?: typeof WebLinksAddon; WebglAddon?: typeof WebglAddon; Unicode11Addon?: typeof Unicode11Addon; @@ -132,6 +134,7 @@ if (document.location.pathname === '/test') { window.FitAddon = FitAddon; window.SearchAddon = SearchAddon; window.SerializeAddon = SerializeAddon; + window.SerializeAddonTestUtil = SerializeAddonTestUtil; window.Unicode11Addon = Unicode11Addon; window.WebLinksAddon = WebLinksAddon; window.WebglAddon = WebglAddon; From 93aab95f7bd19e3b1d2fe65f6108aa92cfc75cda Mon Sep 17 00:00:00 2001 From: Ken Aoki Date: Sat, 23 Jan 2021 04:39:57 +0000 Subject: [PATCH 32/89] filter U+FEFF (BOM) when decoding input data --- src/common/input/TextDecoder.test.ts | 25 +++++++++++++++++++++---- src/common/input/TextDecoder.ts | 8 ++++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/common/input/TextDecoder.test.ts b/src/common/input/TextDecoder.test.ts index 92b0e03a..e9299021 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', () => { diff --git a/src/common/input/TextDecoder.ts b/src/common/input/TextDecoder.ts index 6ecab011..9df26f59 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; @@ -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; From 3d941f2fdf08190aa347f9015a737d83718b747b Mon Sep 17 00:00:00 2001 From: Ken Aoki Date: Sat, 23 Jan 2021 11:42:16 +0000 Subject: [PATCH 33/89] add BOM skip logic --- src/common/input/TextDecoder.test.ts | 13 +++++++++++++ src/common/input/TextDecoder.ts | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/common/input/TextDecoder.test.ts b/src/common/input/TextDecoder.test.ts index e9299021..da1760a2 100644 --- a/src/common/input/TextDecoder.test.ts +++ b/src/common/input/TextDecoder.test.ts @@ -232,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 9df26f59..715e9197 100644 --- a/src/common/input/TextDecoder.ts +++ b/src/common/input/TextDecoder.ts @@ -192,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; } From 2f07ed997605d9c289c8a6cc5c3a2a8bd86e11c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Sat, 23 Jan 2021 13:05:57 +0100 Subject: [PATCH 34/89] simplify stack save in parser --- src/common/InputHandler.ts | 18 ++- src/common/parser/EscapeSequenceParser.ts | 173 +++++++++------------- src/common/parser/Types.d.ts | 20 +++ 3 files changed, 108 insertions(+), 103 deletions(-) diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index 001c9995..099cdff7 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -460,7 +460,9 @@ export class InputHandler extends Disposable implements IInputHandler { super.dispose(); } - // FIXME: cleanup async handling + /** + * Async parse support. + */ private _parseStack = { paused: false, cursorStartX: 0, @@ -468,7 +470,6 @@ export class InputHandler extends Disposable implements IInputHandler { decodedLength: 0, position: 0 }; - private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void { this._parseStack.paused = true; this._parseStack.cursorStartX = cursorStartX; @@ -477,6 +478,19 @@ export class InputHandler extends Disposable implements IInputHandler { this._parseStack.position = position; } + /** + * 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: Never call this directly for a running terminal instance in production. + * Always use `Terminal.write`, which provides in-band blocking and correct exection order. + */ public parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise { let result: void | Promise; let buffer = this._bufferService.buffer; diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 3635ca78..e56655ae 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'; @@ -437,44 +437,28 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this.precedingCodepoint = 0; } - // FIXME: cleanup async handling - private _parseStack: { - paused: boolean; - type: 'ESC' | 'CSI'; // FIXME: support for DCS and OSC - handlers: CsiHandlerType[] | EscHandlerType[]; - handlerPos: number; - transition: number; - currentState: ParserState; - collect: number; - pos: number; - } = { - paused: false, - type: 'ESC', + /** + * Async parse support. + */ + private _parseStack: IParserStackState = { + state: ParserStackType.NONE, handlers: [], handlerPos: 0, transition: 0, - currentState: 0, - collect: 0, - pos: 0 + chunkPos: 0 }; - private _preserveStack( - type: 'ESC' | 'CSI', - handlers: CsiHandlerType[] | EscHandlerType[], + state: ParserStackType, + handlers: ResumableHandlersType, handlerPos: number, transition: number, - currentState: ParserState, - collect: number, - pos: number - ): void { - this._parseStack.paused = true; - this._parseStack.type = type; + chunkPos: number): void + { + this._parseStack.state = state; this._parseStack.handlers = handlers; this._parseStack.handlerPos = handlerPos; this._parseStack.transition = transition; - this._parseStack.currentState = currentState; - this._parseStack.collect = collect; - this._parseStack.pos = pos; + this._parseStack.chunkPos = chunkPos; } /** @@ -494,22 +478,12 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP 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 res: any; let start = 0; - if (this._parseStack.paused) { - const handlers = this._parseStack.handlers; + let handlerResult: any; + + // resume from async handler + if (this._parseStack.state) { let handlerPos = this._parseStack.handlerPos - 1; - transition = this._parseStack.transition; - currentState = this._parseStack.currentState; - collect = this._parseStack.collect; - start = this._parseStack.pos; // we have to resume the old handler loop if: // - return value of the promise was `false` @@ -517,24 +491,25 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP // FIXME: removing handlers from within a handler of the same sequence // is not supported atm (also true for sync handlers)!! if (promiseResult === false && handlerPos > -1) { - switch (this._parseStack.type) { - case 'CSI': + const handlers = this._parseStack.handlers; + switch (this._parseStack.state) { + case ParserStackType.CSI: for (; handlerPos >= 0; handlerPos--) { - if ((res = (handlers as CsiHandlerType[])[handlerPos](params)) !== false) { - if (res instanceof Promise) { + if ((handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params)) !== false) { + if (handlerResult instanceof Promise) { this._parseStack.handlerPos = handlerPos; - return res; + return handlerResult; } break; } } break; - case 'ESC': + case ParserStackType.ESC: for (; handlerPos >= 0; handlerPos--) { - if ((res = (handlers as EscHandlerType[])[handlerPos]()) !== false) { - if (res instanceof Promise) { + if ((handlerResult = (handlers as EscHandlerType[])[handlerPos]()) !== false) { + if (handlerResult instanceof Promise) { this._parseStack.handlerPos = handlerPos; - return res; + return handlerResult; } break; } @@ -543,20 +518,20 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } } // cleanup before continuing with the main loop + this._parseStack.state = ParserStackType.NONE; + start = this._parseStack.chunkPos + 1; this.precedingCodepoint = 0; - this._parseStack.paused = false; - start++; - currentState = transition & TableAccess.TRANSITION_STATE_MASK; + this.currentState = this._parseStack.transition & TableAccess.TRANSITION_STATE_MASK; } - // console.log('startPos', start, length); + // continue with main sync loop // process input string 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 @@ -596,9 +571,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; @@ -606,19 +581,20 @@ 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 ((res = handlers[j](params)) === true) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + if ((handlerResult = handlers[j](this._params)) === true) { break; - } else if (res instanceof Promise) { - this._preserveStack('CSI', handlers, j, transition, currentState, collect, i); - return res; + } 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; @@ -627,94 +603,89 @@ 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 ((res = handlersEsc[jj]()) === true) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + if ((handlerResult = handlersEsc[jj]()) === true) { break; - } else if (res instanceof Promise) { - this._preserveStack('ESC', handlersEsc, jj, transition, currentState, collect, i); - return res; + } 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); + this._dcsParser.unhook(code !== 0x18 && code !== 0x1a); 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 < NON_ASCII_PRINTABLE)) { - osc.put(data, i, j); + this._oscParser.put(data, i, j); i = j - 1; break; } } break; case ParserAction.OSC_END: - osc.end(code !== 0x18 && code !== 0x1a); + this._oscParser.end(code !== 0x18 && code !== 0x1a); 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/Types.d.ts b/src/common/parser/Types.d.ts index 9db38fbd..002fc8ed 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -5,6 +5,7 @@ import { IDisposable } from 'common/Types'; import { ParserState } from 'common/parser/Constants'; +import { OscParser } from 'common/parser/OscParser'; /** sequence params serialized to js arrays */ export type ParamsArray = (number | number[])[]; @@ -237,3 +238,22 @@ export interface IFunctionIdentifier { export interface IHandlerCollection { [key: string]: T[]; } + +/** + * Types for async parser support. + */ +export const enum ParserStackType { + NONE = 0, + CSI, + ESC, + OSC, + DCS +} +export type ResumableHandlersType = CsiHandlerType[] | EscHandlerType[]; +export interface IParserStackState { + state: ParserStackType; + handlers: ResumableHandlersType; + handlerPos: number; + transition: number; + chunkPos: number; +} From d3c9f70bec852b0abf54c177afb80bcef44af30b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Sat, 23 Jan 2021 17:09:43 +0100 Subject: [PATCH 35/89] replace expect testing with assert --- src/browser/Terminal.test.ts | 277 ++++---- src/common/Clone.test.ts | 4 +- src/common/InputHandler.test.ts | 150 +++-- src/common/buffer/BufferLine.test.ts | 168 ++--- .../parser/EscapeSequenceParser.test.ts | 620 +++++++++--------- 5 files changed, 635 insertions(+), 584 deletions(-) diff --git a/src/browser/Terminal.test.ts b/src/browser/Terminal.test.ts index 8626be09..8f919302 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'; @@ -75,7 +75,7 @@ describe('Terminal', () => { 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 +89,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 +103,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(); @@ -724,10 +723,10 @@ describe('Terminal', () => { for (let i = 0xDC00; i <= 0xDCFF; ++i) { term.writeSync(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(); } }); @@ -737,9 +736,9 @@ describe('Terminal', () => { 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(''); + 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(); } }); @@ -750,10 +749,10 @@ describe('Terminal', () => { 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(''); + 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(); } }); @@ -769,9 +768,9 @@ describe('Terminal', () => { } term.writeSync('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(); } }); @@ -782,10 +781,10 @@ describe('Terminal', () => { term.writeSync(high); term.writeSync(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(); } }); @@ -796,81 +795,81 @@ describe('Terminal', () => { it('café', () => { term.writeSync('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', () => { term.buffer.x = term.cols - 1 - 3; term.writeSync('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')); 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')); 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); + assert.equal(term.buffer.x, 0); term.writeSync('¥'); - expect(term.buffer.x).eql(2); + assert.equal(term.buffer.x, 2); }); it('cursor movement odd', () => { term.buffer.x = 1; - expect(term.buffer.x).eql(1); + assert.equal(term.buffer.x, 1); term.writeSync('¥'); - expect(term.buffer.x).eql(3); + assert.equal(term.buffer.x, 3); }); it('line of ¥ even', () => { term.writeSync(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', () => { term.buffer.x = 1; @@ -878,23 +877,23 @@ describe('Terminal', () => { 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', () => { term.buffer.x = 1; @@ -902,42 +901,42 @@ describe('Terminal', () => { 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')); 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', () => { term.buffer.x = 1; @@ -945,42 +944,42 @@ describe('Terminal', () => { 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')); 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); }); }); @@ -992,11 +991,11 @@ describe('Terminal', () => { 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'); + 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)); @@ -1004,12 +1003,12 @@ describe('Terminal', () => { 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'); + 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('¥')); @@ -1017,15 +1016,15 @@ describe('Terminal', () => { 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 + 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 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 + 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 }); }); @@ -1346,7 +1345,7 @@ describe('Terminal', () => { ]; terminal.writeSync(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,7 +1356,7 @@ describe('Terminal', () => { } } } - }).to.not.throw(); + }); }); }); @@ -1406,18 +1405,18 @@ describe('Terminal', () => { // 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'); + 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'); + 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[] { 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/InputHandler.test.ts b/src/common/InputHandler.test.ts index 4c0d8559..e1fcd727 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'; @@ -136,7 +136,16 @@ describe('InputHandler', () => { it('insertChars', function(): void { 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')); @@ -144,36 +153,45 @@ describe('InputHandler', () => { inputHandler.parse(Array(bufferService.cols - 9).join('a')); inputHandler.parse('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 { 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')); @@ -181,39 +199,49 @@ describe('InputHandler', () => { inputHandler.parse(Array(bufferService.cols - 9).join('a')); inputHandler.parse('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 { 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')); @@ -224,24 +252,33 @@ describe('InputHandler', () => { 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 { 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')); @@ -250,7 +287,7 @@ describe('InputHandler', () => { 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 +296,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'), @@ -278,7 +315,7 @@ describe('InputHandler', () => { 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 +324,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), [ '', '', '', @@ -306,7 +343,7 @@ describe('InputHandler', () => { 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 +352,7 @@ describe('InputHandler', () => { Array(bufferService.cols + 1).join(' '), Array(bufferService.cols + 1).join(' ') ]); - expect(termContent(bufferService, true)).eql([ + assert.deepEqual(termContent(bufferService, true), [ '', '', '', @@ -334,11 +371,11 @@ describe('InputHandler', () => { // 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; @@ -349,16 +386,25 @@ describe('InputHandler', () => { // 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); @@ -383,48 +429,48 @@ describe('InputHandler', () => { }); 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'); + 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'); + 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'); + 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(''); + 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'); + 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); + assert.equal(bufferService.buffer.lines.get(0)!.loadCell(0, new CellData()).fg, DEFAULT_ATTR_DATA.fg); handler.parse('\x1b[?1049h\x1b[uTEST'); - expect(bufferService.buffer.translateBufferLineToString(1, true)).to.equal('TEST'); + 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'); // 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); }); }); 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/parser/EscapeSequenceParser.test.ts b/src/common/parser/EscapeSequenceParser.test.ts index 468dc934..f4ec5025 100644 --- a/src/common/parser/EscapeSequenceParser.test.ts +++ b/src/common/parser/EscapeSequenceParser.test.ts @@ -5,7 +5,7 @@ import { IParsingState, IParams, ParamsArray, IOscParser, IOscHandler, OscFallbackHandlerType, IFunctionIdentifier } 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'; @@ -97,38 +97,38 @@ class TestEscapeSequenceParser extends EscapeSequenceParser { // 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 +191,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 +233,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 +269,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 +303,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 +329,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 +355,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 +413,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 +428,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 +489,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 +565,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 +655,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 +669,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 +703,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 +717,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 +744,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 +783,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 +820,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 +878,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 +913,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 +988,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 +1015,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 +1025,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 +1048,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 +1056,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 +1091,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 +1127,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,25 +1187,25 @@ 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 { + it('ESC handler', () => { parser2.registerEscHandler({intermediates: '%', final: 'G'}, function (): boolean { esc.push('%G'); return true; @@ -1215,43 +1215,43 @@ describe('EscapeSequenceParser', function (): void { return true; }); parse(parser2, INPUT); - chai.expect(esc).eql(['%G', 'E']); + 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']); + 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.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.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.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.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[] = []; @@ -1259,14 +1259,14 @@ describe('EscapeSequenceParser', function (): void { 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.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.registerEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); return true; }); @@ -1274,21 +1274,21 @@ describe('EscapeSequenceParser', function (): void { dispo.dispose(); dispo.dispose(); parse(parser2, INPUT); - chai.expect(esc).eql(['default - %G']); + assert.deepEqual(esc, ['default - %G']); }); }); - it('CSI handler', function (): 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], '']]); + 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', () => { @@ -1296,16 +1296,16 @@ describe('EscapeSequenceParser', function (): void { 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.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][] = []; @@ -1314,9 +1314,9 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1325,9 +1325,9 @@ describe('EscapeSequenceParser', function (): void { 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[] = []; @@ -1335,7 +1335,7 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1343,8 +1343,8 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1353,11 +1353,11 @@ describe('EscapeSequenceParser', function (): void { 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 { + it('EXECUTE handler', () => { parser2.setExecuteHandler('\n', function (): boolean { exe.push('\n'); return true; @@ -1367,25 +1367,25 @@ describe('EscapeSequenceParser', function (): void { 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 { + 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', () => { @@ -1393,16 +1393,16 @@ describe('EscapeSequenceParser', function (): void { 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.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][] = []; @@ -1411,9 +1411,9 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1422,9 +1422,9 @@ describe('EscapeSequenceParser', function (): void { 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[] = []; @@ -1432,7 +1432,7 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1440,8 +1440,8 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1450,11 +1450,11 @@ describe('EscapeSequenceParser', function (): void { 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 { + it('DCS handler', () => { parser2.registerDcsHandler({intermediates: '+', final: 'p'}, { hook: function (params: IParams): void { dcs.push(['hook', '', params.toArray(), 0]); @@ -1473,7 +1473,7 @@ describe('EscapeSequenceParser', function (): void { }); 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'] @@ -1483,7 +1483,7 @@ describe('EscapeSequenceParser', function (): void { 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\\'; @@ -1492,14 +1492,14 @@ describe('EscapeSequenceParser', function (): void { 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.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][] = []; @@ -1507,7 +1507,7 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1515,7 +1515,7 @@ describe('EscapeSequenceParser', function (): void { 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[] = []; @@ -1523,7 +1523,7 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1531,7 +1531,7 @@ describe('EscapeSequenceParser', function (): void { 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][] = []; @@ -1540,17 +1540,17 @@ describe('EscapeSequenceParser', function (): void { 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, @@ -1562,7 +1562,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', () => { @@ -1570,46 +1570,46 @@ 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.registerEscHandler({final}, () => true); }, '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.registerEscHandler({final: '\x2f'}, () => true); }, 'final must be in range 48 .. 126'); - chai.assert.throws(() => { parser.registerEscHandler({final: '\x7f'}, () => true); }, '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', () => { @@ -1623,7 +1623,7 @@ describe('EscapeSequenceParser', function (): void { 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[] = []; @@ -1641,7 +1641,10 @@ 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[] = []; @@ -1659,14 +1662,17 @@ 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'] + ] + ); }); }); }); From 68b7f885235b22d20de40c4085d9582070264b9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Sun, 24 Jan 2021 17:09:16 +0100 Subject: [PATCH 36/89] async parser tests for CSI and ESC --- .../parser/EscapeSequenceParser.test.ts | 575 +++++++++++++++--- src/common/parser/EscapeSequenceParser.ts | 48 +- src/common/parser/Types.d.ts | 1 + 3 files changed, 523 insertions(+), 101 deletions(-) diff --git a/src/common/parser/EscapeSequenceParser.test.ts b/src/common/parser/EscapeSequenceParser.test.ts index f4ec5025..56d4c93e 100644 --- a/src/common/parser/EscapeSequenceParser.test.ts +++ b/src/common/parser/EscapeSequenceParser.test.ts @@ -3,7 +3,7 @@ * @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 { assert } from 'chai'; import { StringToUtf32, stringFromCodePoint, utf32ToString } from 'common/input/TextDecoder'; @@ -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 = ''; @@ -92,6 +92,21 @@ 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 && this._trackStack) { + this.trackedStack.push({ ...this.parseStack }); + } + return result; + } } // test object to collect parser actions and compare them with expected values @@ -1206,71 +1221,71 @@ describe('EscapeSequenceParser', () => { assert.equal(print, ''); }); it('ESC handler', () => { - parser2.registerEscHandler({intermediates: '%', final: 'G'}, function (): boolean { + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, function (): boolean { esc.push('%G'); return true; }); - parser2.registerEscHandler({final: 'E'}, function (): boolean { + parser2.registerEscHandler({ final: 'E' }, function (): boolean { esc.push('E'); return true; }); parse(parser2, INPUT); assert.deepEqual(esc, ['%G', 'E']); - parser2.clearEscHandler({intermediates: '%', final: 'G'}); - parser2.clearEscHandler({intermediates: '%', final: 'G'}); // should not throw + parser2.clearEscHandler({ intermediates: '%', final: 'G' }); + parser2.clearEscHandler({ intermediates: '%', final: 'G' }); // should not throw clearAccu(); parse(parser2, INPUT); assert.deepEqual(esc, ['E']); - parser2.clearEscHandler({final: 'E'}); + parser2.clearEscHandler({ final: 'E' }); clearAccu(); parse(parser2, INPUT); assert.deepEqual(esc, []); }); describe('ESC custom handlers', () => { it('prevent fallback', () => { - 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('default - %G'); return true; }); + parser2.registerEscHandler({ intermediates: '%', final: 'G' }, () => { esc.push('custom - %G'); return true; }); parse(parser2, INPUT); assert.deepEqual(esc, ['custom - %G']); }); it('allow fallback', () => { - parser2.registerEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); return true; }); - parser2.registerEscHandler({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); assert.deepEqual(esc, ['custom - %G', 'default - %G']); }); it('Multiple custom handlers fallback once', () => { - 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; }); + 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); assert.deepEqual(esc, ['custom2 - %G', 'custom - %G']); }); it('Multiple custom handlers no fallback', () => { - 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; }); + 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); assert.deepEqual(esc, ['custom2 - %G']); }); it('Execution order should go from latest handler down to the original', () => { const order: number[] = []; - 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; }); + 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'); assert.deepEqual(order, [3, 2, 1]); }); it('Dispose should work', () => { - parser2.registerEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); return true; }); - const dispo = parser2.registerEscHandler({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); assert.deepEqual(esc, ['default - %G']); }); it('Should not corrupt the parser when dispose is called twice', () => { - parser2.registerEscHandler({intermediates: '%', final: 'G'}, () => { esc.push('default - %G'); return true; }); - const dispo = parser2.registerEscHandler({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); @@ -1278,14 +1293,14 @@ describe('EscapeSequenceParser', () => { }); }); it('CSI handler', () => { - parser2.registerCsiHandler({final: 'm'}, function (params: IParams): boolean { + parser2.registerCsiHandler({ final: 'm' }, function (params: IParams): boolean { csi.push(['m', params.toArray(), '']); return true; }); parse(parser2, INPUT); assert.deepEqual(csi, [['m', [1, 31], ''], ['m', [0], '']]); - parser2.clearCsiHandler({final: 'm'}); - parser2.clearCsiHandler({final: 'm'}); // should not throw + parser2.clearCsiHandler({ final: 'm' }); + parser2.clearCsiHandler({ final: 'm' }); // should not throw clearAccu(); parse(parser2, INPUT); assert.deepEqual(csi, []); @@ -1293,16 +1308,16 @@ describe('EscapeSequenceParser', () => { describe('CSI custom handlers', () => { it('Prevent fallback', () => { const csiCustom: [string, ParamsArray, string][] = []; - 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 => { csi.push(['m', params.toArray(), '']); return true; }); + parser2.registerCsiHandler({ final: 'm' }, params => { csiCustom.push(['m', params.toArray(), '']); return true; }); parse(parser2, INPUT); 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.registerCsiHandler({final: 'm'}, params => { csi.push(['m', params.toArray(), '']); return true; }); - parser2.registerCsiHandler({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); assert.deepEqual(csi, [['m', [1, 31], ''], ['m', [0], '']], 'Should fallback to original handler'); assert.deepEqual(csiCustom, [['m', [1, 31], ''], ['m', [0], '']]); @@ -1310,9 +1325,9 @@ describe('EscapeSequenceParser', () => { it('Multiple custom handlers fallback once', () => { const csiCustom: [string, ParamsArray, string][] = []; const csiCustom2: [string, ParamsArray, string][] = []; - 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; }); + 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); assert.deepEqual(csi, [], 'Should not fallback to original handler'); assert.deepEqual(csiCustom, [['m', [1, 31], ''], ['m', [0], '']]); @@ -1321,9 +1336,9 @@ describe('EscapeSequenceParser', () => { it('Multiple custom handlers no fallback', () => { const csiCustom: [string, ParamsArray, string][] = []; const csiCustom2: [string, ParamsArray, string][] = []; - 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; }); + 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); assert.deepEqual(csi, [], 'Should not fallback to original handler'); assert.deepEqual(csiCustom, [], 'Should not fallback once'); @@ -1331,16 +1346,16 @@ describe('EscapeSequenceParser', () => { }); it('Execution order should go from latest handler down to the original', () => { const order: number[] = []; - 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; }); + 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'); assert.deepEqual(order, [3, 2, 1]); }); it('Dispose should work', () => { const csiCustom: [string, ParamsArray, string][] = []; - 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; }); + 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); assert.deepEqual(csi, [['m', [1, 31], ''], ['m', [0], '']]); @@ -1348,8 +1363,8 @@ describe('EscapeSequenceParser', () => { }); it('Should not corrupt the parser when dispose is called twice', () => { const csiCustom: [string, ParamsArray, string][] = []; - 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; }); + 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); @@ -1455,7 +1470,7 @@ describe('EscapeSequenceParser', () => { }); }); it('DCS handler', () => { - parser2.registerDcsHandler({intermediates: '+', final: 'p'}, { + parser2.registerDcsHandler({ intermediates: '+', final: 'p' }, { hook: function (params: IParams): void { dcs.push(['hook', '', params.toArray(), 0]); }, @@ -1478,8 +1493,8 @@ describe('EscapeSequenceParser', () => { ['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'); @@ -1489,54 +1504,54 @@ describe('EscapeSequenceParser', () => { const DCS_INPUT = '\x1bP1;2;3+pabc\x1b\\'; it('Prevent fallback', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - 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(['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); assert.deepEqual(dcsCustom, [['B', [1, 2, 3], 'abc']]); }); it('Allow fallback', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - 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; })); + 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); 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.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; })); + 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); 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.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; })); + 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); assert.deepEqual(dcsCustom, [['C', [1, 2, 3], 'abc']]); }); it('Execution order should go from latest handler down to the original', () => { const order: number[] = []; - 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; })); + 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); assert.deepEqual(order, [3, 2, 1]); }); it('Dispose should work', () => { const dcsCustom: [string, (number | number[])[], string][] = []; - 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; })); + 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); 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.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; })); + 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); @@ -1570,54 +1585,54 @@ describe('EscapeSequenceParser', () => { it('prefix range 0x3c .. 0x3f, one byte', () => { for (let i = 0x3c; i <= 0x3f; ++i) { const c = String.fromCharCode(i); - assert.equal(parser.identToString(parser.identifier({prefix: c, final: 'z'})), c + 'z'); + assert.equal(parser.identToString(parser.identifier({ prefix: c, final: 'z' })), c + 'z'); } - 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'); + 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); - assert.equal(parser.identToString(parser.identifier({intermediates: c + c, final: 'z'})), c + c + 'z'); + assert.equal(parser.identToString(parser.identifier({ intermediates: c + c, final: 'z' })), c + c + 'z'); } - 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'); + 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); - assert.equal(parser.identToString(parser.identifier({final: c})), c); + assert.equal(parser.identToString(parser.identifier({ final: c })), c); } - 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'); + 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; - assert.doesNotThrow(() => { handler = parser.registerEscHandler({final}, () => true); }, '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(); } - 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'); + 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', () => { - 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'); + 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.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; }); + 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(); @@ -1627,12 +1642,12 @@ describe('EscapeSequenceParser', () => { }); it('CSI', () => { const callstack: any[] = []; - 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; }); + 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(); @@ -1648,12 +1663,12 @@ describe('EscapeSequenceParser', () => { }); it('DCS', () => { const callstack: any[] = []; - 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; })); + 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(); @@ -1678,3 +1693,365 @@ describe('EscapeSequenceParser', () => { }); // 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 | $> | OSC 1;foo=bar ST + // 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$>\x1b]1;foo=bar\x1b\\'; + 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', '$>'], + ['OSC 1', 'foo=bar'] + ]; + 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; })); + }); + + it('sync handlers keep 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(data => { callstack.push(['OSC 1', data]); 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'); + // FIXME: come up with a good recovery strategy + }); + 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] + ]); + }); + 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', '>'], + ['OSC 1', 'foo=bar'] + ]; + + // 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] + ]); + }); + 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] + ]); + 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] + ]); + 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] + ]); + 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] + ]); + }); + 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] + ]); + 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] + ]); + 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] + ]); + 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] + ]); + }); + 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] + ]); + 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] + ]); + 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] + ]); + }); + }); +}); diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index e56655ae..1ac1a22b 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -440,14 +440,14 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP /** * Async parse support. */ - private _parseStack: IParserStackState = { + protected _parseStack: IParserStackState = { state: ParserStackType.NONE, handlers: [], handlerPos: 0, transition: 0, chunkPos: 0 }; - private _preserveStack( + protected _preserveStack( state: ParserStackType, handlers: ResumableHandlersType, handlerPos: number, @@ -474,6 +474,39 @@ 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. + * + * FIXME: to be discussed + * While awaiting parse promises the terminal buffer state may not change. + * --> Implement lock semantics / promise chaining on buffer alterations? Waah, pandora's box ;) + * --> Maybe easier: Give up on non-mutating rule for async handlers... + * (needs explanation in docs about exact executor/thenable/worker execution contexts) + * + * Example for proper parsing of multiple chunks: + * + * ```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, promiseResult?: boolean): void | Promise { let code = 0; @@ -483,6 +516,17 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP // resume from async handler if (this._parseStack.state) { + if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) { + /** + * Reject further parsing on improper continuation after pausing. + * This will happen with sync parse calls not awaiting a returned promise. + * It is a really bad condition with screwed up execution order, + * therefore we exit hard with an exception. + * FIXME: Do we need a method to escape from this broken parser state? (hard to achieve properly) + */ + this._parseStack.state = ParserStackType.FAIL; + throw new Error('improper continuation due to previous async handler, giving up parsing'); + } let handlerPos = this._parseStack.handlerPos - 1; // we have to resume the old handler loop if: diff --git a/src/common/parser/Types.d.ts b/src/common/parser/Types.d.ts index 002fc8ed..f6db77fa 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -244,6 +244,7 @@ export interface IHandlerCollection { */ export const enum ParserStackType { NONE = 0, + FAIL, CSI, ESC, OSC, From 54bb0ee18999df013d12aff9ccbb52aa943395ba Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Mon, 25 Jan 2021 10:52:48 +0800 Subject: [PATCH 37/89] SerializeAddon: comment the intent of several check --- .../src/SerializeAddon.ts | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts index 25fa9ad2..0caaaa03 100644 --- a/addons/xterm-addon-serialize/src/SerializeAddon.ts +++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts @@ -149,22 +149,32 @@ class StringSerializeHandler extends BaseSerializeHandler { 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) ) { @@ -179,20 +189,20 @@ class StringSerializeHandler extends BaseSerializeHandler { // move back and erase next line head rowSeparator += '\x1b[1D\x1b[1X'; - // do these because we filled the last several null slot, which we shouldn't 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 even it is invisible - // without this, wrap will be missing - this._lastContentCursorRow = row + 1; - this._lastContentCursorCol = 0; } + // 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; From 0b09f0bafd574171846b995648d3beac966c19e1 Mon Sep 17 00:00:00 2001 From: jeanp413 Date: Sun, 24 Jan 2021 23:17:36 -0500 Subject: [PATCH 38/89] Fixes #3221 --- addons/xterm-addon-webgl/src/WebglRenderer.ts | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/addons/xterm-addon-webgl/src/WebglRenderer.ts b/addons/xterm-addon-webgl/src/WebglRenderer.ts index 9f982165..52d1eda4 100644 --- a/addons/xterm-addon-webgl/src/WebglRenderer.ts +++ b/addons/xterm-addon-webgl/src/WebglRenderer.ts @@ -116,12 +116,9 @@ export class WebglRenderer extends Disposable implements IRenderer { this._refreshCharAtlas(); - this._rectangleRenderer.updateSelection(this._model.selection); - this._glyphRenderer.updateSelection(this._model); - // Force a full refresh this._model.clear(); - this._model.clearSelection(); + this._updateSelectionModel(undefined, undefined); } public onDevicePixelRatioChange(): void { @@ -159,7 +156,7 @@ export class WebglRenderer extends Disposable implements IRenderer { // Force a full refresh this._model.clear(); - this._model.clearSelection(); + this._updateSelectionModel(undefined, undefined); } public onCharSizeChanged(): void { @@ -179,9 +176,6 @@ export class WebglRenderer extends Disposable implements IRenderer { 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 }); } @@ -220,7 +214,6 @@ 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 }); } @@ -253,7 +246,7 @@ export class WebglRenderer extends Disposable implements IRenderer { // 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 +296,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 +321,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 +333,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); } /** From c994c67dd9c667763de15b9e8efa8655c29a34bc Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Fri, 29 Jan 2021 09:14:31 -0800 Subject: [PATCH 39/89] v4.10.0 --- addons/xterm-addon-fit/package.json | 2 +- addons/xterm-addon-ligatures/package.json | 2 +- addons/xterm-addon-search/package.json | 2 +- package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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-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-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/package.json b/package.json index 59902931..445d4833 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.10.0", "main": "lib/xterm.js", "style": "css/xterm.css", "types": "typings/xterm.d.ts", From a0903fbf9b45e35616fce436d15ac27d2f0f6439 Mon Sep 17 00:00:00 2001 From: hantatsang Date: Sun, 31 Jan 2021 11:43:59 +1100 Subject: [PATCH 40/89] terminal.open: support webcomponent in dom node check --- src/browser/Terminal.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/browser/Terminal.ts b/src/browser/Terminal.ts index 06ac57f3..b0964c21 100644 --- a/src/browser/Terminal.ts +++ b/src/browser/Terminal.ts @@ -386,7 +386,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'); } From 0a4b403f6a11d5bda043376c3d75911e5bf1a326 Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Mon, 1 Feb 2021 09:28:26 -0800 Subject: [PATCH 41/89] Fix Demo Server debug launch config --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 59902931..819b3be3 100644 --- a/package.json +++ b/package.json @@ -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", From 46c93f1b63d61a841492648d40745bcd4c3f5c18 Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Mon, 1 Feb 2021 09:34:38 -0800 Subject: [PATCH 42/89] Move util function into page.evaluate --- .../test/SerializeAddon.api.ts | 25 ++++++++++++----- .../test/SerializeAddonTestUtil.ts | 27 ------------------- demo/client.ts | 3 --- 3 files changed, 19 insertions(+), 36 deletions(-) delete mode 100644 addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 339ac162..47af9d91 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -18,12 +18,12 @@ const writeRawSync = (page: any, str: string): Promise => writeSync(page, const testNormalScreenEqual = async (page: any, str: string): Promise => { await writeRawSync(page, str); - const originalBuffer = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); + 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(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); + 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 @@ -43,6 +43,19 @@ 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 + }; + } `); }); @@ -51,11 +64,11 @@ describe('SerializeAddon', () => { it('produce different output when we call test util with different text', async function(): Promise { await writeRawSync(page, '12345'); - const buffer1 = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); + const buffer1 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); await page.evaluate(`term.reset();`); await writeRawSync(page, '67890'); - const buffer2 = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); + const buffer2 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); assert.throw(() => { assert.equal(JSON.stringify(buffer1), JSON.stringify(buffer2)); @@ -64,11 +77,11 @@ describe('SerializeAddon', () => { 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(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); + const buffer3 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); await page.evaluate(`term.reset();`); await writeRawSync(page, '1234567890n12345'); - const buffer4 = await page.evaluate(`SerializeAddonTestUtil.inspectBuffer(term.buffer.normal);`); + const buffer4 = await page.evaluate(`inspectBuffer(term.buffer.normal);`); assert.throw(() => { assert.equal(JSON.stringify(buffer3), JSON.stringify(buffer4)); diff --git a/addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts b/addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts deleted file mode 100644 index 23ac2237..00000000 --- a/addons/xterm-addon-serialize/test/SerializeAddonTestUtil.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) 2021 The xterm.js authors. All rights reserved. - * @license MIT - */ - -import { IBuffer } from 'xterm'; -export class SerializeAddonTestUtil { - // this is a util used only for test - public static inspectBuffer(buffer: IBuffer): { x: number, y: number, data: any[][] } { - const lines: any[] = []; - - for (let i = 0; i < buffer.length; i++) { - /** - * Do this intentionally to get content of underlining source - */ - const bufferLine = (buffer.getLine(i)! as any)._line; - - lines.push(JSON.stringify(bufferLine)); - } - - return { - x: buffer.cursorX, - y: buffer.cursorY, - data: lines - }; - } -} diff --git a/demo/client.ts b/demo/client.ts index 27d1c297..93b7c26c 100644 --- a/demo/client.ts +++ b/demo/client.ts @@ -13,7 +13,6 @@ import { AttachAddon } from '../addons/xterm-addon-attach/out/AttachAddon'; import { FitAddon } from '../addons/xterm-addon-fit/out/FitAddon'; import { SearchAddon, ISearchOptions } from '../addons/xterm-addon-search/out/SearchAddon'; import { SerializeAddon } from '../addons/xterm-addon-serialize/out/SerializeAddon'; -import { SerializeAddonTestUtil } from '../addons/xterm-addon-serialize/out-test/SerializeAddonTestUtil'; import { WebLinksAddon } from '../addons/xterm-addon-web-links/out/WebLinksAddon'; import { WebglAddon } from '../addons/xterm-addon-webgl/out/WebglAddon'; import { Unicode11Addon } from '../addons/xterm-addon-unicode11/out/Unicode11Addon'; @@ -39,7 +38,6 @@ export interface IWindowWithTerminal extends Window { FitAddon?: typeof FitAddon; SearchAddon?: typeof SearchAddon; SerializeAddon?: typeof SerializeAddon; - SerializeAddonTestUtil?: typeof SerializeAddonTestUtil; WebLinksAddon?: typeof WebLinksAddon; WebglAddon?: typeof WebglAddon; Unicode11Addon?: typeof Unicode11Addon; @@ -134,7 +132,6 @@ if (document.location.pathname === '/test') { window.FitAddon = FitAddon; window.SearchAddon = SearchAddon; window.SerializeAddon = SerializeAddon; - window.SerializeAddonTestUtil = SerializeAddonTestUtil; window.Unicode11Addon = Unicode11Addon; window.WebLinksAddon = WebLinksAddon; window.WebglAddon = WebglAddon; From 8b273e6939a2856fc978cdfbeb8e60c9fbc86ba0 Mon Sep 17 00:00:00 2001 From: Mmis1000 Date: Wed, 3 Feb 2021 11:01:55 +0800 Subject: [PATCH 43/89] SerializeAddon: fix parameter name in typing --- .../typings/xterm-addon-serialize.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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. From 94d37bbe4c134ab32292063f54b59625bcc73b3e Mon Sep 17 00:00:00 2001 From: jeanp413 Date: Wed, 3 Feb 2021 00:23:52 -0500 Subject: [PATCH 44/89] Keep selection on resize and when changing colors --- addons/xterm-addon-webgl/src/WebglRenderer.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/addons/xterm-addon-webgl/src/WebglRenderer.ts b/addons/xterm-addon-webgl/src/WebglRenderer.ts index 52d1eda4..ca772129 100644 --- a/addons/xterm-addon-webgl/src/WebglRenderer.ts +++ b/addons/xterm-addon-webgl/src/WebglRenderer.ts @@ -118,7 +118,6 @@ export class WebglRenderer extends Disposable implements IRenderer { // Force a full refresh this._model.clear(); - this._updateSelectionModel(undefined, undefined); } public onDevicePixelRatioChange(): void { @@ -156,7 +155,6 @@ export class WebglRenderer extends Disposable implements IRenderer { // Force a full refresh this._model.clear(); - this._updateSelectionModel(undefined, undefined); } public onCharSizeChanged(): void { From ff6d3a076822c2da38c827bd3fdc10275d239690 Mon Sep 17 00:00:00 2001 From: jeanp413 Date: Wed, 3 Feb 2021 01:29:39 -0500 Subject: [PATCH 45/89] Refresh selection on resize as dimensions changed --- addons/xterm-addon-webgl/src/WebglRenderer.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/addons/xterm-addon-webgl/src/WebglRenderer.ts b/addons/xterm-addon-webgl/src/WebglRenderer.ts index ca772129..3bf74242 100644 --- a/addons/xterm-addon-webgl/src/WebglRenderer.ts +++ b/addons/xterm-addon-webgl/src/WebglRenderer.ts @@ -134,7 +134,6 @@ 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)); @@ -148,6 +147,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(); From eec804dd7c7705d3e11598f535f0cf3cf352b6e6 Mon Sep 17 00:00:00 2001 From: ew Date: Fri, 28 Aug 2020 13:07:00 +0000 Subject: [PATCH 46/89] Add hover and leave callbacks for linkprovider Fixes #3056. --- .../src/WebLinkProvider.ts | 21 ++++++++++++++++--- .../src/WebLinksAddon.ts | 8 +++++-- typings/xterm.d.ts | 17 +++++++++++++++ 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/addons/xterm-addon-web-links/src/WebLinkProvider.ts b/addons/xterm-addon-web-links/src/WebLinkProvider.ts index af6ad7d3..f1c2b441 100644 --- a/addons/xterm-addon-web-links/src/WebLinkProvider.ts +++ b/addons/xterm-addon-web-links/src/WebLinkProvider.ts @@ -3,20 +3,35 @@ * @license MIT */ -import { ILinkProvider, IBufferCellPosition, ILink, Terminal } from 'xterm'; +import { ILinkProvider, ILink, Terminal, IViewportRange, ILinkProviderOptions } from 'xterm'; 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; + }); } } diff --git a/addons/xterm-addon-web-links/src/WebLinksAddon.ts b/addons/xterm-addon-web-links/src/WebLinksAddon.ts index dce405a5..574a5c53 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, ILinkProviderOptions } from 'xterm'; import { WebLinkProvider } from './WebLinkProvider'; const protocolClause = '(https?:\\/\\/)'; @@ -53,7 +53,11 @@ export class WebLinksAddon implements ITerminalAddon { this._terminal = terminal; if (this._useLinkProvider && 'registerLinkProvider' in this._terminal) { - this._linkProvider = this._terminal.registerLinkProvider(new WebLinkProvider(this._terminal, strictUrlRegex, this._handler)); + const options = { + hover: this._options.tooltipCallback, + leave: this._options.leaveCallback + }; + 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); diff --git a/typings/xterm.d.ts b/typings/xterm.d.ts index d860ddfa..fcf3ff13 100644 --- a/typings/xterm.d.ts +++ b/typings/xterm.d.ts @@ -352,6 +352,23 @@ declare module 'xterm' { willLinkActivate?: (event: MouseEvent, uri: string) => boolean; } + /** + * 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; + } + /** * An object that can be disposed via a dispose function. */ From bd6676d3b6d5404e9cf46c3882f543de2fae963f Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Wed, 3 Feb 2021 05:28:23 -0800 Subject: [PATCH 47/89] Move options to addon and avoid recreating options --- .../src/WebLinkProvider.ts | 7 ++++++- .../src/WebLinksAddon.ts | 19 ++++++++++------- .../typings/xterm-addon-web-links.d.ts | 21 +++++++++++++++++-- typings/xterm.d.ts | 17 --------------- 4 files changed, 36 insertions(+), 28 deletions(-) diff --git a/addons/xterm-addon-web-links/src/WebLinkProvider.ts b/addons/xterm-addon-web-links/src/WebLinkProvider.ts index f1c2b441..487d5fe6 100644 --- a/addons/xterm-addon-web-links/src/WebLinkProvider.ts +++ b/addons/xterm-addon-web-links/src/WebLinkProvider.ts @@ -3,7 +3,12 @@ * @license MIT */ -import { ILinkProvider, ILink, Terminal, IViewportRange, ILinkProviderOptions } 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 { diff --git a/addons/xterm-addon-web-links/src/WebLinksAddon.ts b/addons/xterm-addon-web-links/src/WebLinksAddon.ts index 574a5c53..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, ILinkProviderOptions } 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,24 +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) { - const options = { - hover: this._options.tooltipCallback, - leave: this._options.leaveCallback - }; + 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/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/typings/xterm.d.ts b/typings/xterm.d.ts index fcf3ff13..d860ddfa 100644 --- a/typings/xterm.d.ts +++ b/typings/xterm.d.ts @@ -352,23 +352,6 @@ declare module 'xterm' { willLinkActivate?: (event: MouseEvent, uri: string) => boolean; } - /** - * 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; - } - /** * An object that can be disposed via a dispose function. */ From 350f6cfea107fa22539511cb5dce098818a5afd5 Mon Sep 17 00:00:00 2001 From: jeanp413 Date: Fri, 5 Feb 2021 11:15:39 -0500 Subject: [PATCH 48/89] Fixes https://github.com/microsoft/vscode/issues/102194 --- src/browser/services/RenderService.ts | 4 ++++ 1 file changed, 4 insertions(+) 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); } From d59f4d2f6f6da9fe862e52e0152b8d87583d4b9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Mon, 8 Feb 2021 01:53:59 +0100 Subject: [PATCH 49/89] async impl for DCS, DcsParser tests --- src/common/parser/DcsParser.test.ts | 205 ++++++++++++++++++++++ src/common/parser/DcsParser.ts | 63 +++++-- src/common/parser/EscapeSequenceParser.ts | 45 +++-- src/common/parser/Types.d.ts | 6 +- 4 files changed, 289 insertions(+), 30 deletions(-) diff --git a/src/common/parser/DcsParser.test.ts b/src/common/parser/DcsParser.test.ts index cf174139..096ebb58 100644 --- a/src/common/parser/DcsParser.test.ts +++ b/src/common/parser/DcsParser.test.ts @@ -252,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 2fa28992..9f326099 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -15,11 +15,11 @@ 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 = () => { }; public dispose(): void { this._handlers = Object.create(null); - this._handlerFb = () => {}; + this._handlerFb = () => { }; this._active = EMPTY_HANDLERS; } @@ -79,20 +79,46 @@ export class DcsParser implements IDcsParser { } } - public unhook(success: boolean): void { + private _stack = { + paused: false, + loopPosition: 0, + fallThrough: false + }; + public unhook(success: boolean, promiseResult?: boolean): void | Promise { if (!this._active.length) { this._handlerFb(this._ident, 'UNHOOK', success); } else { + let handlerResult: any = false; let j = this._active.length - 1; - for (; j >= 0; j--) { - if (this._active[j].unhook(success)) { - 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--) { + if ((handlerResult = this._active[j].unhook(success)) !== false) { + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = false; + return handlerResult; + } + break; + } + } + j--; + } + // cleanup left over handlers (fallThrough for async) for (; j >= 0; j--) { - this._active[j].unhook(false); + if ((handlerResult = this._active[j].unhook(false)) instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } } } this._active = EMPTY_HANDLERS; @@ -113,7 +139,7 @@ export class DcsHandler implements IDcsHandler { private _params: IParams = EMPTY_PARAMS; private _hitLimit: boolean = false; - constructor(private _handler: (data: string, params: IParams) => boolean) {} + constructor(private _handler: (data: string, params: IParams) => boolean | Promise) { } public hook(params: IParams): void { // since we need to preserve params until `unhook`, we have to clone it @@ -136,12 +162,21 @@ export class DcsHandler implements IDcsHandler { } } - public unhook(success: boolean): boolean { - let ret = false; + 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); + if ((ret = this._handler(this._data, this._params)) instanceof Promise) { + // FIXME: should this be behind a catch rule? + return ret.then(res => { + // cleanup handler state late + this._params = EMPTY_PARAMS; + this._data = ''; + this._hitLimit = false; + return res; + }); + } } this._params = EMPTY_PARAMS; this._data = ''; diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 1ac1a22b..842a99b8 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -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; @@ -280,7 +280,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._errorHandler = this._errorHandlerFb; // swallow 7bit ST (ESC+\) - this.registerEscHandler({final: '\\'}, () => true); + this.registerEscHandler({ final: '\\' }, () => true); } protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number { @@ -452,8 +452,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP handlers: ResumableHandlersType, handlerPos: number, transition: number, - chunkPos: number): void - { + chunkPos: number): void { this._parseStack.state = state; this._parseStack.handlers = handlers; this._parseStack.handlerPos = handlerPos; @@ -534,10 +533,11 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP // - handlers are not exhausted yet // FIXME: removing handlers from within a handler of the same sequence // is not supported atm (also true for sync handlers)!! - if (promiseResult === false && handlerPos > -1) { - const handlers = this._parseStack.handlers; - switch (this._parseStack.state) { - case ParserStackType.CSI: + let handlers: ResumableHandlersType; + switch (this._parseStack.state) { + case ParserStackType.CSI: + if (promiseResult === false && handlerPos > -1) { + handlers = this._parseStack.handlers; for (; handlerPos >= 0; handlerPos--) { if ((handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params)) !== false) { if (handlerResult instanceof Promise) { @@ -547,8 +547,11 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP break; } } - break; - case ParserStackType.ESC: + } + break; + case ParserStackType.ESC: + if (promiseResult === false && handlerPos > -1) { + handlers = this._parseStack.handlers; for (; handlerPos >= 0; handlerPos--) { if ((handlerResult = (handlers as EscHandlerType[])[handlerPos]()) !== false) { if (handlerResult instanceof Promise) { @@ -558,8 +561,21 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP break; } } - break; - } + } + break; + case ParserStackType.DCS: + code = data[this._parseStack.chunkPos]; + if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a)) { + 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: + // TODO + break; } // cleanup before continuing with the main loop this._parseStack.state = ParserStackType.NONE; @@ -700,7 +716,10 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } break; case ParserAction.DCS_UNHOOK: - this._dcsParser.unhook(code !== 0x18 && code !== 0x1a); + if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a)) { + this._parseStack.state = ParserStackType.DCS; + return handlerResult; + } if (code === 0x1b) transition |= ParserState.ESCAPE; this._params.reset(); this._params.addParam(0); // ZDM diff --git a/src/common/parser/Types.d.ts b/src/common/parser/Types.d.ts index f6db77fa..30217cc6 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -5,7 +5,7 @@ import { IDisposable } from 'common/Types'; import { ParserState } from 'common/parser/Constants'; -import { OscParser } from 'common/parser/OscParser'; + /** sequence params serialized to js arrays */ export type ParamsArray = (number | number[])[]; @@ -94,7 +94,7 @@ export interface IDcsHandler { * execution of the command should depend on `success`. * To save memory also cleanup data structures here. */ - unhook(success: boolean): boolean; + unhook(success: boolean): boolean | Promise; } export type DcsFallbackHandlerType = (ident: number, action: 'HOOK' | 'PUT' | 'UNHOOK', payload?: any) => void; @@ -219,7 +219,7 @@ export interface IOscParser extends ISubParser { hook(ident: number, params: IParams): void; - unhook(success: boolean): void; + unhook(success: boolean, promiseResult?: boolean): void | Promise; } /** From 041e259c11e065f8451052a300dd2e0c8b9fd59f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Mon, 8 Feb 2021 03:03:28 +0100 Subject: [PATCH 50/89] OSC impl, OscParser tests --- src/common/parser/EscapeSequenceParser.ts | 20 ++- src/common/parser/OscParser.test.ts | 201 ++++++++++++++++++++++ src/common/parser/OscParser.ts | 86 ++++++--- src/common/parser/Types.d.ts | 4 +- 4 files changed, 277 insertions(+), 34 deletions(-) diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 842a99b8..d2da17c6 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -548,6 +548,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } } } + this._parseStack.handlers = []; break; case ParserStackType.ESC: if (promiseResult === false && handlerPos > -1) { @@ -562,10 +563,11 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } } } + this._parseStack.handlers = []; break; case ParserStackType.DCS: code = data[this._parseStack.chunkPos]; - if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a)) { + if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult)) { return handlerResult; } if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; @@ -574,7 +576,14 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._collect = 0; break; case ParserStackType.OSC: - // TODO + code = data[this._parseStack.chunkPos]; + if (handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult)) { + return handlerResult; + } + if (code === 0x1b) transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; break; } // cleanup before continuing with the main loop @@ -717,7 +726,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP break; case ParserAction.DCS_UNHOOK: if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a)) { - this._parseStack.state = ParserStackType.DCS; + this._preserveStack(ParserStackType.DCS, [], 0, transition, i); return handlerResult; } if (code === 0x1b) transition |= ParserState.ESCAPE; @@ -740,7 +749,10 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } break; case ParserAction.OSC_END: - this._oscParser.end(code !== 0x18 && code !== 0x1a); + if (handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a)) { + this._preserveStack(ParserStackType.OSC, [], 0, transition, i); + return handlerResult; + } if (code === 0x1b) transition |= ParserState.ESCAPE; this._params.reset(); this._params.addParam(0); // ZDM diff --git a/src/common/parser/OscParser.test.ts b/src/common/parser/OscParser.test.ts index e2c8641c..5c7f5777 100644 --- a/src/common/parser/OscParser.test.ts +++ b/src/common/parser/OscParser.test.ts @@ -250,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 e7edac66..b0b51e23 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -41,7 +41,7 @@ export class OscParser implements IOscParser { public dispose(): void { this._handlers = Object.create(null); - this._handlerFb = () => {}; + this._handlerFb = () => { }; this._active = EMPTY_HANDLERS; } @@ -76,27 +76,6 @@ export class OscParser implements IOscParser { } } - 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 - if (!this._active.length) { - this._handlerFb(this._id, 'END', success); - } else { - let j = this._active.length - 1; - for (; j >= 0; j--) { - if (this._active[j].end(success)) { - break; - } - } - j--; - // cleanup left over handlers - for (; j >= 0; j--) { - this._active[j].end(false); - } - } - } - public start(): void { // always reset leftover handlers this.reset(); @@ -137,12 +116,18 @@ export class OscParser implements IOscParser { } } + private _stack = { + paused: false, + loopPosition: 0, + fallThrough: false + }; + /** * Indicates end of an OSC command. * Whether the OSC got aborted or finished normally * is indicated by `success`. */ - public end(success: boolean): void { + public end(success: boolean, promiseResult?: boolean): void | Promise { if (this._state === OscState.START) { return; } @@ -154,7 +139,46 @@ 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: any = 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--) { + if ((handlerResult = this._active[j].end(success)) !== false) { + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = false; + return handlerResult; + } + break; + } + } + 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--) { + if ((handlerResult = this._active[j].end(false)) instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } + } + } + } this._active = EMPTY_HANDLERS; this._id = -1; @@ -170,7 +194,7 @@ export class OscHandler implements IOscHandler { private _data = ''; private _hitLimit: boolean = false; - constructor(private _handler: (data: string) => boolean) {} + constructor(private _handler: (data: string) => boolean | Promise) { } public start(): void { this._data = ''; @@ -188,12 +212,18 @@ export class OscHandler implements IOscHandler { } } - public end(success: boolean): boolean { - let ret = false; + 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 = this._handler(this._data)) instanceof Promise) { + 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 30217cc6..dda798cc 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -130,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): boolean; + end(success: boolean): boolean | Promise; } export type OscFallbackHandlerType = (ident: number, action: 'START' | 'PUT' | 'END', payload?: any) => void; @@ -214,7 +214,7 @@ 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 { From d0b555687fc3f80d54f777060f30b7155b2498fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Mon, 8 Feb 2021 03:28:49 +0100 Subject: [PATCH 51/89] update parser hooks api and tests --- src/browser/Terminal2.test.ts | 2 +- src/browser/TestUtils.test.ts | 8 ++++---- src/browser/Types.d.ts | 8 ++++---- src/browser/public/Terminal.ts | 24 ++++++++++++------------ src/common/CoreTerminal.ts | 18 +++++++++--------- src/common/InputHandler.ts | 16 ++++++++-------- src/common/Types.d.ts | 6 +++++- test/api/Parser.api.ts | 28 ++++++++++++++-------------- 8 files changed, 57 insertions(+), 53 deletions(-) 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 38f9c8f1..a2140aa5 100644 --- a/src/browser/TestUtils.test.ts +++ b/src/browser/TestUtils.test.ts @@ -78,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..1262117f 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; 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/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index 7b45a172..50be0d7c 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -278,23 +278,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 { @@ -332,7 +332,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.ts b/src/common/InputHandler.ts index 099cdff7..08f04d9e 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -701,9 +701,9 @@ 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.registerCsiHandler(id, params => { @@ -717,23 +717,23 @@ export class InputHandler extends Disposable implements IInputHandler { } /** - * Forward addDcsHandler from parser. + * Forward registerDcsHandler from parser. */ - public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable { + 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 { + 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 { + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise): IDisposable { return this._parser.registerOscHandler(ident, new OscHandler(callback)); } diff --git a/src/common/Types.d.ts b/src/common/Types.d.ts index 1ea26c2a..e345e11d 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'; @@ -351,6 +351,10 @@ export interface IInputHandler { parse(data: string | Uint8Array): void; 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; diff --git a/test/api/Parser.api.ts b/test/api/Parser.api.ts index 77101e23..ff82895d 100644 --- a/test/api/Parser.api.ts +++ b/test/api/Parser.api.ts @@ -28,12 +28,12 @@ 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; }, ''); @@ -42,20 +42,20 @@ describe('Parser Integration Tests', function(): void { assert.deepEqual(await page.evaluate(`(() => window._customCsiHandlerParams)();`), [[38, 5, 123], [38, [2, -1, 50, 100, 150]]]); }); }); - 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; }); @@ -64,20 +64,20 @@ describe('Parser Integration Tests', function(): void { assert.deepEqual(await page.evaluate(`(() => window._customDcsHandlerCallStack)();`), [['C', [1, 2], 'some data'], ['B', [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; }); @@ -86,20 +86,20 @@ describe('Parser Integration Tests', function(): void { assert.deepEqual(await page.evaluate(`(() => window._customEscHandlerCallStack)();`), ['C', 'B']); }); }); - 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; }); From 5db479c25d706c22e0ba14a80bdfe95b83fc81ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Mon, 8 Feb 2021 03:35:42 +0100 Subject: [PATCH 52/89] update public API --- typings/xterm.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/typings/xterm.d.ts b/typings/xterm.d.ts index d860ddfa..a842a82b 100644 --- a/typings/xterm.d.ts +++ b/typings/xterm.d.ts @@ -1515,7 +1515,7 @@ declare module 'xterm' { * 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. @@ -1534,7 +1534,7 @@ declare module 'xterm' { * 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. @@ -1547,7 +1547,7 @@ declare module 'xterm' { * 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. @@ -1565,7 +1565,7 @@ declare module 'xterm' { * 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; } /** From 26502114d42134f7b67bb6602759f20b7f0710b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Mon, 15 Feb 2021 16:24:29 +0100 Subject: [PATCH 53/89] minor tweaks, API docs update --- src/common/parser/EscapeSequenceParser.ts | 6 ++-- typings/xterm.d.ts | 37 +++++++++++++++-------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index d2da17c6..79f8b844 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -526,18 +526,17 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP this._parseStack.state = ParserStackType.FAIL; throw new Error('improper continuation due to previous async handler, giving up parsing'); } - let handlerPos = this._parseStack.handlerPos - 1; // we have to resume the old handler loop if: // - return value of the promise was `false` // - handlers are not exhausted yet // FIXME: removing handlers from within a handler of the same sequence // is not supported atm (also true for sync handlers)!! - let handlers: ResumableHandlersType; + let handlers = this._parseStack.handlers; + let handlerPos = this._parseStack.handlerPos - 1; switch (this._parseStack.state) { case ParserStackType.CSI: if (promiseResult === false && handlerPos > -1) { - handlers = this._parseStack.handlers; for (; handlerPos >= 0; handlerPos--) { if ((handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params)) !== false) { if (handlerResult instanceof Promise) { @@ -552,7 +551,6 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP break; case ParserStackType.ESC: if (promiseResult === false && handlerPos > -1) { - handlers = this._parseStack.handlers; for (; handlerPos >= 0; handlerPos--) { if ((handlerResult = (handlers as EscHandlerType[])[handlerPos]()) !== false) { if (handlerResult instanceof Promise) { diff --git a/typings/xterm.d.ts b/typings/xterm.d.ts index a842a82b..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,9 +1527,8 @@ 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 | Promise): IDisposable; @@ -1529,9 +1545,8 @@ 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 | Promise): IDisposable; @@ -1542,9 +1557,8 @@ 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 | Promise): IDisposable; @@ -1560,9 +1574,8 @@ 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 | Promise): IDisposable; From 3ab2376517930e2da157a6ee4902e449b1ce592d Mon Sep 17 00:00:00 2001 From: nxshell <74552956+nxshell@users.noreply.github.com> Date: Tue, 16 Feb 2021 19:37:03 +0800 Subject: [PATCH 54/89] feat: Add nxshell which use xtermjs --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b46b7e93..26db59d0 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ Xterm.js is used in several world-class applications to provide great terminal e - [**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. [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. From bce3269e445376f3dc7c5b3faac65855c30209f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 25 Feb 2021 15:41:10 +0100 Subject: [PATCH 55/89] async OSC/DCS registering/dispose tests on parser instance --- .../parser/EscapeSequenceParser.test.ts | 201 ++++++++++++++++-- src/common/parser/EscapeSequenceParser.ts | 18 +- 2 files changed, 192 insertions(+), 27 deletions(-) diff --git a/src/common/parser/EscapeSequenceParser.test.ts b/src/common/parser/EscapeSequenceParser.test.ts index 56d4c93e..6d00adda 100644 --- a/src/common/parser/EscapeSequenceParser.test.ts +++ b/src/common/parser/EscapeSequenceParser.test.ts @@ -102,7 +102,7 @@ class TestEscapeSequenceParser extends EscapeSequenceParser { public trackedStack: IParserStackState[] = []; public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise { const result = super.parse(data, length, promiseResult); - if (result && this._trackStack) { + if (result instanceof Promise && this._trackStack) { this.trackedStack.push({ ...this.parseStack }); } return result; @@ -1742,9 +1742,9 @@ async function throwsAsync(fn: () => Promise, message?: string | undefined) } describe('EscapeSequenceParser - async', () => { - // sequences: SGR 1;31 | hello SP | ESC %G | wor | ESC E | ld! | SGR 0 | EXE \r\n | $> | OSC 1;foo=bar ST + // 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$>\x1b]1;foo=bar\x1b\\'; + 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[] = []; @@ -1764,7 +1764,9 @@ describe('EscapeSequenceParser - async', () => { ['EXE \r'], ['EXE \n'], ['PRINT', '$>'], - ['OSC 1', 'foo=bar'] + ['DCS a', ['xyz', [1, 2]]], + ['OSC 1', 'foo=bar'], + ['PRINT', 'FIN'] ]; parser = new TestEscapeSequenceParser(); parser.reset(); @@ -1786,9 +1788,10 @@ describe('EscapeSequenceParser - async', () => { 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 parsed in sync mode', () => { + 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 @@ -1819,7 +1822,8 @@ describe('EscapeSequenceParser - async', () => { 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(data => { callstack.push(['OSC 1', data]); 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', () => { @@ -1849,7 +1853,12 @@ describe('EscapeSequenceParser - 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] + [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 () => { @@ -1874,7 +1883,11 @@ describe('EscapeSequenceParser - async', () => { ['EXE \n'], ['PRINT', '$'], ['PRINT', '>'], - ['OSC 1', 'foo=bar'] + ['DCS a', ['xyz', [1, 2]]], + ['OSC 1', 'foo=bar'], + ['PRINT', 'F'], + ['PRINT', 'I'], + ['PRINT', 'N'] ]; // split to single char input @@ -1888,7 +1901,9 @@ describe('EscapeSequenceParser - async', () => { [0, ParserStackType.CSI, 0], [0, ParserStackType.ESC, 0], [0, ParserStackType.ESC, 0], - [0, ParserStackType.CSI, 0] + [0, ParserStackType.CSI, 0], + [0, ParserStackType.DCS, 0], + [0, ParserStackType.OSC, 0] ]); }); it('multiple async SGR handlers', async () => { @@ -1906,7 +1921,9 @@ describe('EscapeSequenceParser - async', () => { [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], [27, ParserStackType.CSI, 1], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); // after dispose we should be back to RESULT @@ -1917,7 +1934,9 @@ describe('EscapeSequenceParser - async', () => { [6, ParserStackType.CSI, 0], [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); @@ -1933,7 +1952,9 @@ describe('EscapeSequenceParser - async', () => { [6, ParserStackType.CSI, 1], [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], - [27, ParserStackType.CSI, 1] + [27, ParserStackType.CSI, 1], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); // after dispose we should be back to RESULT @@ -1944,7 +1965,9 @@ describe('EscapeSequenceParser - async', () => { [6, ParserStackType.CSI, 0], [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); }); it('multiple async ESC handlers', async () => { @@ -1960,7 +1983,9 @@ describe('EscapeSequenceParser - async', () => { [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 1], [20, ParserStackType.ESC, 0], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); // after dispose we should be back to RESULT @@ -1971,7 +1996,9 @@ describe('EscapeSequenceParser - async', () => { [6, ParserStackType.CSI, 0], [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); @@ -1986,7 +2013,9 @@ describe('EscapeSequenceParser - async', () => { [6, ParserStackType.CSI, 0], [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 1], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); // after dispose we should be back to RESULT @@ -1997,7 +2026,9 @@ describe('EscapeSequenceParser - async', () => { [6, ParserStackType.CSI, 0], [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); }); it('sync/async SGR mixed', async () => { @@ -2020,7 +2051,9 @@ describe('EscapeSequenceParser - async', () => { [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], [27, ParserStackType.CSI, 2], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); // dispose SGR2 (sync one) @@ -2039,7 +2072,9 @@ describe('EscapeSequenceParser - async', () => { [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], [27, ParserStackType.CSI, 1], - [27, ParserStackType.CSI, 0] + [27, ParserStackType.CSI, 0], + [41, ParserStackType.DCS, 0], + [54, ParserStackType.OSC, 0] ]); clearAccu(); // dispose SGR3 (async one) @@ -2050,8 +2085,134 @@ describe('EscapeSequenceParser - async', () => { [6, ParserStackType.CSI, 0], [15, ParserStackType.ESC, 0], [20, ParserStackType.ESC, 0], - [27, ParserStackType.CSI, 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 79f8b844..3b5c1d05 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -492,7 +492,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP * --> Maybe easier: Give up on non-mutating rule for async handlers... * (needs explanation in docs about exact executor/thenable/worker execution contexts) * - * Example for proper parsing of multiple chunks: + * Boilerplate for proper parsing of multiple chunks with async handlers: * * ```typescript * async function parseMultipleChunks(chunks: Uint32Array[]): Promise { @@ -518,10 +518,14 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) { /** * Reject further parsing on improper continuation after pausing. - * This will happen with sync parse calls not awaiting a returned promise. - * It is a really bad condition with screwed up execution order, - * therefore we exit hard with an exception. - * FIXME: Do we need a method to escape from this broken parser state? (hard to achieve properly) + * This is a really bad condition with screwed up execution order and 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. */ this._parseStack.state = ParserStackType.FAIL; throw new Error('improper continuation due to previous async handler, giving up parsing'); @@ -578,13 +582,13 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP if (handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult)) { return handlerResult; } - if (code === 0x1b) transition |= ParserState.ESCAPE; + 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 loop + // cleanup before continuing with the main sync loop this._parseStack.state = ParserStackType.NONE; start = this._parseStack.chunkPos + 1; this.precedingCodepoint = 0; From 9985ae2c38de82968a7bb7e4c5e496caf753698b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 25 Feb 2021 15:44:39 +0100 Subject: [PATCH 56/89] fix linter warning --- src/common/parser/EscapeSequenceParser.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 3b5c1d05..f9a14553 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -536,7 +536,7 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP // - handlers are not exhausted yet // FIXME: removing handlers from within a handler of the same sequence // is not supported atm (also true for sync handlers)!! - let handlers = this._parseStack.handlers; + const handlers = this._parseStack.handlers; let handlerPos = this._parseStack.handlerPos - 1; switch (this._parseStack.state) { case ParserStackType.CSI: From d500b0f204ffad672139f63f78293a8e3ac11ff9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 25 Feb 2021 17:06:10 +0100 Subject: [PATCH 57/89] inputhandler tests --- src/common/InputHandler.test.ts | 59 +++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/common/InputHandler.test.ts b/src/common/InputHandler.test.ts index d127f673..0402f262 100644 --- a/src/common/InputHandler.test.ts +++ b/src/common/InputHandler.test.ts @@ -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 [ @@ -1805,3 +1806,61 @@ describe('InputHandler', () => { }); }); }); + + +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']); + }); +}); From 6b579215674808166b0f62c0ba5ba228967ef0b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 25 Feb 2021 17:41:16 +0100 Subject: [PATCH 58/89] async handler API tests --- test/api/Parser.api.ts | 117 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 111 insertions(+), 6 deletions(-) diff --git a/test/api/Parser.api.ts b/test/api/Parser.api.ts index ff82895d..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 @@ -39,7 +39,35 @@ describe('Parser Integration Tests', function(): void { }, ''); `); 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('registerDcsHandler', () => { @@ -61,7 +89,35 @@ describe('Parser Integration Tests', function(): void { }); `); 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('registerEscHandler', () => { @@ -83,7 +139,28 @@ describe('Parser Integration Tests', function(): void { }); `); 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('registerOscHandler', () => { @@ -105,7 +182,35 @@ describe('Parser Integration Tests', function(): void { }); `); 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'] + ]); }); }); }); From b4635eddf3ec6c206c32bc81e2aa22ef84d916e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Thu, 25 Feb 2021 19:04:37 +0100 Subject: [PATCH 59/89] make reset async aware --- src/common/parser/DcsParser.ts | 6 +- .../parser/EscapeSequenceParser.test.ts | 4 +- src/common/parser/EscapeSequenceParser.ts | 173 ++++++++++-------- src/common/parser/OscParser.ts | 7 +- src/common/parser/Types.d.ts | 1 + 5 files changed, 111 insertions(+), 80 deletions(-) diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index 9f326099..5389b828 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -48,9 +48,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; } diff --git a/src/common/parser/EscapeSequenceParser.test.ts b/src/common/parser/EscapeSequenceParser.test.ts index 6d00adda..4b23fa00 100644 --- a/src/common/parser/EscapeSequenceParser.test.ts +++ b/src/common/parser/EscapeSequenceParser.test.ts @@ -1847,7 +1847,9 @@ describe('EscapeSequenceParser - async', () => { // 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'); - // FIXME: come up with a good recovery strategy + // 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); diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index f9a14553..9ed3e462 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -427,6 +427,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(); @@ -435,6 +444,13 @@ 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 + } } /** @@ -486,12 +502,6 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP * 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. * - * FIXME: to be discussed - * While awaiting parse promises the terminal buffer state may not change. - * --> Implement lock semantics / promise chaining on buffer alterations? Waah, pandora's box ;) - * --> Maybe easier: Give up on non-mutating rule for async handlers... - * (needs explanation in docs about exact executor/thenable/worker execution contexts) - * * Boilerplate for proper parsing of multiple chunks with async handlers: * * ```typescript @@ -515,84 +525,95 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP // resume from async handler if (this._parseStack.state) { - 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 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. - */ - this._parseStack.state = ParserStackType.FAIL; - throw new Error('improper continuation due to previous async handler, giving up parsing'); - } + // allow sync parser reset even in continuation mode + // Note: can be used to recover parser from improper continuation error above + 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 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. + * + * Its possible to get rid of this error condition by calling `reset`, but dont rely on that, + * as the pending async handler might mess up the terminal even further. 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 - // FIXME: removing handlers from within a handler of the same sequence - // is not supported atm (also true for sync handlers)!! - 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--) { - if ((handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params)) !== false) { - if (handlerResult instanceof Promise) { - this._parseStack.handlerPos = handlerPos; - return handlerResult; + // we have to resume the old handler loop if: + // - return value of the promise was `false` + // - handlers are not exhausted yet + // FIXME: removing handlers from within a handler of the same sequence + // is not supported atm (also true for sync handlers)!! + 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--) { + if ((handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params)) !== false) { + if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + break; } - break; } } - } - this._parseStack.handlers = []; - break; - case ParserStackType.ESC: - if (promiseResult === false && handlerPos > -1) { - for (; handlerPos >= 0; handlerPos--) { - if ((handlerResult = (handlers as EscHandlerType[])[handlerPos]()) !== false) { - 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--) { + if ((handlerResult = (handlers as EscHandlerType[])[handlerPos]()) !== false) { + if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + break; } - break; } } - } - this._parseStack.handlers = []; - break; - case ParserStackType.DCS: - code = data[this._parseStack.chunkPos]; - if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult)) { - 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]; - if (handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult)) { - return handlerResult; - } - if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; - this._params.reset(); - this._params.addParam(0); // ZDM - this._collect = 0; - break; + this._parseStack.handlers = []; + break; + case ParserStackType.DCS: + code = data[this._parseStack.chunkPos]; + if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult)) { + 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]; + if (handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult)) { + 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; } - // 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 diff --git a/src/common/parser/OscParser.ts b/src/common/parser/OscParser.ts index b0b51e23..1516308c 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -46,10 +46,13 @@ export class OscParser implements IOscParser { } 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; diff --git a/src/common/parser/Types.d.ts b/src/common/parser/Types.d.ts index dda798cc..26a02e83 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -245,6 +245,7 @@ export interface IHandlerCollection { export const enum ParserStackType { NONE = 0, FAIL, + RESET, CSI, ESC, OSC, From cc005a274dc440c40cf985fe1ebfa184e2f0f517 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Sat, 27 Feb 2021 20:18:41 +0100 Subject: [PATCH 60/89] multiple changes: - reorder exception throwing to be sync to band position - document WriteBuffer._innerWrite - remove any declarations - remove conditional assigments - use faster return value branching in all parsers - remove dead code in benchmark --- src/common/InputHandler.ts | 4 +- src/common/input/WriteBuffer.ts | 57 +++++++++++++++++++---- src/common/parser/DcsParser.ts | 28 +++++------ src/common/parser/EscapeSequenceParser.ts | 55 ++++++++++++---------- src/common/parser/OscParser.ts | 26 ++++++----- test/benchmark/Terminal.benchmark.ts | 22 --------- 6 files changed, 111 insertions(+), 81 deletions(-) diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index 08f04d9e..f663ded7 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -488,8 +488,8 @@ export class InputHandler extends Disposable implements IInputHandler { * execution stopped at async handler, stack saved, continue with * same chunk and the promise resolve value as `promiseResult` until the method returns `undefined` * - * Note: Never call this directly for a running terminal instance in production. - * Always use `Terminal.write`, which provides in-band blocking and correct exection order. + * 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; diff --git a/src/common/input/WriteBuffer.ts b/src/common/input/WriteBuffer.ts index c6178024..a2c70004 100644 --- a/src/common/input/WriteBuffer.ts +++ b/src/common/input/WriteBuffer.ts @@ -31,6 +31,12 @@ 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)[] = []; @@ -39,7 +45,9 @@ export class WriteBuffer { constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise) { } - // FIXME: does not work that way anymore with async handlers!!! + /** + * @deprecated Unreliable, to be removed soon. + */ 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 @@ -77,13 +85,40 @@ export class WriteBuffer { this._callbacks.push(callback); } - protected _innerWrite(d: number = 0, promiseResult: boolean = true): void { - let result: void | Promise; - const startTime = d || 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]; - - if (result = this._action(data, promiseResult)) { + 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. @@ -98,7 +133,6 @@ export class WriteBuffer { * * 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). - * FIXME: No clear exception handling rules for sync handlers yet (will exit whole processing?). */ /** @@ -127,7 +161,14 @@ export class WriteBuffer { // ? r => setTimeout(() => this._innerWrite(0, r)) // : r => this._innerWrite(startTime, r); - result.then(continuation, err => { setTimeout(() => { throw err; }); continuation(true); }); + // 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(true); + }).then(continuation); return; } diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index 5389b828..6b5ddd6e 100644 --- a/src/common/parser/DcsParser.ts +++ b/src/common/parser/DcsParser.ts @@ -88,11 +88,11 @@ export class DcsParser implements IDcsParser { loopPosition: 0, fallThrough: false }; - public unhook(success: boolean, promiseResult?: boolean): void | Promise { + public unhook(success: boolean, promiseResult: boolean = true): void | Promise { if (!this._active.length) { this._handlerFb(this._ident, 'UNHOOK', success); } else { - let handlerResult: any = false; + let handlerResult: boolean | Promise = false; let j = this._active.length - 1; let fallThrough = false; if (this._stack.paused) { @@ -103,21 +103,22 @@ export class DcsParser implements IDcsParser { } if (!fallThrough && handlerResult === false) { for (; j >= 0; j--) { - if ((handlerResult = this._active[j].unhook(success)) !== false) { - if (handlerResult instanceof Promise) { - this._stack.paused = true; - this._stack.loopPosition = j; - this._stack.fallThrough = false; - return handlerResult; - } + 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--) { - if ((handlerResult = this._active[j].unhook(false)) instanceof Promise) { + handlerResult = this._active[j].unhook(false); + if (handlerResult instanceof Promise) { this._stack.paused = true; this._stack.loopPosition = j; this._stack.fallThrough = true; @@ -171,10 +172,11 @@ export class DcsHandler implements IDcsHandler { if (this._hitLimit) { ret = false; } else if (success) { - if ((ret = this._handler(this._data, this._params)) instanceof Promise) { - // FIXME: should this be behind a catch rule? + 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 => { - // cleanup handler state late this._params = EMPTY_PARAMS; this._data = ''; this._hitLimit = false; diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index 9ed3e462..c1d80c5c 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -468,7 +468,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP handlers: ResumableHandlersType, handlerPos: number, transition: number, - chunkPos: number): void { + chunkPos: number + ): void { this._parseStack.state = state; this._parseStack.handlers = handlers; this._parseStack.handlerPos = handlerPos; @@ -521,12 +522,12 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP let code = 0; let transition = 0; let start = 0; - let handlerResult: any; + 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 above + // 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 @@ -534,8 +535,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP 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 messed up terminal state, - * therefore we exit hard with an exception and reject any further parsing. + * 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 @@ -543,8 +544,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP * `InputHandler.parse` or `EscapeSequenceParser.parse` synchronously without waiting for * continuation of a running async handler. * - * Its possible to get rid of this error condition by calling `reset`, but dont rely on that, - * as the pending async handler might mess up the terminal even further. Instead fix the faulty + * 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; @@ -554,20 +555,18 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP // we have to resume the old handler loop if: // - return value of the promise was `false` // - handlers are not exhausted yet - // FIXME: removing handlers from within a handler of the same sequence - // is not supported atm (also true for sync handlers)!! 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--) { - if ((handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params)) !== false) { - if (handlerResult instanceof Promise) { - this._parseStack.handlerPos = handlerPos; - return handlerResult; - } + handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params); + if (handlerResult === true) { break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; } } } @@ -576,12 +575,12 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP case ParserStackType.ESC: if (promiseResult === false && handlerPos > -1) { for (; handlerPos >= 0; handlerPos--) { - if ((handlerResult = (handlers as EscHandlerType[])[handlerPos]()) !== false) { - if (handlerResult instanceof Promise) { - this._parseStack.handlerPos = handlerPos; - return handlerResult; - } + handlerResult = (handlers as EscHandlerType[])[handlerPos](); + if (handlerResult === true) { break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; } } } @@ -589,7 +588,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP break; case ParserStackType.DCS: code = data[this._parseStack.chunkPos]; - if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult)) { + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { return handlerResult; } if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; @@ -599,7 +599,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP break; case ParserStackType.OSC: code = data[this._parseStack.chunkPos]; - if (handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult)) { + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { return handlerResult; } if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; @@ -678,7 +679,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP for (; j >= 0; j--) { // true means success and to stop bubbling // a promise indicates an async handler that needs to finish before progressing - if ((handlerResult = handlers[j](this._params)) === true) { + handlerResult = handlers[j](this._params); + if (handlerResult === true) { break; } else if (handlerResult instanceof Promise) { this._preserveStack(ParserStackType.CSI, handlers, j, transition, i); @@ -716,7 +718,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP for (; jj >= 0; jj--) { // true means success and to stop bubbling // a promise indicates an async handler that needs to finish before progressing - if ((handlerResult = handlersEsc[jj]()) === true) { + handlerResult = handlersEsc[jj](); + if (handlerResult === true) { break; } else if (handlerResult instanceof Promise) { this._preserveStack(ParserStackType.ESC, handlersEsc, jj, transition, i); @@ -748,7 +751,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } break; case ParserAction.DCS_UNHOOK: - if (handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a)) { + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a); + if (handlerResult) { this._preserveStack(ParserStackType.DCS, [], 0, transition, i); return handlerResult; } @@ -772,7 +776,8 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP } break; case ParserAction.OSC_END: - if (handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a)) { + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a); + if (handlerResult) { this._preserveStack(ParserStackType.OSC, [], 0, transition, i); return handlerResult; } diff --git a/src/common/parser/OscParser.ts b/src/common/parser/OscParser.ts index 1516308c..f043bd82 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -130,7 +130,7 @@ export class OscParser implements IOscParser { * Whether the OSC got aborted or finished normally * is indicated by `success`. */ - public end(success: boolean, promiseResult?: boolean): void | Promise { + public end(success: boolean, promiseResult: boolean = true): void | Promise { if (this._state === OscState.START) { return; } @@ -146,7 +146,7 @@ export class OscParser implements IOscParser { if (!this._active.length) { this._handlerFb(this._id, 'END', success); } else { - let handlerResult: any = false; + let handlerResult: boolean | Promise = false; let j = this._active.length - 1; let fallThrough = false; if (this._stack.paused) { @@ -157,14 +157,14 @@ export class OscParser implements IOscParser { } if (!fallThrough && handlerResult === false) { for (; j >= 0; j--) { - if ((handlerResult = this._active[j].end(success)) !== false) { - if (handlerResult instanceof Promise) { - this._stack.paused = true; - this._stack.loopPosition = j; - this._stack.fallThrough = false; - return handlerResult; - } + 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--; @@ -173,7 +173,8 @@ export class OscParser implements IOscParser { // we always have to call .end for proper cleanup, // here we use `success` to indicate whether a handler should execute for (; j >= 0; j--) { - if ((handlerResult = this._active[j].end(false)) instanceof Promise) { + handlerResult = this._active[j].end(false); + if (handlerResult instanceof Promise) { this._stack.paused = true; this._stack.loopPosition = j; this._stack.fallThrough = true; @@ -220,7 +221,10 @@ export class OscHandler implements IOscHandler { if (this._hitLimit) { ret = false; } else if (success) { - if ((ret = this._handler(this._data)) instanceof Promise) { + 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; diff --git a/test/benchmark/Terminal.benchmark.ts b/test/benchmark/Terminal.benchmark.ts index 7d0f5d84..40a3c208 100644 --- a/test/benchmark/Terminal.benchmark.ts +++ b/test/benchmark/Terminal.benchmark.ts @@ -44,28 +44,6 @@ perfContext('Terminal: ls -lR /usr/lib', () => { } }); - // perfContext('write/string/sync', () => { - // let terminal: Terminal; - // before(() => { - // terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000}); - // }); - // new ThroughputRuntimeCase('', () => { - // terminal.writeSync(content); - // return {payloadSize: contentUtf8.length}; - // }, {fork: false}).showAverageThroughput(); - // }); - // - // perfContext('write/Utf8/sync', () => { - // let terminal: Terminal; - // before(() => { - // terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000}); - // }); - // new ThroughputRuntimeCase('', () => { - // terminal.writeSync(content); - // return {payloadSize: contentUtf8.length}; - // }, {fork: false}).showAverageThroughput(); - // }); - perfContext('write/string/async', () => { let terminal: Terminal; before(() => { From 48a93c379fb2aa04a02317ae9c6768d1c7cc9465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Sat, 27 Feb 2021 22:24:55 +0100 Subject: [PATCH 61/89] log a warning if an async handler takes too long --- src/common/InputHandler.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index f663ded7..228df3a3 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -20,6 +20,7 @@ import { AttributeData } from 'common/buffer/AttributeData'; import { ICoreService, IBufferService, IOptionsService, ILogService, IDirtyRowService, ICoreMouseService, ICharsetService, IUnicodeService } from 'common/services/Services'; import { OscHandler } from 'common/parser/OscParser'; import { DcsHandler } from 'common/parser/DcsParser'; +import { LogLevel } from 'common/services/LogService'; /** * Map collect to glevel. Used in `selectCharset`. @@ -97,6 +98,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 */ @@ -477,6 +481,13 @@ export class InputHandler extends Disposable implements IInputHandler { this._parseStack.decodedLength = decodedLength; this._parseStack.position = position; } + private _logSlowResolvingAsync(p: Promise): void { + // log a limited warning about an async taking too long + if ((this._logService as any)._logLevel <= LogLevel.WARN) { + Promise.race([p, new Promise((res, rej) => setTimeout(rej, SLOW_ASYNC_LIMIT))]) + .catch(() => console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`)); + } + } /** * Parse call with async handler support. @@ -502,6 +513,7 @@ export class InputHandler extends Disposable implements IInputHandler { 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; @@ -536,6 +548,7 @@ export class InputHandler extends Disposable implements IInputHandler { : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer); if (result = this._parser.parse(this._parseBuffer, len)) { this._preserveStack(cursorStartX, cursorStartY, len, i); + this._logSlowResolvingAsync(result); return result; } } @@ -546,6 +559,7 @@ export class InputHandler extends Disposable implements IInputHandler { : 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; } } From cdd238d75e72b9ffe3b484242caa87be2cccd58b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Sun, 28 Feb 2021 13:53:06 +0100 Subject: [PATCH 62/89] do not timeout on faulty async handlers, continue with false to give default handlers chance to run --- src/common/InputHandler.ts | 9 +++++++-- src/common/input/WriteBuffer.ts | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index 228df3a3..7ab2a186 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -484,8 +484,13 @@ export class InputHandler extends Disposable implements IInputHandler { private _logSlowResolvingAsync(p: Promise): void { // log a limited warning about an async taking too long if ((this._logService as any)._logLevel <= LogLevel.WARN) { - Promise.race([p, new Promise((res, rej) => setTimeout(rej, SLOW_ASYNC_LIMIT))]) - .catch(() => console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`)); + 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`); + }); } } diff --git a/src/common/input/WriteBuffer.ts b/src/common/input/WriteBuffer.ts index a2c70004..d22de912 100644 --- a/src/common/input/WriteBuffer.ts +++ b/src/common/input/WriteBuffer.ts @@ -167,7 +167,7 @@ export class WriteBuffer { // (executed on the same queue, thus properly aligned before continuation happens) result.catch(err => { qmt(() => {throw err;}); - return Promise.resolve(true); + return Promise.resolve(false); }).then(continuation); return; } From 9b3fbc9b84e49928989f03b2dcaab72f9c73e922 Mon Sep 17 00:00:00 2001 From: meganrogge Date: Tue, 9 Mar 2021 10:18:14 -0800 Subject: [PATCH 63/89] v 4.11.0 --- addons/xterm-addon-serialize/package.json | 2 +- addons/xterm-addon-webgl/package.json | 2 +- package.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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-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/package.json b/package.json index 91d9a646..9134a378 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "xterm", "description": "Full xterm terminal, in your browser", - "version": "4.10.0", + "version": "4.11.0", "main": "lib/xterm.js", "style": "css/xterm.css", "types": "typings/xterm.d.ts", From 7968b7ce7e5811e684dc02f3ac42511ca68cae2f Mon Sep 17 00:00:00 2001 From: Python-37 <19404655+Python-37@users.noreply.github.com> Date: Wed, 10 Mar 2021 17:27:58 +0800 Subject: [PATCH 64/89] Fix bug of some IMEs cannot input in terminal Fix bug of QQ pinyin and Rime IME cannot input characters in terminal. --- css/xterm.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/css/xterm.css b/css/xterm.css index 7ddcc2d0..bbadb190 100644 --- a/css/xterm.css +++ b/css/xterm.css @@ -59,7 +59,7 @@ } .xterm .xterm-helper-textarea { - padding: 0; +/* padding: 0; */ border: 0; margin: 0; /* Move textarea out of the screen to the far left, so that the cursor is not visible */ From 5185e5f894527080c778e92794922d52bd8c783f Mon Sep 17 00:00:00 2001 From: Martin Sander Date: Mon, 25 Jan 2021 00:12:47 +0100 Subject: [PATCH 65/89] Use linkifier2 to double click select links Also works with right click select. Fixes #682. --- src/browser/Linkifier2.ts | 13 ++------- src/browser/Terminal.ts | 4 ++- src/browser/Types.d.ts | 10 +++++++ src/browser/services/SelectionService.test.ts | 2 +- src/browser/services/SelectionService.ts | 27 +++++++++++++------ 5 files changed, 35 insertions(+), 21 deletions(-) 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/Terminal.ts b/src/browser/Terminal.ts index b0964c21..03ee1f10 100644 --- a/src/browser/Terminal.ts +++ b/src/browser/Terminal.ts @@ -482,7 +482,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())); diff --git a/src/browser/Types.d.ts b/src/browser/Types.d.ts index e8e0cabd..44849b70 100644 --- a/src/browser/Types.d.ts +++ b/src/browser/Types.d.ts @@ -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; + currentLink: ILinkWithState | undefined; attachToDom(element: HTMLElement, mouseService: IMouseService, renderService: IRenderService): void; registerLinkProvider(linkProvider: ILinkProvider): IDisposable; 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 3b993876..547bba4a 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'; @@ -121,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, @@ -316,13 +318,22 @@ export class SelectionService extends Disposable implements ISelectionService { * Selects word at the current mouse event coordinates. * @param event The mouse event. */ - private _selectWordAtCursor(event: MouseEvent): void { + private _selectWordAtCursor(event: MouseEvent, allowWhitespaceOnlySelection: boolean): boolean { + const range = this._linkifier.currentLink?.link?.range; + if (range) { + const scrollOffset = this._bufferService.buffer.ydisp; + this._model.selectionStart = [range.start.x - 1, range.start.y - scrollOffset - 1]; + this._model.selectionEnd = [range.end.x, range.end.y - scrollOffset - 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; } /** @@ -527,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); } } @@ -764,7 +773,9 @@ export class SelectionService extends Disposable implements ISelectionService { public rightClickSelect(ev: MouseEvent): void { if (!this._isClickInSelection(ev)) { - this._selectWordAtCursor(ev); + if (this._selectWordAtCursor(ev, false)) { + this.refresh(true); + } this._fireEventIfSelectionChanged(); } } From 8e7cdd25874c2792497888313c46e6dcd59c1242 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Wed, 17 Mar 2021 22:29:01 +0100 Subject: [PATCH 66/89] interface for inputhandler parse stack, proper typing of LogService.logLevel --- src/common/InputHandler.ts | 25 +++++++++++----------- src/common/TestUtils.test.ts | 3 ++- src/common/Types.d.ts | 10 ++++++++- src/common/services/LogService.ts | 35 ++++++++++++------------------- src/common/services/Services.ts | 9 ++++++++ 5 files changed, 46 insertions(+), 36 deletions(-) diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index 7ab2a186..a35f7981 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,10 +17,9 @@ 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'; -import { LogLevel } from 'common/services/LogService'; /** * Map collect to glevel. Used in `selectCharset`. @@ -263,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, @@ -467,13 +474,6 @@ export class InputHandler extends Disposable implements IInputHandler { /** * Async parse support. */ - private _parseStack = { - paused: false, - cursorStartX: 0, - cursorStartY: 0, - decodedLength: 0, - position: 0 - }; private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void { this._parseStack.paused = true; this._parseStack.cursorStartX = cursorStartX; @@ -481,9 +481,10 @@ export class InputHandler extends Disposable implements IInputHandler { this._parseStack.decodedLength = decodedLength; this._parseStack.position = position; } + private _logSlowResolvingAsync(p: Promise): void { - // log a limited warning about an async taking too long - if ((this._logService as any)._logLevel <= LogLevel.WARN) { + // 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') { 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 e345e11d..108d81ac 100644 --- a/src/common/Types.d.ts +++ b/src/common/Types.d.ts @@ -349,7 +349,7 @@ 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; @@ -431,3 +431,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/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 { From 869c11f1d8ce7edee3a262d904f8e4a4768ad746 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Wed, 17 Mar 2021 22:39:09 +0100 Subject: [PATCH 67/89] interface for subparser stack saves --- src/common/parser/DcsParser.ts | 12 ++++++------ src/common/parser/EscapeSequenceParser.ts | 16 +++++++++------- src/common/parser/OscParser.ts | 13 ++++++------- src/common/parser/Types.d.ts | 13 +++++++++++++ 4 files changed, 34 insertions(+), 20 deletions(-) diff --git a/src/common/parser/DcsParser.ts b/src/common/parser/DcsParser.ts index 6b5ddd6e..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'; @@ -16,6 +16,11 @@ export class DcsParser implements IDcsParser { private _active: IDcsHandler[] = EMPTY_HANDLERS; private _ident: number = 0; private _handlerFb: DcsFallbackHandlerType = () => { }; + private _stack: ISubParserStackState = { + paused: false, + loopPosition: 0, + fallThrough: false + }; public dispose(): void { this._handlers = Object.create(null); @@ -83,11 +88,6 @@ export class DcsParser implements IDcsParser { } } - private _stack = { - paused: false, - loopPosition: 0, - fallThrough: false - }; public unhook(success: boolean, promiseResult: boolean = true): void | Promise { if (!this._active.length) { this._handlerFb(this._ident, 'UNHOOK', success); diff --git a/src/common/parser/EscapeSequenceParser.ts b/src/common/parser/EscapeSequenceParser.ts index c1d80c5c..f20a7e91 100644 --- a/src/common/parser/EscapeSequenceParser.ts +++ b/src/common/parser/EscapeSequenceParser.ts @@ -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 ) { @@ -456,13 +465,6 @@ export class EscapeSequenceParser extends Disposable implements IEscapeSequenceP /** * Async parse support. */ - protected _parseStack: IParserStackState = { - state: ParserStackType.NONE, - handlers: [], - handlerPos: 0, - transition: 0, - chunkPos: 0 - }; protected _preserveStack( state: ParserStackType, handlers: ResumableHandlersType, diff --git a/src/common/parser/OscParser.ts b/src/common/parser/OscParser.ts index f043bd82..32710aed 100644 --- a/src/common/parser/OscParser.ts +++ b/src/common/parser/OscParser.ts @@ -3,7 +3,7 @@ * @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'; @@ -16,6 +16,11 @@ export class OscParser implements IOscParser { private _id = -1; private _handlers: IHandlerCollection = Object.create(null); private _handlerFb: OscFallbackHandlerType = () => { }; + private _stack: ISubParserStackState = { + paused: false, + loopPosition: 0, + fallThrough: false + }; public registerHandler(ident: number, handler: IOscHandler): IDisposable { if (this._handlers[ident] === undefined) { @@ -119,12 +124,6 @@ export class OscParser implements IOscParser { } } - private _stack = { - paused: false, - loopPosition: 0, - fallThrough: false - }; - /** * Indicates end of an OSC command. * Whether the OSC got aborted or finished normally diff --git a/src/common/parser/Types.d.ts b/src/common/parser/Types.d.ts index 26a02e83..3a621eab 100644 --- a/src/common/parser/Types.d.ts +++ b/src/common/parser/Types.d.ts @@ -242,6 +242,8 @@ export interface IHandlerCollection { /** * Types for async parser support. */ + +// type of saved stack state in parser export const enum ParserStackType { NONE = 0, FAIL, @@ -251,7 +253,11 @@ export const enum ParserStackType { 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; @@ -259,3 +265,10 @@ export interface IParserStackState { transition: number; chunkPos: number; } + +// saved stack state of subparser (OSC and DCS) +export interface ISubParserStackState { + paused: boolean; + loopPosition: number; + fallThrough: boolean; +} From 00bdd2805a27c2bef8d2e4ac7d61c2cdefa2c17b Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Thu, 18 Mar 2021 08:14:27 -0700 Subject: [PATCH 68/89] Ensure in js that the textarea is always > 1x1px --- css/xterm.css | 2 +- src/browser/input/CompositionHelper.ts | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/css/xterm.css b/css/xterm.css index bbadb190..7ddcc2d0 100644 --- a/css/xterm.css +++ b/css/xterm.css @@ -59,7 +59,7 @@ } .xterm .xterm-helper-textarea { -/* padding: 0; */ + padding: 0; border: 0; margin: 0; /* Move textarea out of the screen to the far left, so that the cursor is not visible */ diff --git a/src/browser/input/CompositionHelper.ts b/src/browser/input/CompositionHelper.ts index f93483d3..32f8bbb9 100644 --- a/src/browser/input/CompositionHelper.ts +++ b/src/browser/input/CompositionHelper.ts @@ -222,6 +222,9 @@ export class CompositionHelper { const compositionViewBounds = this._compositionView.getBoundingClientRect(); this._textarea.style.left = cursorLeft + 'px'; this._textarea.style.top = cursorTop + '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.width = compositionViewBounds.width + 'px'; this._textarea.style.height = compositionViewBounds.height + 'px'; this._textarea.style.lineHeight = compositionViewBounds.height + 'px'; From 886f285ab7c54b29b4b0c4e15174e43743d2997d Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Thu, 18 Mar 2021 08:31:13 -0700 Subject: [PATCH 69/89] Remove old setting dimensions --- src/browser/input/CompositionHelper.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/browser/input/CompositionHelper.ts b/src/browser/input/CompositionHelper.ts index 32f8bbb9..85cfc3b6 100644 --- a/src/browser/input/CompositionHelper.ts +++ b/src/browser/input/CompositionHelper.ts @@ -225,8 +225,6 @@ export class CompositionHelper { // 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.width = compositionViewBounds.width + 'px'; - this._textarea.style.height = compositionViewBounds.height + 'px'; this._textarea.style.lineHeight = compositionViewBounds.height + 'px'; } From 5170a12cb1ff66c55557159eff0e8655c63111a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Fri, 19 Mar 2021 01:07:43 +0100 Subject: [PATCH 70/89] silence writeSync warning --- src/common/CoreTerminal.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index 50be0d7c..a8961451 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'; @@ -135,9 +135,13 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { * @deprecated Unreliable, will be removed soon. */ public writeSync(data: string | Uint8Array): void { - console.error('writeSync is unreliable and will be removed soon.'); + if (this._logService.logLevel <= LogLevelEnum.WARN && !this._hasBeenWarnedOnce) { + this._logService.warn('writeSync is unreliable and will be removed soon.'); + this._hasBeenWarnedOnce = true; + } this._writeBuffer.writeSync(data); } + private _hasBeenWarnedOnce = false; public resize(x: number, y: number): void { if (isNaN(x) || isNaN(y)) { From 5c5ca4e213c4bfe8b7a1cfa5fb65676af5b37a92 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Fri, 19 Mar 2021 06:24:42 -0700 Subject: [PATCH 71/89] Change warning to one per session not terminal --- src/common/CoreTerminal.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index a8961451..0236d39f 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -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: boolean = false; + export abstract class CoreTerminal extends Disposable implements ICoreTerminal { protected readonly _instantiationService: IInstantiationService; protected readonly _bufferService: IBufferService; @@ -135,13 +138,12 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { * @deprecated Unreliable, will be removed soon. */ public writeSync(data: string | Uint8Array): void { - if (this._logService.logLevel <= LogLevelEnum.WARN && !this._hasBeenWarnedOnce) { + if (this._logService.logLevel <= LogLevelEnum.WARN && !hasWriteSyncWarnHappened) { this._logService.warn('writeSync is unreliable and will be removed soon.'); - this._hasBeenWarnedOnce = true; + hasWriteSyncWarnHappened = true; } this._writeBuffer.writeSync(data); } - private _hasBeenWarnedOnce = false; public resize(x: number, y: number): void { if (isNaN(x) || isNaN(y)) { From c2f4c4dd323413a650a695c5b0dde8b1c4c9902d Mon Sep 17 00:00:00 2001 From: Daniel Steinberg Date: Fri, 19 Mar 2021 18:40:36 -0400 Subject: [PATCH 72/89] Add gifcast to "Real-world uses" in README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 26db59d0..d5488125 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ Xterm.js is used in several world-class applications to provide great terminal e - [**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. From 61213159ee8f00550169b12147ebf21d58b823d6 Mon Sep 17 00:00:00 2001 From: Thomas Zilz Date: Thu, 25 Mar 2021 13:55:29 +0100 Subject: [PATCH 73/89] Test test --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d5488125..d6e6cb7c 100644 --- a/README.md +++ b/README.md @@ -204,3 +204,5 @@ If you contribute code to this project, you are implicitly allowing your code to Copyright (c) 2017-2019, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)
Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)
Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) +1 +hallo heiko From b666e6a924b5b16d575e5b4a36a33f38af2cd394 Mon Sep 17 00:00:00 2001 From: Thomas Zilz Date: Thu, 25 Mar 2021 13:59:20 +0100 Subject: [PATCH 74/89] =?UTF-8?q?Noch=20mehr=20=C3=A4nderungen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE | 6 ++++++ src/tsconfig-base.json | 1 + 2 files changed, 7 insertions(+) diff --git a/LICENSE b/LICENSE index 4472336c..2193d688 100644 --- a/LICENSE +++ b/LICENSE @@ -19,3 +19,9 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +asdfasd asdfasddf +asdfasd as +df +asdfasdf asdfasddfsad +f diff --git a/src/tsconfig-base.json b/src/tsconfig-base.json index 0cd951a7..d16ffcad 100644 --- a/src/tsconfig-base.json +++ b/src/tsconfig-base.json @@ -12,3 +12,4 @@ "experimentalDecorators": true } } +asdfasdf s From 61519cc10c375c4012faf35a196e3e9be48fe0cf Mon Sep 17 00:00:00 2001 From: Thomas Zilz Date: Thu, 25 Mar 2021 14:09:44 +0100 Subject: [PATCH 75/89] Revert "Test test" This reverts commit 61213159ee8f00550169b12147ebf21d58b823d6. --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index d6e6cb7c..d5488125 100644 --- a/README.md +++ b/README.md @@ -204,5 +204,3 @@ If you contribute code to this project, you are implicitly allowing your code to Copyright (c) 2017-2019, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)
Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)
Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) -1 -hallo heiko From 787ef30279777e1602bf0ca4d16c01a6bb4453d9 Mon Sep 17 00:00:00 2001 From: Thomas Zilz Date: Thu, 25 Mar 2021 14:09:47 +0100 Subject: [PATCH 76/89] =?UTF-8?q?Revert=20"Noch=20mehr=20=C3=A4nderungen"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit b666e6a924b5b16d575e5b4a36a33f38af2cd394. --- LICENSE | 6 ------ src/tsconfig-base.json | 1 - 2 files changed, 7 deletions(-) diff --git a/LICENSE b/LICENSE index 2193d688..4472336c 100644 --- a/LICENSE +++ b/LICENSE @@ -19,9 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -asdfasd asdfasddf -asdfasd as -df -asdfasdf asdfasddfsad -f diff --git a/src/tsconfig-base.json b/src/tsconfig-base.json index d16ffcad..0cd951a7 100644 --- a/src/tsconfig-base.json +++ b/src/tsconfig-base.json @@ -12,4 +12,3 @@ "experimentalDecorators": true } } -asdfasdf s From e106cd02cfcfe1c63144b2c3ab3affd9d3cbb5c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Breitbart?= Date: Fri, 26 Mar 2021 12:46:39 +0100 Subject: [PATCH 77/89] fix callstack overflow of writeSync --- src/common/CoreTerminal.ts | 4 +- src/common/input/WriteBuffer.test.ts | 21 ++++++++++ src/common/input/WriteBuffer.ts | 60 +++++++++++++++++++--------- 3 files changed, 65 insertions(+), 20 deletions(-) diff --git a/src/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index 0236d39f..c11554f1 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -137,12 +137,12 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal { * * @deprecated Unreliable, will be removed soon. */ - public writeSync(data: string | Uint8Array): void { + 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); + this._writeBuffer.writeSync(data, maxSubsequentCalls); } public resize(x: number, y: number): void { 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 d22de912..cc84c9ab 100644 --- a/src/common/input/WriteBuffer.ts +++ b/src/common/input/WriteBuffer.ts @@ -42,31 +42,55 @@ export class WriteBuffer { private _callbacks: ((() => void) | undefined)[] = []; private _pendingData = 0; private _bufferOffset = 0; + private _isSyncWriting = false; + private _syncCalls = 0; constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise) { } /** * @deprecated Unreliable, to be removed soon. */ - public writeSync(data: string | Uint8Array): void { + 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; + // 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 { @@ -191,8 +215,8 @@ export class WriteBuffer { } setTimeout(() => this._innerWrite()); } else { - this._writeBuffer = []; - this._callbacks = []; + this._writeBuffer.length = 0; + this._callbacks.length = 0; this._pendingData = 0; this._bufferOffset = 0; } From de791cfb35897d9121729252c07a138dd1062e10 Mon Sep 17 00:00:00 2001 From: coderaiser Date: Sun, 28 Mar 2021 15:27:03 +0300 Subject: [PATCH 78/89] chore: lint using putout --- addons/xterm-addon-attach/src/AttachAddon.ts | 4 +- .../test/AttachAddon.api.ts | 2 +- addons/xterm-addon-fit/test/FitAddon.api.ts | 6 +-- addons/xterm-addon-ligatures/src/parse.ts | 6 +-- addons/xterm-addon-search/src/SearchAddon.ts | 6 +-- .../test/SearchAddon.api.ts | 2 +- .../test/SerializeAddon.api.ts | 2 +- .../test/Unicode11Addon.api.ts | 2 +- .../src/WebLinkProvider.ts | 4 +- .../test/WebLinksAddon.api.ts | 2 +- addons/xterm-addon-webgl/src/WebglRenderer.ts | 40 ++++++++++++++----- .../test/WebglRenderer.api.ts | 4 +- src/browser/MouseZoneManager.ts | 4 +- src/browser/Terminal.ts | 6 +-- src/common/CoreTerminal.ts | 2 +- src/common/InputHandler.test.ts | 4 +- src/common/InputHandler.ts | 2 +- 17 files changed, 59 insertions(+), 39 deletions(-) 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/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/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/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/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts index 47af9d91..d472d753 100644 --- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts +++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts @@ -34,7 +34,7 @@ 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 }); 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 487d5fe6..f0caf974 100644 --- a/addons/xterm-addon-web-links/src/WebLinkProvider.ts +++ b/addons/xterm-addon-web-links/src/WebLinkProvider.ts @@ -41,7 +41,7 @@ export class WebLinkProvider implements ILinkProvider { } 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); @@ -89,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/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-webgl/src/WebglRenderer.ts b/addons/xterm-addon-webgl/src/WebglRenderer.ts index 3bf74242..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,10 +108,10 @@ 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(); @@ -136,7 +138,9 @@ export class WebglRenderer extends Disposable implements IRenderer { this._model.resize(this._terminal.cols, this._terminal.rows); // 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; @@ -168,15 +172,21 @@ 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); @@ -184,11 +194,15 @@ export class WebglRenderer extends Disposable implements IRenderer { } 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(); } @@ -222,7 +236,9 @@ export class WebglRenderer extends Disposable implements IRenderer { } 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 { @@ -245,7 +261,9 @@ 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()) { 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/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.ts b/src/browser/Terminal.ts index b0964c21..686ae68d 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); @@ -834,7 +834,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/common/CoreTerminal.ts b/src/common/CoreTerminal.ts index c11554f1..384691ed 100644 --- a/src/common/CoreTerminal.ts +++ b/src/common/CoreTerminal.ts @@ -41,7 +41,7 @@ import { InputHandler } from 'common/InputHandler'; import { WriteBuffer } from 'common/input/WriteBuffer'; // Only trigger this warning a single time per session -let hasWriteSyncWarnHappened: boolean = false; +let hasWriteSyncWarnHappened = false; export abstract class CoreTerminal extends Disposable implements ICoreTerminal { protected readonly _instantiationService: IInstantiationService; diff --git a/src/common/InputHandler.test.ts b/src/common/InputHandler.test.ts index 0402f262..b5067193 100644 --- a/src/common/InputHandler.test.ts +++ b/src/common/InputHandler.test.ts @@ -1759,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')); @@ -1767,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'); diff --git a/src/common/InputHandler.ts b/src/common/InputHandler.ts index a35f7981..13b0a0e7 100644 --- a/src/common/InputHandler.ts +++ b/src/common/InputHandler.ts @@ -2856,7 +2856,7 @@ export class InputHandler extends Disposable implements IInputHandler { 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) { From cbe056c27e14820c7f24aee5b5742a27e3267d28 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Mon, 29 Mar 2021 18:46:53 +0000 Subject: [PATCH 79/89] [Security] Bump y18n from 4.0.0 to 4.0.1 Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1. **This update includes a security fix.** - [Release notes](https://github.com/yargs/y18n/releases) - [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md) - [Commits](https://github.com/yargs/y18n/commits) Signed-off-by: dependabot-preview[bot] --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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" From dafe7ea3daeba3bd53e56b4f82ad4da0fdd81901 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Tue, 30 Mar 2021 04:45:41 -0700 Subject: [PATCH 80/89] Remove experimental note from webgl renderer Fixes #2033 --- addons/xterm-addon-webgl/README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 From b7e0489a53e649e51aac91db96d30b8e4780d969 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Tue, 30 Mar 2021 06:17:28 -0700 Subject: [PATCH 81/89] Remove offset from link The link range is absolute, not relative to viewport --- src/browser/services/SelectionService.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/browser/services/SelectionService.ts b/src/browser/services/SelectionService.ts index 547bba4a..8f7caeb3 100644 --- a/src/browser/services/SelectionService.ts +++ b/src/browser/services/SelectionService.ts @@ -321,9 +321,8 @@ export class SelectionService extends Disposable implements ISelectionService { private _selectWordAtCursor(event: MouseEvent, allowWhitespaceOnlySelection: boolean): boolean { const range = this._linkifier.currentLink?.link?.range; if (range) { - const scrollOffset = this._bufferService.buffer.ydisp; - this._model.selectionStart = [range.start.x - 1, range.start.y - scrollOffset - 1]; - this._model.selectionEnd = [range.end.x, range.end.y - scrollOffset - 1]; + this._model.selectionStart = [range.start.x - 1, range.start.y - 1]; + this._model.selectionEnd = [range.end.x, range.end.y - 1]; return true; } From 04092c80e80bd47467b16f07e6c06c71ad92b08a Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Tue, 30 Mar 2021 06:19:34 -0700 Subject: [PATCH 82/89] Update src/browser/services/SelectionService.ts --- src/browser/services/SelectionService.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/browser/services/SelectionService.ts b/src/browser/services/SelectionService.ts index 8f7caeb3..4806ef91 100644 --- a/src/browser/services/SelectionService.ts +++ b/src/browser/services/SelectionService.ts @@ -319,6 +319,7 @@ export class SelectionService extends Disposable implements ISelectionService { * @param event The mouse event. */ 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]; From d2471b43012b5639ae00cbbd1b6764a6983ee700 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Tue, 30 Mar 2021 06:19:39 -0700 Subject: [PATCH 83/89] Update src/browser/Types.d.ts --- src/browser/Types.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/browser/Types.d.ts b/src/browser/Types.d.ts index 29b489aa..f743934e 100644 --- a/src/browser/Types.d.ts +++ b/src/browser/Types.d.ts @@ -217,7 +217,7 @@ export interface ILinkWithState { export interface ILinkifier2 { onShowLinkUnderline: IEvent; onHideLinkUnderline: IEvent; - currentLink: ILinkWithState | undefined; + readonly currentLink: ILinkWithState | undefined; attachToDom(element: HTMLElement, mouseService: IMouseService, renderService: IRenderService): void; registerLinkProvider(linkProvider: ILinkProvider): IDisposable; From de334ea116efbfe8badd940a4ab808619835e3f1 Mon Sep 17 00:00:00 2001 From: kena0ki Date: Wed, 31 Mar 2021 23:32:53 +0900 Subject: [PATCH 84/89] Use RenderService.dimensions instead of CharSizeService for textarea position --- src/browser/Terminal.ts | 32 ++++++++++++--------- src/browser/input/CompositionHelper.test.ts | 4 +-- src/browser/input/CompositionHelper.ts | 17 +++++++---- 3 files changed, 31 insertions(+), 22 deletions(-) diff --git a/src/browser/Terminal.ts b/src/browser/Terminal.ts index 2eba4027..95d74254 100644 --- a/src/browser/Terminal.ts +++ b/src/browser/Terminal.ts @@ -297,19 +297,23 @@ 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 viewportRelativeCursorY = cursorY - this.buffer.ydisp; + const cursorX = Math.min(this.buffer.x, this.cols - 1); + const cellHeight = this._renderService.dimensions.actualCellHeight; + const width = this.buffer.lines.get(cursorY)!.getWidth(cursorX); + const cellWidth = this._renderService.dimensions.actualCellWidth * width; + const cursorTop = viewportRelativeCursorY * 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'; @@ -438,14 +442,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 +453,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); diff --git a/src/browser/input/CompositionHelper.test.ts b/src/browser/input/CompositionHelper.test.ts index b9a4f668..080c9c47 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 { MockCharSizeService, 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(), new MockCharSizeService(10, 10), coreService, new MockRenderService()); }); describe('Input', () => { diff --git a/src/browser/input/CompositionHelper.ts b/src/browser/input/CompositionHelper.ts index 85cfc3b6..e5389af4 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 { ICharSizeService, IRenderService } from 'browser/services/Services'; import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services'; interface IPosition { @@ -46,7 +46,8 @@ export class CompositionHelper { @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; @@ -202,14 +203,18 @@ export class CompositionHelper { * necessary as the IME events across browsers are not consistently triggered. */ public updateCompositionElements(dontRecurse?: boolean): void { - if (!this._isComposing) { + if (!this._isComposing || !this._renderService) { return; } if (this._bufferService.buffer.isCursorInViewport) { - const cellHeight = Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight); - const cursorTop = this._bufferService.buffer.y * cellHeight; - const cursorLeft = this._bufferService.buffer.x * this._charSizeService.width; + const cursorY = this._bufferService.buffer.ybase + this._bufferService.buffer.y; + const viewportRelativeCursorY = cursorY - this._bufferService.buffer.ydisp; + const cursorX = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1); + + const cellHeight = this._renderService.dimensions.actualCellHeight; + const cursorTop = viewportRelativeCursorY * this._renderService.dimensions.actualCellHeight; + const cursorLeft = cursorX * this._renderService.dimensions.actualCellWidth; this._compositionView.style.left = cursorLeft + 'px'; this._compositionView.style.top = cursorTop + 'px'; From a15f61bb8540cd7817170b735bee9a454eaf12a5 Mon Sep 17 00:00:00 2001 From: kena0ki Date: Thu, 1 Apr 2021 00:11:30 +0900 Subject: [PATCH 85/89] Remove non-null assertion --- src/browser/Terminal.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/browser/Terminal.ts b/src/browser/Terminal.ts index 95d74254..371f5549 100644 --- a/src/browser/Terminal.ts +++ b/src/browser/Terminal.ts @@ -304,7 +304,9 @@ export class Terminal extends CoreTerminal implements ITerminal { const viewportRelativeCursorY = cursorY - this.buffer.ydisp; const cursorX = Math.min(this.buffer.x, this.cols - 1); const cellHeight = this._renderService.dimensions.actualCellHeight; - const width = this.buffer.lines.get(cursorY)!.getWidth(cursorX); + const bufferLine = this.buffer.lines.get(cursorY); + if (!bufferLine) return; + const width = bufferLine.getWidth(cursorX); const cellWidth = this._renderService.dimensions.actualCellWidth * width; const cursorTop = viewportRelativeCursorY * this._renderService.dimensions.actualCellHeight; const cursorLeft = cursorX * this._renderService.dimensions.actualCellWidth; From e9e716964e1a24758132ac92e22276147ced54ed Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Thu, 1 Apr 2021 08:19:12 -0700 Subject: [PATCH 86/89] Remove now unneeded CharSizeService --- src/browser/input/CompositionHelper.test.ts | 4 ++-- src/browser/input/CompositionHelper.ts | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/browser/input/CompositionHelper.test.ts b/src/browser/input/CompositionHelper.test.ts index 080c9c47..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, MockRenderService } 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, new MockRenderService()); + 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 e5389af4..d2626e2c 100644 --- a/src/browser/input/CompositionHelper.ts +++ b/src/browser/input/CompositionHelper.ts @@ -3,7 +3,7 @@ * @license MIT */ -import { ICharSizeService, IRenderService } from 'browser/services/Services'; +import { IRenderService } from 'browser/services/Services'; import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services'; interface IPosition { @@ -45,7 +45,6 @@ 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, @IRenderService private readonly _renderService: IRenderService ) { From b62a64519f567081f327c34c01a056eb9edcdcd4 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Thu, 1 Apr 2021 08:23:18 -0700 Subject: [PATCH 87/89] Use buffer y for relative cursor pos --- src/browser/input/CompositionHelper.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/browser/input/CompositionHelper.ts b/src/browser/input/CompositionHelper.ts index d2626e2c..65a5d672 100644 --- a/src/browser/input/CompositionHelper.ts +++ b/src/browser/input/CompositionHelper.ts @@ -207,12 +207,10 @@ export class CompositionHelper { } if (this._bufferService.buffer.isCursorInViewport) { - const cursorY = this._bufferService.buffer.ybase + this._bufferService.buffer.y; - const viewportRelativeCursorY = cursorY - this._bufferService.buffer.ydisp; const cursorX = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1); const cellHeight = this._renderService.dimensions.actualCellHeight; - const cursorTop = viewportRelativeCursorY * 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'; From 05516750b5ac832147c7153f5db1f79d7f941508 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Thu, 1 Apr 2021 08:23:35 -0700 Subject: [PATCH 88/89] Remove RenderService check, it must be passed to ctor --- src/browser/input/CompositionHelper.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/browser/input/CompositionHelper.ts b/src/browser/input/CompositionHelper.ts index 65a5d672..8a204831 100644 --- a/src/browser/input/CompositionHelper.ts +++ b/src/browser/input/CompositionHelper.ts @@ -202,7 +202,7 @@ export class CompositionHelper { * necessary as the IME events across browsers are not consistently triggered. */ public updateCompositionElements(dontRecurse?: boolean): void { - if (!this._isComposing || !this._renderService) { + if (!this._isComposing) { return; } From 7b920adbe9ace642e4188a7c60412c9cd7d620d5 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Thu, 1 Apr 2021 08:26:35 -0700 Subject: [PATCH 89/89] Tidy up syncTextArea --- src/browser/Terminal.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/browser/Terminal.ts b/src/browser/Terminal.ts index 371f5549..f95013cd 100644 --- a/src/browser/Terminal.ts +++ b/src/browser/Terminal.ts @@ -301,21 +301,22 @@ export class Terminal extends CoreTerminal implements ITerminal { return; } const cursorY = this.buffer.ybase + this.buffer.y; - const viewportRelativeCursorY = cursorY - this.buffer.ydisp; + 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 bufferLine = this.buffer.lines.get(cursorY); - if (!bufferLine) return; const width = bufferLine.getWidth(cursorX); const cellWidth = this._renderService.dimensions.actualCellWidth * width; - const cursorTop = viewportRelativeCursorY * this._renderService.dimensions.actualCellHeight; + 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 = cellWidth +'px'; + this.textarea.style.width = cellWidth + 'px'; this.textarea.style.height = cellHeight + 'px'; this.textarea.style.lineHeight = cellHeight + 'px'; this.textarea.style.zIndex = '-5';