diff options
Diffstat (limited to 'node_modules/xterm/src/common')
50 files changed, 11502 insertions, 0 deletions
diff --git a/node_modules/xterm/src/common/CircularList.ts b/node_modules/xterm/src/common/CircularList.ts new file mode 100644 index 0000000..4d2c04e --- /dev/null +++ b/node_modules/xterm/src/common/CircularList.ts @@ -0,0 +1,239 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICircularList } from 'common/Types'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; + +export interface IInsertEvent { + index: number; + amount: number; +} + +export interface IDeleteEvent { + index: number; + amount: number; +} + +/** + * Represents a circular list; a list with a maximum size that wraps around when push is called, + * overriding values at the start of the list. + */ +export class CircularList<T> implements ICircularList<T> { + protected _array: (T | undefined)[]; + private _startIndex: number; + private _length: number; + + public onDeleteEmitter = new EventEmitter<IDeleteEvent>(); + public get onDelete(): IEvent<IDeleteEvent> { return this.onDeleteEmitter.event; } + public onInsertEmitter = new EventEmitter<IInsertEvent>(); + public get onInsert(): IEvent<IInsertEvent> { return this.onInsertEmitter.event; } + public onTrimEmitter = new EventEmitter<number>(); + public get onTrim(): IEvent<number> { return this.onTrimEmitter.event; } + + constructor( + private _maxLength: number + ) { + this._array = new Array<T>(this._maxLength); + this._startIndex = 0; + this._length = 0; + } + + public get maxLength(): number { + return this._maxLength; + } + + public set maxLength(newMaxLength: number) { + // There was no change in maxLength, return early. + if (this._maxLength === newMaxLength) { + return; + } + + // Reconstruct array, starting at index 0. Only transfer values from the + // indexes 0 to length. + const newArray = new Array<T | undefined>(newMaxLength); + for (let i = 0; i < Math.min(newMaxLength, this.length); i++) { + newArray[i] = this._array[this._getCyclicIndex(i)]; + } + this._array = newArray; + this._maxLength = newMaxLength; + this._startIndex = 0; + } + + public get length(): number { + return this._length; + } + + public set length(newLength: number) { + if (newLength > this._length) { + for (let i = this._length; i < newLength; i++) { + this._array[i] = undefined; + } + } + this._length = newLength; + } + + /** + * Gets the value at an index. + * + * Note that for performance reasons there is no bounds checking here, the index reference is + * circular so this should always return a value and never throw. + * @param index The index of the value to get. + * @return The value corresponding to the index. + */ + public get(index: number): T | undefined { + return this._array[this._getCyclicIndex(index)]; + } + + /** + * Sets the value at an index. + * + * Note that for performance reasons there is no bounds checking here, the index reference is + * circular so this should always return a value and never throw. + * @param index The index to set. + * @param value The value to set. + */ + public set(index: number, value: T | undefined): void { + this._array[this._getCyclicIndex(index)] = value; + } + + /** + * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0 + * if the maximum length is reached. + * @param value The value to push onto the list. + */ + public push(value: T): void { + this._array[this._getCyclicIndex(this._length)] = value; + if (this._length === this._maxLength) { + this._startIndex = ++this._startIndex % this._maxLength; + this.onTrimEmitter.fire(1); + } else { + this._length++; + } + } + + /** + * Advance ringbuffer index and return current element for recycling. + * Note: The buffer must be full for this method to work. + * @throws When the buffer is not full. + */ + public recycle(): T { + if (this._length !== this._maxLength) { + throw new Error('Can only recycle when the buffer is full'); + } + this._startIndex = ++this._startIndex % this._maxLength; + this.onTrimEmitter.fire(1); + return this._array[this._getCyclicIndex(this._length - 1)]!; + } + + /** + * Ringbuffer is at max length. + */ + public get isFull(): boolean { + return this._length === this._maxLength; + } + + /** + * Removes and returns the last value on the list. + * @return The popped value. + */ + public pop(): T | undefined { + return this._array[this._getCyclicIndex(this._length-- - 1)]; + } + + /** + * Deletes and/or inserts items at a particular index (in that order). Unlike + * Array.prototype.splice, this operation does not return the deleted items as a new array in + * order to save creating a new array. Note that this operation may shift all values in the list + * in the worst case. + * @param start The index to delete and/or insert. + * @param deleteCount The number of elements to delete. + * @param items The items to insert. + */ + public splice(start: number, deleteCount: number, ...items: T[]): void { + // Delete items + if (deleteCount) { + for (let i = start; i < this._length - deleteCount; i++) { + this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)]; + } + this._length -= deleteCount; + this.onDeleteEmitter.fire({ index: start, amount: deleteCount }); + } + + // Add items + for (let i = this._length - 1; i >= start; i--) { + this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)]; + } + for (let i = 0; i < items.length; i++) { + this._array[this._getCyclicIndex(start + i)] = items[i]; + } + if (items.length) { + this.onInsertEmitter.fire({ index: start, amount: items.length }); + } + + // Adjust length as needed + if (this._length + items.length > this._maxLength) { + const countToTrim = (this._length + items.length) - this._maxLength; + this._startIndex += countToTrim; + this._length = this._maxLength; + this.onTrimEmitter.fire(countToTrim); + } else { + this._length += items.length; + } + } + + /** + * Trims a number of items from the start of the list. + * @param count The number of items to remove. + */ + public trimStart(count: number): void { + if (count > this._length) { + count = this._length; + } + this._startIndex += count; + this._length -= count; + this.onTrimEmitter.fire(count); + } + + public shiftElements(start: number, count: number, offset: number): void { + if (count <= 0) { + return; + } + if (start < 0 || start >= this._length) { + throw new Error('start argument out of range'); + } + if (start + offset < 0) { + throw new Error('Cannot shift elements in list beyond index 0'); + } + + if (offset > 0) { + for (let i = count - 1; i >= 0; i--) { + this.set(start + i + offset, this.get(start + i)); + } + const expandListBy = (start + count + offset) - this._length; + if (expandListBy > 0) { + this._length += expandListBy; + while (this._length > this._maxLength) { + this._length--; + this._startIndex++; + this.onTrimEmitter.fire(1); + } + } + } else { + for (let i = 0; i < count; i++) { + this.set(start + i + offset, this.get(start + i)); + } + } + } + + /** + * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the + * backing array to get the element associated with the regular index. + * @param index The regular index. + * @returns The cyclic index. + */ + private _getCyclicIndex(index: number): number { + return (this._startIndex + index) % this._maxLength; + } +} diff --git a/node_modules/xterm/src/common/Clone.ts b/node_modules/xterm/src/common/Clone.ts new file mode 100644 index 0000000..37821fe --- /dev/null +++ b/node_modules/xterm/src/common/Clone.ts @@ -0,0 +1,23 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/* + * A simple utility for cloning values + */ +export function clone<T>(val: T, depth: number = 5): T { + if (typeof val !== 'object') { + return val; + } + + // If we're cloning an array, use an array as the base, otherwise use an object + const clonedObject: any = Array.isArray(val) ? [] : {}; + + for (const key in val) { + // Recursively clone eack item unless we're at the maximum depth + clonedObject[key] = depth <= 1 ? val[key] : (val[key] && clone(val[key], depth - 1)); + } + + return clonedObject as T; +} diff --git a/node_modules/xterm/src/common/CoreTerminal.ts b/node_modules/xterm/src/common/CoreTerminal.ts new file mode 100644 index 0000000..12b374c --- /dev/null +++ b/node_modules/xterm/src/common/CoreTerminal.ts @@ -0,0 +1,297 @@ +/** + * Copyright (c) 2014-2020 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + * + * Terminal Emulation References: + * http://vt100.net/ + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt + * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + * http://invisible-island.net/vttest/ + * http://www.inwap.com/pdp10/ansicode.txt + * http://linux.die.net/man/4/console_codes + * http://linux.die.net/man/7/urxvt + */ + +import { Disposable } from 'common/Lifecycle'; +import { IInstantiationService, IOptionsService, IBufferService, ILogService, ICharsetService, ICoreService, ICoreMouseService, IUnicodeService, IDirtyRowService, LogLevelEnum, ITerminalOptions } 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'; +import { OptionsService } from 'common/services/OptionsService'; +import { IDisposable, IBufferLine, IAttributeData, ICoreTerminal, IKeyboardEvent, IScrollEvent, ScrollSource, ITerminalOptions as IPublicTerminalOptions } from 'common/Types'; +import { CoreService } from 'common/services/CoreService'; +import { EventEmitter, IEvent, forwardEvent } from 'common/EventEmitter'; +import { CoreMouseService } from 'common/services/CoreMouseService'; +import { DirtyRowService } from 'common/services/DirtyRowService'; +import { UnicodeService } from 'common/services/UnicodeService'; +import { CharsetService } from 'common/services/CharsetService'; +import { updateWindowsModeWrappedState } from 'common/WindowsMode'; +import { IFunctionIdentifier, IParams } from 'common/parser/Types'; +import { IBufferSet } from 'common/buffer/Types'; +import { InputHandler } from 'common/InputHandler'; +import { WriteBuffer } from 'common/input/WriteBuffer'; + +// Only trigger this warning a single time per session +let hasWriteSyncWarnHappened = false; + +export abstract class CoreTerminal extends Disposable implements ICoreTerminal { + protected readonly _instantiationService: IInstantiationService; + protected readonly _bufferService: IBufferService; + protected readonly _logService: ILogService; + protected readonly _charsetService: ICharsetService; + protected readonly _dirtyRowService: IDirtyRowService; + + public readonly coreMouseService: ICoreMouseService; + public readonly coreService: ICoreService; + public readonly unicodeService: IUnicodeService; + public readonly optionsService: IOptionsService; + + protected _inputHandler: InputHandler; + private _writeBuffer: WriteBuffer; + private _windowsMode: IDisposable | undefined; + + private _onBinary = new EventEmitter<string>(); + public get onBinary(): IEvent<string> { return this._onBinary.event; } + private _onData = new EventEmitter<string>(); + public get onData(): IEvent<string> { return this._onData.event; } + protected _onLineFeed = new EventEmitter<void>(); + public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; } + private _onResize = new EventEmitter<{ cols: number, rows: number }>(); + public get onResize(): IEvent<{ cols: number, rows: number }> { return this._onResize.event; } + protected _onScroll = new EventEmitter<IScrollEvent, void>(); + /** + * Internally we track the source of the scroll but this is meaningless outside the library so + * it's filtered out. + */ + protected _onScrollApi?: EventEmitter<number, void>; + public get onScroll(): IEvent<number, void> { + if (!this._onScrollApi) { + this._onScrollApi = new EventEmitter<number, void>(); + this.register(this._onScroll.event(ev => { + this._onScrollApi?.fire(ev.position); + })); + } + return this._onScrollApi.event; + } + + public get cols(): number { return this._bufferService.cols; } + public get rows(): number { return this._bufferService.rows; } + public get buffers(): IBufferSet { return this._bufferService.buffers; } + public get options(): ITerminalOptions { return this.optionsService.options; } + public set options(options: ITerminalOptions) { + for (const key in options) { + this.optionsService.options[key] = options[key]; + } + } + + constructor( + options: Partial<ITerminalOptions> + ) { + super(); + + // Setup and initialize services + this._instantiationService = new InstantiationService(); + this.optionsService = new OptionsService(options); + this._instantiationService.setService(IOptionsService, this.optionsService); + this._bufferService = this.register(this._instantiationService.createInstance(BufferService)); + this._instantiationService.setService(IBufferService, this._bufferService); + this._logService = this._instantiationService.createInstance(LogService); + this._instantiationService.setService(ILogService, this._logService); + this.coreService = this.register(this._instantiationService.createInstance(CoreService, () => this.scrollToBottom())); + this._instantiationService.setService(ICoreService, this.coreService); + this.coreMouseService = this._instantiationService.createInstance(CoreMouseService); + this._instantiationService.setService(ICoreMouseService, this.coreMouseService); + this._dirtyRowService = this._instantiationService.createInstance(DirtyRowService); + this._instantiationService.setService(IDirtyRowService, this._dirtyRowService); + this.unicodeService = this._instantiationService.createInstance(UnicodeService); + this._instantiationService.setService(IUnicodeService, this.unicodeService); + this._charsetService = this._instantiationService.createInstance(CharsetService); + this._instantiationService.setService(ICharsetService, this._charsetService); + + // Register input handler and handle/forward events + this._inputHandler = new InputHandler(this._bufferService, this._charsetService, this.coreService, this._dirtyRowService, this._logService, this.optionsService, this.coreMouseService, this.unicodeService); + this.register(forwardEvent(this._inputHandler.onLineFeed, this._onLineFeed)); + this.register(this._inputHandler); + + // Setup listeners + this.register(forwardEvent(this._bufferService.onResize, this._onResize)); + this.register(forwardEvent(this.coreService.onData, this._onData)); + this.register(forwardEvent(this.coreService.onBinary, this._onBinary)); + this.register(this.optionsService.onOptionChange(key => this._updateOptions(key))); + this.register(this._bufferService.onScroll(event => { + this._onScroll.fire({ position: this._bufferService.buffer.ydisp, source: ScrollSource.TERMINAL }); + this._dirtyRowService.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom); + })); + this.register(this._inputHandler.onScroll(event => { + this._onScroll.fire({ position: this._bufferService.buffer.ydisp, source: ScrollSource.TERMINAL }); + this._dirtyRowService.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom); + })); + + // Setup WriteBuffer + this._writeBuffer = new WriteBuffer((data, promiseResult) => this._inputHandler.parse(data, promiseResult)); + } + + public dispose(): void { + if (this._isDisposed) { + return; + } + super.dispose(); + this._windowsMode?.dispose(); + this._windowsMode = undefined; + } + + public write(data: string | Uint8Array, callback?: () => void): void { + 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, maxSubsequentCalls?: number): void { + if (this._logService.logLevel <= LogLevelEnum.WARN && !hasWriteSyncWarnHappened) { + this._logService.warn('writeSync is unreliable and will be removed soon.'); + hasWriteSyncWarnHappened = true; + } + this._writeBuffer.writeSync(data, maxSubsequentCalls); + } + + public resize(x: number, y: number): void { + if (isNaN(x) || isNaN(y)) { + return; + } + + x = Math.max(x, MINIMUM_COLS); + y = Math.max(y, MINIMUM_ROWS); + + this._bufferService.resize(x, y); + } + + /** + * Scroll the terminal down 1 row, creating a blank line. + * @param isWrapped Whether the new line is wrapped from the previous line. + */ + public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void { + this._bufferService.scroll(eraseAttr, isWrapped); + } + + /** + * Scroll the display of the terminal + * @param disp The number of lines to scroll down (negative scroll up). + * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used + * to avoid unwanted events being handled by the viewport when the event was triggered from the + * viewport originally. + */ + public scrollLines(disp: number, suppressScrollEvent?: boolean, source?: ScrollSource): void { + this._bufferService.scrollLines(disp, suppressScrollEvent, source); + } + + /** + * Scroll the display of the terminal by a number of pages. + * @param pageCount The number of pages to scroll (negative scrolls up). + */ + public scrollPages(pageCount: number): void { + this._bufferService.scrollPages(pageCount); + } + + /** + * Scrolls the display of the terminal to the top. + */ + public scrollToTop(): void { + this._bufferService.scrollToTop(); + } + + /** + * Scrolls the display of the terminal to the bottom. + */ + public scrollToBottom(): void { + this._bufferService.scrollToBottom(); + } + + public scrollToLine(line: number): void { + this._bufferService.scrollToLine(line); + } + + /** Add handler for ESC escape sequence. See xterm.d.ts for details. */ + public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable { + return this._inputHandler.registerEscHandler(id, callback); + } + + /** Add handler for DCS escape sequence. See xterm.d.ts for details. */ + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable { + return this._inputHandler.registerDcsHandler(id, callback); + } + + /** Add handler for CSI escape sequence. See xterm.d.ts for details. */ + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable { + return this._inputHandler.registerCsiHandler(id, callback); + } + + /** Add handler for OSC escape sequence. See xterm.d.ts for details. */ + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable { + return this._inputHandler.registerOscHandler(ident, callback); + } + + protected _setup(): void { + if (this.optionsService.rawOptions.windowsMode) { + this._enableWindowsMode(); + } + } + + public reset(): void { + this._inputHandler.reset(); + this._bufferService.reset(); + this._charsetService.reset(); + this.coreService.reset(); + this.coreMouseService.reset(); + } + + protected _updateOptions(key: string): void { + // TODO: These listeners should be owned by individual components + switch (key) { + case 'scrollback': + this.buffers.resize(this.cols, this.rows); + break; + case 'windowsMode': + if (this.optionsService.rawOptions.windowsMode) { + this._enableWindowsMode(); + } else { + this._windowsMode?.dispose(); + this._windowsMode = undefined; + } + break; + } + } + + protected _enableWindowsMode(): void { + if (!this._windowsMode) { + const disposables: IDisposable[] = []; + disposables.push(this.onLineFeed(updateWindowsModeWrappedState.bind(null, this._bufferService))); + disposables.push(this.registerCsiHandler({ final: 'H' }, () => { + updateWindowsModeWrappedState(this._bufferService); + return false; + })); + this._windowsMode = { + dispose: () => { + for (const d of disposables) { + d.dispose(); + } + } + }; + } + } +} diff --git a/node_modules/xterm/src/common/EventEmitter.ts b/node_modules/xterm/src/common/EventEmitter.ts new file mode 100644 index 0000000..4684809 --- /dev/null +++ b/node_modules/xterm/src/common/EventEmitter.ts @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/Types'; + +interface IListener<T, U = void> { + (arg1: T, arg2: U): void; +} + +export interface IEvent<T, U = void> { + (listener: (arg1: T, arg2: U) => any): IDisposable; +} + +export interface IEventEmitter<T, U = void> { + event: IEvent<T, U>; + fire(arg1: T, arg2: U): void; + dispose(): void; +} + +export class EventEmitter<T, U = void> implements IEventEmitter<T, U> { + private _listeners: IListener<T, U>[] = []; + private _event?: IEvent<T, U>; + private _disposed: boolean = false; + + public get event(): IEvent<T, U> { + if (!this._event) { + this._event = (listener: (arg1: T, arg2: U) => any) => { + this._listeners.push(listener); + const disposable = { + dispose: () => { + if (!this._disposed) { + for (let i = 0; i < this._listeners.length; i++) { + if (this._listeners[i] === listener) { + this._listeners.splice(i, 1); + return; + } + } + } + } + }; + return disposable; + }; + } + return this._event; + } + + public fire(arg1: T, arg2: U): void { + const queue: IListener<T, U>[] = []; + for (let i = 0; i < this._listeners.length; i++) { + queue.push(this._listeners[i]); + } + for (let i = 0; i < queue.length; i++) { + queue[i].call(undefined, arg1, arg2); + } + } + + public dispose(): void { + if (this._listeners) { + this._listeners.length = 0; + } + this._disposed = true; + } +} + +export function forwardEvent<T>(from: IEvent<T>, to: IEventEmitter<T>): IDisposable { + return from(e => to.fire(e)); +} diff --git a/node_modules/xterm/src/common/InputHandler.ts b/node_modules/xterm/src/common/InputHandler.ts new file mode 100644 index 0000000..68660f8 --- /dev/null +++ b/node_modules/xterm/src/common/InputHandler.ts @@ -0,0 +1,3229 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + */ + +import { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IColorEvent, IParseStack, ColorIndex, ColorRequestType } from 'common/Types'; +import { C0, C1 } from 'common/data/EscapeSequences'; +import { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets'; +import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser'; +import { Disposable } from 'common/Lifecycle'; +import { concat } from 'common/TypedArrayUtils'; +import { StringToUtf32, stringFromCodePoint, utf32ToString, Utf8ToUtf32 } from 'common/input/TextDecoder'; +import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types'; +import { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content, 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, LogLevelEnum } from 'common/services/Services'; +import { OscHandler } from 'common/parser/OscParser'; +import { DcsHandler } from 'common/parser/DcsParser'; +import { IBuffer } from 'common/buffer/Types'; +import { parseColor } from 'common/input/XParseColor'; + +/** + * Map collect to glevel. Used in `selectCharset`. + */ +const GLEVEL: { [key: string]: number } = { '(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2 }; + +/** + * VT commands done by the parser - FIXME: move this to the parser? + */ +// @vt: #Y ESC CSI "Control Sequence Introducer" "ESC [" "Start of a CSI sequence." +// @vt: #Y ESC OSC "Operating System Command" "ESC ]" "Start of an OSC sequence." +// @vt: #Y ESC DCS "Device Control String" "ESC P" "Start of a DCS sequence." +// @vt: #Y ESC ST "String Terminator" "ESC \" "Terminator used for string type sequences." +// @vt: #Y ESC PM "Privacy Message" "ESC ^" "Start of a privacy message." +// @vt: #Y ESC APC "Application Program Command" "ESC _" "Start of an APC sequence." +// @vt: #Y C1 CSI "Control Sequence Introducer" "\x9B" "Start of a CSI sequence." +// @vt: #Y C1 OSC "Operating System Command" "\x9D" "Start of an OSC sequence." +// @vt: #Y C1 DCS "Device Control String" "\x90" "Start of a DCS sequence." +// @vt: #Y C1 ST "String Terminator" "\x9C" "Terminator used for string type sequences." +// @vt: #Y C1 PM "Privacy Message" "\x9E" "Start of a privacy message." +// @vt: #Y C1 APC "Application Program Command" "\x9F" "Start of an APC sequence." +// @vt: #Y C0 NUL "Null" "\0, \x00" "NUL is ignored." +// @vt: #Y C0 ESC "Escape" "\e, \x1B" "Start of a sequence. Cancels any other sequence." + +/** + * Document common VT features here that are currently unsupported + */ +// @vt: #N DCS SIXEL "SIXEL Graphics" "DCS Ps ; Ps ; Ps ; q Pt ST" "Draw SIXEL image starting at cursor position." +// @vt: #N OSC 1 "Set Icon Name" "OSC 1 ; Pt BEL" "Set icon name." + +/** + * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher. + */ +const MAX_PARSEBUFFER_LENGTH = 131072; + +/** + * Limit length of title and icon name stacks. + */ +const STACK_LIMIT = 10; + +// map params to window option +function paramToWindowOption(n: number, opts: IWindowOptions): boolean { + if (n > 24) { + return opts.setWinLines || false; + } + switch (n) { + case 1: return !!opts.restoreWin; + case 2: return !!opts.minimizeWin; + case 3: return !!opts.setWinPosition; + case 4: return !!opts.setWinSizePixels; + case 5: return !!opts.raiseWin; + case 6: return !!opts.lowerWin; + case 7: return !!opts.refreshWin; + case 8: return !!opts.setWinSizeChars; + case 9: return !!opts.maximizeWin; + case 10: return !!opts.fullscreenWin; + case 11: return !!opts.getWinState; + case 13: return !!opts.getWinPosition; + case 14: return !!opts.getWinSizePixels; + case 15: return !!opts.getScreenSizePixels; + case 16: return !!opts.getCellSizePixels; + case 18: return !!opts.getWinSizeChars; + case 19: return !!opts.getScreenSizeChars; + case 20: return !!opts.getIconTitle; + case 21: return !!opts.getWinTitle; + case 22: return !!opts.pushTitle; + case 23: return !!opts.popTitle; + case 24: return !!opts.setWinLines; + } + return false; +} + +export enum WindowsOptionsReportType { + GET_WIN_SIZE_PIXELS = 0, + 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 + */ + +/** + * DCS $ q Pt ST + * DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html) + * Request Status String (DECRQSS), VT420 and up. + * Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html) + * + * @vt: #P[See limited support below.] DCS DECRQSS "Request Selection or Setting" "DCS $ q Pt ST" "Request several terminal settings." + * Response is in the form `ESC P 1 $ r Pt ST` for valid requests, where `Pt` contains the corresponding CSI string, + * `ESC P 0 ST` for invalid requests. + * + * Supported requests and responses: + * + * | Type | Request | Response (`Pt`) | + * | -------------------------------- | ----------------- | ----------------------------------------------------- | + * | Graphic Rendition (SGR) | `DCS $ q m ST` | always reporting `0m` (currently broken) | + * | Top and Bottom Margins (DECSTBM) | `DCS $ q r ST` | `Ps ; Ps r` | + * | Cursor Style (DECSCUSR) | `DCS $ q SP q ST` | `Ps SP q` | + * | Protection Attribute (DECSCA) | `DCS $ q " q ST` | always reporting `0 " q` (DECSCA is unsupported) | + * | Conformance Level (DECSCL) | `DCS $ q " p ST` | always reporting `61 ; 1 " p` (DECSCL is unsupported) | + * + * + * TODO: + * - fix SGR report + * - either implement DECSCA or remove the report + * - either check which conformance is better suited or remove the report completely + * --> we are currently a mixture of all up to VT400 but dont follow anyone strictly + */ +class DECRQSS implements IDcsHandler { + private _data: Uint32Array = new Uint32Array(0); + + constructor( + private _bufferService: IBufferService, + private _coreService: ICoreService, + private _logService: ILogService, + private _optionsService: IOptionsService + ) { } + + public hook(params: IParams): void { + this._data = new Uint32Array(0); + } + + public put(data: Uint32Array, start: number, end: number): void { + this._data = concat(this._data, data.subarray(start, end)); + } + + public unhook(success: boolean): boolean { + if (!success) { + this._data = new Uint32Array(0); + return true; + } + const data = utf32ToString(this._data); + this._data = new Uint32Array(0); + switch (data) { + // valid: DCS 1 $ r Pt ST (xterm) + case '"q': // DECSCA + this._coreService.triggerDataEvent(`${C0.ESC}P1$r0"q${C0.ESC}\\`); + break; + case '"p': // DECSCL + 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'; + this._coreService.triggerDataEvent(`${C0.ESC}P1$r${pt}${C0.ESC}\\`); + break; + case 'm': // SGR + // TODO: report real settings instead of 0m + 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.rawOptions.cursorStyle]; + style -= this._optionsService.rawOptions.cursorBlink ? 1 : 0; + 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; + } +} + +/** + * DCS Ps; Ps| Pt ST + * DECUDK (https://vt100.net/docs/vt510-rm/DECUDK.html) + * not supported + * + * @vt: #N DCS DECUDK "User Defined Keys" "DCS Ps ; Ps | Pt ST" "Definitions for user-defined keys." + */ + +/** + * DCS + q Pt ST (xterm) + * Request Terminfo String + * not implemented + * + * @vt: #N DCS XTGETTCAP "Request Terminfo String" "DCS + q Pt ST" "Request Terminfo String." + */ + +/** + * DCS + p Pt ST (xterm) + * Set Terminfo Data + * not supported + * + * @vt: #N DCS XTSETTCAP "Set Terminfo Data" "DCS + p Pt ST" "Set Terminfo Data." + */ + + + +/** + * The terminal's standard implementation of IInputHandler, this handles all + * input from the Parser. + * + * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand + * each function's header comment. + */ +export class InputHandler extends Disposable implements IInputHandler { + private _parseBuffer: Uint32Array = new Uint32Array(4096); + private _stringDecoder: StringToUtf32 = new StringToUtf32(); + private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32(); + private _workCell: CellData = new CellData(); + private _windowTitle = ''; + private _iconName = ''; + protected _windowTitleStack: string[] = []; + protected _iconNameStack: string[] = []; + + private _curAttrData: IAttributeData = DEFAULT_ATTR_DATA.clone(); + private _eraseAttrDataInternal: IAttributeData = DEFAULT_ATTR_DATA.clone(); + + private _activeBuffer: IBuffer; + + private _onRequestBell = new EventEmitter<void>(); + public get onRequestBell(): IEvent<void> { return this._onRequestBell.event; } + private _onRequestRefreshRows = new EventEmitter<number, number>(); + public get onRequestRefreshRows(): IEvent<number, number> { return this._onRequestRefreshRows.event; } + private _onRequestReset = new EventEmitter<void>(); + public get onRequestReset(): IEvent<void> { return this._onRequestReset.event; } + private _onRequestSendFocus = new EventEmitter<void>(); + public get onRequestSendFocus(): IEvent<void> { return this._onRequestSendFocus.event; } + private _onRequestSyncScrollBar = new EventEmitter<void>(); + public get onRequestSyncScrollBar(): IEvent<void> { return this._onRequestSyncScrollBar.event; } + private _onRequestWindowsOptionsReport = new EventEmitter<WindowsOptionsReportType>(); + public get onRequestWindowsOptionsReport(): IEvent<WindowsOptionsReportType> { return this._onRequestWindowsOptionsReport.event; } + + private _onA11yChar = new EventEmitter<string>(); + public get onA11yChar(): IEvent<string> { return this._onA11yChar.event; } + private _onA11yTab = new EventEmitter<number>(); + public get onA11yTab(): IEvent<number> { return this._onA11yTab.event; } + private _onCursorMove = new EventEmitter<void>(); + public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; } + private _onLineFeed = new EventEmitter<void>(); + public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; } + private _onScroll = new EventEmitter<number>(); + public get onScroll(): IEvent<number> { return this._onScroll.event; } + private _onTitleChange = new EventEmitter<string>(); + public get onTitleChange(): IEvent<string> { return this._onTitleChange.event; } + private _onColor = new EventEmitter<IColorEvent>(); + public get onColor(): IEvent<IColorEvent> { return this._onColor.event; } + + private _parseStack: IParseStack = { + paused: false, + cursorStartX: 0, + cursorStartY: 0, + decodedLength: 0, + position: 0 + }; + + constructor( + private readonly _bufferService: IBufferService, + private readonly _charsetService: ICharsetService, + private readonly _coreService: ICoreService, + private readonly _dirtyRowService: IDirtyRowService, + private readonly _logService: ILogService, + private readonly _optionsService: IOptionsService, + private readonly _coreMouseService: ICoreMouseService, + private readonly _unicodeService: IUnicodeService, + private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser() + ) { + super(); + this.register(this._parser); + + // Track properties used in performance critical code manually to avoid using slow getters + this._activeBuffer = this._bufferService.buffer; + this.register(this._bufferService.buffers.onBufferActivate(e => this._activeBuffer = e.activeBuffer)); + + /** + * custom fallback handlers + */ + this._parser.setCsiHandlerFallback((ident, params) => { + this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() }); + }); + this._parser.setEscHandlerFallback(ident => { + this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) }); + }); + this._parser.setExecuteHandlerFallback(code => { + this._logService.debug('Unknown EXECUTE code: ', { code }); + }); + this._parser.setOscHandlerFallback((identifier, action, data) => { + this._logService.debug('Unknown OSC code: ', { identifier, action, data }); + }); + this._parser.setDcsHandlerFallback((ident, action, payload) => { + if (action === 'HOOK') { + payload = payload.toArray(); + } + this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload }); + }); + + /** + * print handler + */ + this._parser.setPrintHandler((data, start, end) => this.print(data, start, end)); + + /** + * CSI handler + */ + this._parser.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 + */ + this._parser.setExecuteHandler(C0.BEL, () => this.bell()); + this._parser.setExecuteHandler(C0.LF, () => this.lineFeed()); + this._parser.setExecuteHandler(C0.VT, () => this.lineFeed()); + this._parser.setExecuteHandler(C0.FF, () => this.lineFeed()); + this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn()); + this._parser.setExecuteHandler(C0.BS, () => this.backspace()); + this._parser.setExecuteHandler(C0.HT, () => this.tab()); + this._parser.setExecuteHandler(C0.SO, () => this.shiftOut()); + this._parser.setExecuteHandler(C0.SI, () => this.shiftIn()); + // FIXME: What do to with missing? Old code just added those to print. + + this._parser.setExecuteHandler(C1.IND, () => this.index()); + this._parser.setExecuteHandler(C1.NEL, () => this.nextLine()); + this._parser.setExecuteHandler(C1.HTS, () => this.tabSet()); + + /** + * OSC handler + */ + // 0 - icon name + title + this._parser.registerOscHandler(0, new OscHandler(data => { this.setTitle(data); this.setIconName(data); return true; })); + // 1 - icon name + this._parser.registerOscHandler(1, new OscHandler(data => this.setIconName(data))); + // 2 - title + 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.registerOscHandler(4, new OscHandler(data => this.setOrReportIndexedColor(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) + // 10 - Change VT100 text foreground color to Pt. + this._parser.registerOscHandler(10, new OscHandler(data => this.setOrReportFgColor(data))); + // 11 - Change VT100 text background color to Pt. + this._parser.registerOscHandler(11, new OscHandler(data => this.setOrReportBgColor(data))); + // 12 - Change text cursor color to Pt. + this._parser.registerOscHandler(12, new OscHandler(data => this.setOrReportCursorColor(data))); + // 13 - Change mouse foreground color to Pt. + // 14 - Change mouse background color to Pt. + // 15 - Change Tektronix foreground color to Pt. + // 16 - Change Tektronix background color to Pt. + // 17 - Change highlight background color to Pt. + // 18 - Change Tektronix cursor color to Pt. + // 19 - Change highlight foreground color to Pt. + // 46 - Change Log File to Pt. + // 50 - Set Font to Pt. + // 51 - reserved for Emacs shell. + // 52 - Manipulate Selection Data. + // 104 ; c - Reset Color Number c. + this._parser.registerOscHandler(104, new OscHandler(data => this.restoreIndexedColor(data))); + // 105 ; c - Reset Special Color Number c. + // 106 ; c; f - Enable/disable Special Color Number c. + // 110 - Reset VT100 text foreground color. + this._parser.registerOscHandler(110, new OscHandler(data => this.restoreFgColor(data))); + // 111 - Reset VT100 text background color. + this._parser.registerOscHandler(111, new OscHandler(data => this.restoreBgColor(data))); + // 112 - Reset text cursor color. + this._parser.registerOscHandler(112, new OscHandler(data => this.restoreCursorColor(data))); + // 113 - Reset mouse foreground color. + // 114 - Reset mouse background color. + // 115 - Reset Tektronix foreground color. + // 116 - Reset Tektronix background color. + // 117 - Reset highlight color. + // 118 - Reset Tektronix cursor color. + // 119 - Reset highlight foreground color. + + /** + * ESC handlers + */ + this._parser.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.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.registerEscHandler({ intermediates: '#', final: '8' }, () => this.screenAlignmentPattern()); + + /** + * error handler + */ + this._parser.setErrorHandler((state: IParsingState) => { + this._logService.error('Parsing error: ', state); + return state; + }); + + /** + * DCS handler + */ + this._parser.registerDcsHandler({ intermediates: '$', final: 'q' }, new DECRQSS(this._bufferService, this._coreService, this._logService, this._optionsService)); + } + + public dispose(): void { + super.dispose(); + } + + /** + * Async parse support. + */ + private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void { + this._parseStack.paused = true; + this._parseStack.cursorStartX = cursorStartX; + this._parseStack.cursorStartY = cursorStartY; + this._parseStack.decodedLength = decodedLength; + this._parseStack.position = position; + } + + private _logSlowResolvingAsync(p: Promise<boolean>): void { + // log a limited warning about an async handler taking too long + if (this._logService.logLevel <= LogLevelEnum.WARN) { + Promise.race([p, new Promise((res, rej) => setTimeout(() => rej('#SLOW_TIMEOUT'), SLOW_ASYNC_LIMIT))]) + .catch(err => { + if (err !== '#SLOW_TIMEOUT') { + throw err; + } + console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`); + }); + } + } + + /** + * Parse call with async handler support. + * + * Whether the stack state got preserved for the next call, is indicated by the return value: + * - undefined (void): + * all handlers were sync, no stack save, continue normally with next chunk + * - Promise\<boolean\>: + * execution stopped at async handler, stack saved, continue with + * same chunk and the promise resolve value as `promiseResult` until the method returns `undefined` + * + * Note: This method should only be called by `Terminal.write` to ensure correct execution order and + * proper continuation of async parser handlers. + */ + public parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise<boolean> { + let result: void | Promise<boolean>; + let cursorStartX = this._activeBuffer.x; + let cursorStartY = this._activeBuffer.y; + let start = 0; + const wasPaused = this._parseStack.paused; + + if (wasPaused) { + // assumption: _parseBuffer never mutates between async calls + if (result = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, promiseResult)) { + this._logSlowResolvingAsync(result); + return result; + } + cursorStartX = this._parseStack.cursorStartX; + cursorStartY = this._parseStack.cursorStartY; + this._parseStack.paused = false; + if (data.length > MAX_PARSEBUFFER_LENGTH) { + start = this._parseStack.position + MAX_PARSEBUFFER_LENGTH; + } + } + + // Log debug data, the log level gate is to prevent extra work in this hot path + if (this._logService.logLevel <= LogLevelEnum.DEBUG) { + this._logService.debug(`parsing data${typeof data === 'string' ? ` "${data}"` : ''}`, typeof data === 'string' + ? data.split('').map(e => e.charCodeAt(0)) + : data + ); + } + + // resize input buffer if needed + if (this._parseBuffer.length < data.length) { + if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) { + this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH)); + } + } + + // Clear the dirty row service so we know which lines changed as a result of parsing + // 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 = 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); + if (result = this._parser.parse(this._parseBuffer, len)) { + this._preserveStack(cursorStartX, cursorStartY, len, i); + this._logSlowResolvingAsync(result); + return result; + } + } + } else { + if (!wasPaused) { + const len = (typeof data === 'string') + ? this._stringDecoder.decode(data, this._parseBuffer) + : this._utf8Decoder.decode(data, this._parseBuffer); + if (result = this._parser.parse(this._parseBuffer, len)) { + this._preserveStack(cursorStartX, cursorStartY, len, 0); + this._logSlowResolvingAsync(result); + return result; + } + } + } + + if (this._activeBuffer.x !== cursorStartX || this._activeBuffer.y !== cursorStartY) { + this._onCursorMove.fire(); + } + + // Refresh any dirty rows accumulated as part of parsing + this._onRequestRefreshRows.fire(this._dirtyRowService.start, this._dirtyRowService.end); + } + + public print(data: Uint32Array, start: number, end: number): void { + let code: number; + let chWidth: number; + const charset = this._charsetService.charset; + const screenReaderMode = this._optionsService.rawOptions.screenReaderMode; + const cols = this._bufferService.cols; + const wraparoundMode = this._coreService.decPrivateModes.wraparound; + const insertMode = this._coreService.modes.insertMode; + const curAttr = this._curAttrData; + let bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!; + + this._dirtyRowService.markDirty(this._activeBuffer.y); + + // handle wide chars: reset start_cell-1 if we would overwrite the second cell of a wide char + if (this._activeBuffer.x && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x - 1) === 2) { + bufferRow.setCellFromCodePoint(this._activeBuffer.x - 1, 0, 1, curAttr.fg, curAttr.bg, curAttr.extended); + } + + for (let pos = start; pos < end; ++pos) { + code = data[pos]; + + // calculate print space + // expensive call, therefore we save width in line buffer + chWidth = this._unicodeService.wcwidth(code); + + // get charset replacement character + // charset is only defined for ASCII, therefore we only + // search for an replacement char if code < 127 + if (code < 127 && charset) { + const ch = charset[String.fromCharCode(code)]; + if (ch) { + code = ch.charCodeAt(0); + } + } + + if (screenReaderMode) { + this._onA11yChar.fire(stringFromCodePoint(code)); + } + + // insert combining char at last cursor position + // this._activeBuffer.x should never be 0 for a combining char + // since they always follow a cell consuming char + // therefore we can test for this._activeBuffer.x to avoid overflow left + if (!chWidth && this._activeBuffer.x) { + if (!bufferRow.getWidth(this._activeBuffer.x - 1)) { + // found empty cell after fullwidth, need to go 2 cells back + // it is save to step 2 cells back here + // since an empty cell is only set by fullwidth chars + bufferRow.addCodepointToCell(this._activeBuffer.x - 2, code); + } else { + bufferRow.addCodepointToCell(this._activeBuffer.x - 1, code); + } + continue; + } + + // goto next line if ch would overflow + // NOTE: To avoid costly width checks here, + // the terminal does not allow a cols < 2. + if (this._activeBuffer.x + chWidth - 1 >= cols) { + // autowrap - DECAWM + // automatically wraps to the beginning of the next line + if (wraparoundMode) { + // clear left over cells to the right + while (this._activeBuffer.x < cols) { + bufferRow.setCellFromCodePoint(this._activeBuffer.x++, 0, 1, curAttr.fg, curAttr.bg, curAttr.extended); + } + this._activeBuffer.x = 0; + this._activeBuffer.y++; + if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) { + this._activeBuffer.y--; + this._bufferService.scroll(this._eraseAttrData(), true); + } else { + if (this._activeBuffer.y >= this._bufferService.rows) { + this._activeBuffer.y = this._bufferService.rows - 1; + } + // The line already exists (eg. the initial viewport), mark it as a + // wrapped line + this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = true; + } + // row changed, get it again + bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!; + } else { + this._activeBuffer.x = cols - 1; + if (chWidth === 2) { + // FIXME: check for xterm behavior + // What to do here? We got a wide char that does not fit into last cell + continue; + } + } + } + + // insert mode: move characters to right + if (insertMode) { + // right shift cells according to the width + bufferRow.insertCells(this._activeBuffer.x, chWidth, this._activeBuffer.getNullCell(curAttr), curAttr); + // test last cell - since the last cell has only room for + // a halfwidth char any fullwidth shifted there is lost + // and will be set to empty cell + if (bufferRow.getWidth(cols - 1) === 2) { + bufferRow.setCellFromCodePoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr.fg, curAttr.bg, curAttr.extended); + } + } + + // write current char to buffer and advance cursor + bufferRow.setCellFromCodePoint(this._activeBuffer.x++, code, chWidth, curAttr.fg, curAttr.bg, curAttr.extended); + + // fullwidth char - also set next cell to placeholder stub and advance cursor + // for graphemes bigger than fullwidth we can simply loop to zero + // we already made sure above, that this._activeBuffer.x + chWidth will not overflow right + if (chWidth > 0) { + while (--chWidth) { + // other than a regular empty cell a cell following a wide char has no width + bufferRow.setCellFromCodePoint(this._activeBuffer.x++, 0, 0, curAttr.fg, curAttr.bg, curAttr.extended); + } + } + } + // store last char in Parser.precedingCodepoint for REP to work correctly + // This needs to check whether: + // - fullwidth + surrogates: reset + // - combining: only base char gets carried on (bug in xterm?) + if (end - start > 0) { + bufferRow.loadCell(this._activeBuffer.x - 1, this._workCell); + if (this._workCell.getWidth() === 2 || this._workCell.getCode() > 0xFFFF) { + this._parser.precedingCodepoint = 0; + } else if (this._workCell.isCombined()) { + this._parser.precedingCodepoint = this._workCell.getChars().charCodeAt(0); + } else { + this._parser.precedingCodepoint = this._workCell.content; + } + } + + // handle wide chars: reset cell to the right if it is second cell of a wide char + if (this._activeBuffer.x < cols && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x) === 0 && !bufferRow.hasContent(this._activeBuffer.x)) { + bufferRow.setCellFromCodePoint(this._activeBuffer.x, 0, 1, curAttr.fg, curAttr.bg, curAttr.extended); + } + + this._dirtyRowService.markDirty(this._activeBuffer.y); + } + + /** + * Forward registerCsiHandler from parser. + */ + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable { + if (id.final === 't' && !id.prefix && !id.intermediates) { + // security: always check whether window option is allowed + return this._parser.registerCsiHandler(id, params => { + if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) { + return true; + } + return callback(params); + }); + } + return this._parser.registerCsiHandler(id, callback); + } + + /** + * Forward registerDcsHandler from parser. + */ + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable { + return this._parser.registerDcsHandler(id, new DcsHandler(callback)); + } + + /** + * Forward registerEscHandler from parser. + */ + public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable { + return this._parser.registerEscHandler(id, callback); + } + + /** + * Forward registerOscHandler from parser. + */ + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable { + return this._parser.registerOscHandler(ident, new OscHandler(callback)); + } + + /** + * BEL + * Bell (Ctrl-G). + * + * @vt: #Y C0 BEL "Bell" "\a, \x07" "Ring the bell." + * The behavior of the bell is further customizable with `ITerminalOptions.bellStyle` + * and `ITerminalOptions.bellSound`. + */ + public bell(): boolean { + this._onRequestBell.fire(); + return true; + } + + /** + * LF + * Line Feed or New Line (NL). (LF is Ctrl-J). + * + * @vt: #Y C0 LF "Line Feed" "\n, \x0A" "Move the cursor one row down, scrolling if needed." + * Scrolling is restricted to scroll margins and will only happen on the bottom line. + * + * @vt: #Y C0 VT "Vertical Tabulation" "\v, \x0B" "Treated as LF." + * @vt: #Y C0 FF "Form Feed" "\f, \x0C" "Treated as LF." + */ + public lineFeed(): boolean { + this._dirtyRowService.markDirty(this._activeBuffer.y); + if (this._optionsService.rawOptions.convertEol) { + this._activeBuffer.x = 0; + } + this._activeBuffer.y++; + if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) { + this._activeBuffer.y--; + this._bufferService.scroll(this._eraseAttrData()); + } else if (this._activeBuffer.y >= this._bufferService.rows) { + this._activeBuffer.y = this._bufferService.rows - 1; + } + // If the end of the line is hit, prevent this action from wrapping around to the next line. + if (this._activeBuffer.x >= this._bufferService.cols) { + this._activeBuffer.x--; + } + this._dirtyRowService.markDirty(this._activeBuffer.y); + + this._onLineFeed.fire(); + return true; + } + + /** + * CR + * Carriage Return (Ctrl-M). + * + * @vt: #Y C0 CR "Carriage Return" "\r, \x0D" "Move the cursor to the beginning of the row." + */ + public carriageReturn(): boolean { + this._activeBuffer.x = 0; + return true; + } + + /** + * BS + * Backspace (Ctrl-H). + * + * @vt: #Y C0 BS "Backspace" "\b, \x08" "Move the cursor one position to the left." + * By default it is not possible to move the cursor past the leftmost position. + * If `reverse wrap-around` (`CSI ? 45 h`) is set, a previous soft line wrap (DECAWM) + * can be undone with BS within the scroll margins. In that case the cursor will wrap back + * 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(): boolean { + // reverse wrap-around is disabled + if (!this._coreService.decPrivateModes.reverseWraparound) { + this._restrictCursor(); + if (this._activeBuffer.x > 0) { + this._activeBuffer.x--; + } + return true; + } + + // reverse wrap-around is enabled + // other than for normal operation mode, reverse wrap-around allows the cursor + // to be at x=cols to be able to address the last cell of a row by BS + this._restrictCursor(this._bufferService.cols); + + if (this._activeBuffer.x > 0) { + this._activeBuffer.x--; + } else { + /** + * reverse wrap-around handling: + * Our implementation deviates from xterm on purpose. Details: + * - only previous soft NLs can be reversed (isWrapped=true) + * - only works within scrollborders (top/bottom, left/right not yet supported) + * - cannot peek into scrollbuffer + * - any cursor movement sequence keeps working as expected + */ + if (this._activeBuffer.x === 0 + && this._activeBuffer.y > this._activeBuffer.scrollTop + && this._activeBuffer.y <= this._activeBuffer.scrollBottom + && this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)?.isWrapped) { + this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false; + this._activeBuffer.y--; + this._activeBuffer.x = this._bufferService.cols - 1; + // find last taken cell - last cell can have 3 different states: + // - hasContent(true) + hasWidth(1): narrow char - we are done + // - hasWidth(0): second part of wide char - we are done + // - hasContent(false) + hasWidth(1): empty cell due to early wrapping wide char, go one cell further back + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!; + if (line.hasWidth(this._activeBuffer.x) && !line.hasContent(this._activeBuffer.x)) { + this._activeBuffer.x--; + // We do this only once, since width=1 + hasContent=false currently happens only once before + // early wrapping of a wide char. + // This needs to be fixed once we support graphemes taking more than 2 cells. + } + } + } + this._restrictCursor(); + return true; + } + + /** + * TAB + * Horizontal Tab (HT) (Ctrl-I). + * + * @vt: #Y C0 HT "Horizontal Tabulation" "\t, \x09" "Move the cursor to the next character tab stop." + */ + public tab(): boolean { + if (this._activeBuffer.x >= this._bufferService.cols) { + return true; + } + const originalX = this._activeBuffer.x; + this._activeBuffer.x = this._activeBuffer.nextStop(); + if (this._optionsService.rawOptions.screenReaderMode) { + this._onA11yTab.fire(this._activeBuffer.x - originalX); + } + return true; + } + + /** + * SO + * Shift Out (Ctrl-N) -> Switch to Alternate Character Set. This invokes the + * G1 character set. + * + * @vt: #P[Only limited ISO-2022 charset support.] C0 SO "Shift Out" "\x0E" "Switch to an alternative character set." + */ + public shiftOut(): boolean { + this._charsetService.setgLevel(1); + return true; + } + + /** + * SI + * Shift In (Ctrl-O) -> Switch to Standard Character Set. This invokes the G0 + * character set (the default). + * + * @vt: #Y C0 SI "Shift In" "\x0F" "Return to regular character set after Shift Out." + */ + public shiftIn(): boolean { + this._charsetService.setgLevel(0); + return true; + } + + /** + * Restrict cursor to viewport size / scroll margin (origin mode). + */ + private _restrictCursor(maxCol: number = this._bufferService.cols - 1): void { + this._activeBuffer.x = Math.min(maxCol, Math.max(0, this._activeBuffer.x)); + this._activeBuffer.y = this._coreService.decPrivateModes.origin + ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y)) + : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y)); + this._dirtyRowService.markDirty(this._activeBuffer.y); + } + + /** + * Set absolute cursor position. + */ + private _setCursor(x: number, y: number): void { + this._dirtyRowService.markDirty(this._activeBuffer.y); + if (this._coreService.decPrivateModes.origin) { + this._activeBuffer.x = x; + this._activeBuffer.y = this._activeBuffer.scrollTop + y; + } else { + this._activeBuffer.x = x; + this._activeBuffer.y = y; + } + this._restrictCursor(); + this._dirtyRowService.markDirty(this._activeBuffer.y); + } + + /** + * Set relative cursor position. + */ + private _moveCursor(x: number, y: number): void { + // for relative changes we have to make sure we are within 0 .. cols/rows - 1 + // before calculating the new position + this._restrictCursor(); + this._setCursor(this._activeBuffer.x + x, this._activeBuffer.y + y); + } + + /** + * CSI Ps A + * Cursor Up Ps Times (default = 1) (CUU). + * + * @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): boolean { + // stop at scrollTop + const diffToTop = this._activeBuffer.y - this._activeBuffer.scrollTop; + if (diffToTop >= 0) { + this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1)); + } else { + this._moveCursor(0, -(params.params[0] || 1)); + } + return true; + } + + /** + * CSI Ps B + * Cursor Down Ps Times (default = 1) (CUD). + * + * @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): boolean { + // stop at scrollBottom + const diffToBottom = this._activeBuffer.scrollBottom - this._activeBuffer.y; + if (diffToBottom >= 0) { + this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1)); + } else { + this._moveCursor(0, params.params[0] || 1); + } + return true; + } + + /** + * CSI Ps C + * Cursor Forward Ps Times (default = 1) (CUF). + * + * @vt: #Y CSI CUF "Cursor Forward" "CSI Ps C" "Move cursor `Ps` times forward (default=1)." + */ + public cursorForward(params: IParams): boolean { + this._moveCursor(params.params[0] || 1, 0); + return true; + } + + /** + * CSI Ps D + * Cursor Backward Ps Times (default = 1) (CUB). + * + * @vt: #Y CSI CUB "Cursor Backward" "CSI Ps D" "Move cursor `Ps` times backward (default=1)." + */ + public cursorBackward(params: IParams): boolean { + this._moveCursor(-(params.params[0] || 1), 0); + return true; + } + + /** + * CSI Ps E + * Cursor Next Line Ps Times (default = 1) (CNL). + * Other than cursorDown (CUD) also set the cursor to first column. + * + * @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): boolean { + this.cursorDown(params); + this._activeBuffer.x = 0; + return true; + } + + /** + * CSI Ps F + * Cursor Previous Line Ps Times (default = 1) (CPL). + * Other than cursorUp (CUU) also set the cursor to first column. + * + * @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): boolean { + this.cursorUp(params); + this._activeBuffer.x = 0; + return true; + } + + /** + * CSI Ps G + * Cursor Character Absolute [column] (default = [row,1]) (CHA). + * + * @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): boolean { + this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y); + return true; + } + + /** + * CSI Ps ; Ps H + * Cursor Position [row;column] (default = [1,1]) (CUP). + * + * @vt: #Y CSI CUP "Cursor Position" "CSI Ps ; Ps H" "Set cursor to position [`Ps`, `Ps`] (default = [1, 1])." + * If ORIGIN mode is set, places the cursor to the absolute position within the scroll margins. + * 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): boolean { + this._setCursor( + // col + (params.length >= 2) ? (params.params[1] || 1) - 1 : 0, + // row + (params.params[0] || 1) - 1 + ); + return true; + } + + /** + * CSI Pm ` Character Position Absolute + * [column] (default = [row,1]) (HPA). + * Currently same functionality as CHA. + * + * @vt: #Y CSI HPA "Horizontal Position Absolute" "CSI Ps ` " "Same as CHA." + */ + public charPosAbsolute(params: IParams): boolean { + this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y); + return true; + } + + /** + * CSI Pm a Character Position Relative + * [columns] (default = [row,col+1]) (HPR) + * + * @vt: #Y CSI HPR "Horizontal Position Relative" "CSI Ps a" "Same as CUF." + */ + public hPositionRelative(params: IParams): boolean { + this._moveCursor(params.params[0] || 1, 0); + return true; + } + + /** + * CSI Pm d Vertical Position Absolute (VPA) + * [row] (default = [1,column]) + * + * @vt: #Y CSI VPA "Vertical Position Absolute" "CSI Ps d" "Move cursor to `Ps`-th row (default=1)." + */ + public linePosAbsolute(params: IParams): boolean { + this._setCursor(this._activeBuffer.x, (params.params[0] || 1) - 1); + return true; + } + + /** + * CSI Pm e Vertical Position Relative (VPR) + * [rows] (default = [row+1,column]) + * reuse CSI Ps B ? + * + * @vt: #Y CSI VPR "Vertical Position Relative" "CSI Ps e" "Move cursor `Ps` times down (default=1)." + */ + public vPositionRelative(params: IParams): boolean { + this._moveCursor(0, params.params[0] || 1); + return true; + } + + /** + * CSI Ps ; Ps f + * Horizontal and Vertical Position [row;column] (default = + * [1,1]) (HVP). + * Same as CUP. + * + * @vt: #Y CSI HVP "Horizontal and Vertical Position" "CSI Ps ; Ps f" "Same as CUP." + */ + public hVPosition(params: IParams): boolean { + this.cursorPosition(params); + return true; + } + + /** + * CSI Ps g Tab Clear (TBC). + * Ps = 0 -> Clear Current Column (default). + * Ps = 3 -> Clear All. + * Potentially: + * Ps = 2 -> Clear Stops on Line. + * http://vt100.net/annarbor/aaa-ug/section6.html + * + * @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): boolean { + const param = params.params[0]; + if (param === 0) { + delete this._activeBuffer.tabs[this._activeBuffer.x]; + } else if (param === 3) { + this._activeBuffer.tabs = {}; + } + return true; + } + + /** + * CSI Ps I + * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT). + * + * @vt: #Y CSI CHT "Cursor Horizontal Tabulation" "CSI Ps I" "Move cursor `Ps` times tabs forward (default=1)." + */ + public cursorForwardTab(params: IParams): boolean { + if (this._activeBuffer.x >= this._bufferService.cols) { + return true; + } + let param = params.params[0] || 1; + while (param--) { + this._activeBuffer.x = this._activeBuffer.nextStop(); + } + return true; + } + + /** + * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT). + * + * @vt: #Y CSI CBT "Cursor Backward Tabulation" "CSI Ps Z" "Move cursor `Ps` tabs backward (default=1)." + */ + public cursorBackwardTab(params: IParams): boolean { + if (this._activeBuffer.x >= this._bufferService.cols) { + return true; + } + let param = params.params[0] || 1; + + while (param--) { + this._activeBuffer.x = this._activeBuffer.prevStop(); + } + return true; + } + + + /** + * Helper method to erase cells in a terminal row. + * The cell gets replaced with the eraseChar of the terminal. + * @param y row index + * @param start first cell index to be erased + * @param end end - 1 is last erased cell + * @param cleanWrap clear the isWrapped flag + */ + private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false): void { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.replaceCells( + start, + end, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData() + ); + if (clearWrap) { + line.isWrapped = false; + } + } + + /** + * Helper method to reset cells in a terminal row. + * The cell gets replaced with the eraseChar of the terminal and the isWrapped property is set to false. + * @param y row index + */ + private _resetBufferLine(y: number): void { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.fill(this._activeBuffer.getNullCell(this._eraseAttrData())); + line.isWrapped = false; + } + + /** + * CSI Ps J Erase in Display (ED). + * Ps = 0 -> Erase Below (default). + * Ps = 1 -> Erase Above. + * Ps = 2 -> Erase All. + * Ps = 3 -> Erase Saved Lines (xterm). + * CSI ? Ps J + * Erase in Display (DECSED). + * Ps = 0 -> Selective Erase Below (default). + * Ps = 1 -> Selective Erase Above. + * Ps = 2 -> Selective Erase All. + * + * @vt: #Y CSI ED "Erase In Display" "CSI Ps J" "Erase various parts of the viewport." + * Supported param values: + * + * | Ps | Effect | + * | -- | ------------------------------------------------------------ | + * | 0 | Erase from the cursor through the end of the viewport. | + * | 1 | Erase from the beginning of the viewport through the cursor. | + * | 2 | Erase complete viewport. | + * | 3 | Erase scrollback. | + * + * @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): boolean { + this._restrictCursor(this._bufferService.cols); + let j; + switch (params.params[0]) { + case 0: + j = this._activeBuffer.y; + this._dirtyRowService.markDirty(j); + this._eraseInBufferLine(j++, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0); + for (; j < this._bufferService.rows; j++) { + this._resetBufferLine(j); + } + this._dirtyRowService.markDirty(j); + break; + case 1: + j = this._activeBuffer.y; + this._dirtyRowService.markDirty(j); + // Deleted front part of line and everything before. This line will no longer be wrapped. + this._eraseInBufferLine(j, 0, this._activeBuffer.x + 1, true); + if (this._activeBuffer.x + 1 >= this._bufferService.cols) { + // Deleted entire previous line. This next line can no longer be wrapped. + this._activeBuffer.lines.get(j + 1)!.isWrapped = false; + } + while (j--) { + this._resetBufferLine(j); + } + this._dirtyRowService.markDirty(0); + break; + case 2: + j = this._bufferService.rows; + this._dirtyRowService.markDirty(j - 1); + while (j--) { + this._resetBufferLine(j); + } + this._dirtyRowService.markDirty(0); + break; + case 3: + // Clear scrollback (everything not in viewport) + const scrollBackSize = this._activeBuffer.lines.length - this._bufferService.rows; + if (scrollBackSize > 0) { + this._activeBuffer.lines.trimStart(scrollBackSize); + this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - scrollBackSize, 0); + this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - scrollBackSize, 0); + // Force a scroll event to refresh viewport + this._onScroll.fire(0); + } + break; + } + return true; + } + + /** + * CSI Ps K Erase in Line (EL). + * Ps = 0 -> Erase to Right (default). + * Ps = 1 -> Erase to Left. + * Ps = 2 -> Erase All. + * CSI ? Ps K + * Erase in Line (DECSEL). + * Ps = 0 -> Selective Erase to Right (default). + * Ps = 1 -> Selective Erase to Left. + * Ps = 2 -> Selective Erase All. + * + * @vt: #Y CSI EL "Erase In Line" "CSI Ps K" "Erase various parts of the active row." + * Supported param values: + * + * | Ps | Effect | + * | -- | -------------------------------------------------------- | + * | 0 | Erase from the cursor through the end of the row. | + * | 1 | Erase from the beginning of the line through the cursor. | + * | 2 | Erase complete line. | + * + * @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): boolean { + this._restrictCursor(this._bufferService.cols); + switch (params.params[0]) { + case 0: + this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0); + break; + case 1: + this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false); + break; + case 2: + this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true); + break; + } + this._dirtyRowService.markDirty(this._activeBuffer.y); + return true; + } + + /** + * CSI Ps L + * Insert Ps Line(s) (default = 1) (IL). + * + * @vt: #Y CSI IL "Insert Line" "CSI Ps L" "Insert `Ps` blank lines at active row (default=1)." + * For every inserted line at the scroll top one line at the scroll bottom gets removed. + * The cursor is set to the first column. + * IL has no effect if the cursor is outside the scroll margins. + */ + public insertLines(params: IParams): boolean { + this._restrictCursor(); + let param = params.params[0] || 1; + + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + + const row: number = this._activeBuffer.ybase + this._activeBuffer.y; + + const scrollBottomRowsOffset = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom; + const scrollBottomAbsolute = this._bufferService.rows - 1 + this._activeBuffer.ybase - scrollBottomRowsOffset + 1; + while (param--) { + // test: echo -e '\e[44m\e[1L\e[0m' + // blankLine(true) - xterm/linux behavior + this._activeBuffer.lines.splice(scrollBottomAbsolute - 1, 1); + this._activeBuffer.lines.splice(row, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); + } + + this._dirtyRowService.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom); + this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only? + return true; + } + + /** + * CSI Ps M + * Delete Ps Line(s) (default = 1) (DL). + * + * @vt: #Y CSI DL "Delete Line" "CSI Ps M" "Delete `Ps` lines at active row (default=1)." + * For every deleted line at the scroll top one blank line at the scroll bottom gets appended. + * The cursor is set to the first column. + * DL has no effect if the cursor is outside the scroll margins. + */ + public deleteLines(params: IParams): boolean { + this._restrictCursor(); + let param = params.params[0] || 1; + + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + + const row: number = this._activeBuffer.ybase + this._activeBuffer.y; + + let j: number; + j = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom; + j = this._bufferService.rows - 1 + this._activeBuffer.ybase - j; + while (param--) { + // test: echo -e '\e[44m\e[1M\e[0m' + // blankLine(true) - xterm/linux behavior + this._activeBuffer.lines.splice(row, 1); + this._activeBuffer.lines.splice(j, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); + } + + this._dirtyRowService.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom); + this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only? + return true; + } + + /** + * CSI Ps @ + * Insert Ps (Blank) Character(s) (default = 1) (ICH). + * + * @vt: #Y CSI ICH "Insert Characters" "CSI Ps @" "Insert `Ps` (blank) characters (default = 1)." + * The ICH sequence inserts `Ps` blank characters. The cursor remains at the beginning of the blank characters. + * Text between the cursor and right margin moves to the right. Characters moved past the right margin are lost. + * + * + * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) + */ + public insertChars(params: IParams): boolean { + this._restrictCursor(); + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); + if (line) { + line.insertCells( + this._activeBuffer.x, + params.params[0] || 1, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData() + ); + this._dirtyRowService.markDirty(this._activeBuffer.y); + } + return true; + } + + /** + * CSI Ps P + * Delete Ps Character(s) (default = 1) (DCH). + * + * @vt: #Y CSI DCH "Delete Character" "CSI Ps P" "Delete `Ps` characters (default=1)." + * As characters are deleted, the remaining characters between the cursor and right margin move to the left. + * Character attributes move with the characters. The terminal adds blank characters at the right margin. + * + * + * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual) + */ + public deleteChars(params: IParams): boolean { + this._restrictCursor(); + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); + if (line) { + line.deleteCells( + this._activeBuffer.x, + params.params[0] || 1, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData() + ); + this._dirtyRowService.markDirty(this._activeBuffer.y); + } + return true; + } + + /** + * CSI Ps S Scroll up Ps lines (default = 1) (SU). + * + * @vt: #Y CSI SU "Scroll Up" "CSI Ps S" "Scroll `Ps` lines up (default=1)." + * + * + * FIXME: scrolled out lines at top = 1 should add to scrollback (xterm) + */ + public scrollUp(params: IParams): boolean { + let param = params.params[0] || 1; + + while (param--) { + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1); + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); + } + this._dirtyRowService.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps T Scroll down Ps lines (default = 1) (SD). + * + * @vt: #Y CSI SD "Scroll Down" "CSI Ps T" "Scroll `Ps` lines down (default=1)." + */ + public scrollDown(params: IParams): boolean { + let param = params.params[0] || 1; + + while (param--) { + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1); + this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(DEFAULT_ATTR_DATA)); + } + this._dirtyRowService.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps SP @ Scroll left Ps columns (default = 1) (SL) ECMA-48 + * + * Notation: (Pn) + * Representation: CSI Pn 02/00 04/00 + * Parameter default value: Pn = 1 + * SL causes the data in the presentation component to be moved by n character positions + * if the line orientation is horizontal, or by n line positions if the line orientation + * is vertical, such that the data appear to move to the left; where n equals the value of Pn. + * The active presentation position is not affected by this control function. + * + * Supported: + * - always left shift (no line orientation setting respected) + * + * @vt: #Y CSI SL "Scroll Left" "CSI Ps SP @" "Scroll viewport `Ps` times to the left." + * 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): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.deleteCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()), this._eraseAttrData()); + line.isWrapped = false; + } + this._dirtyRowService.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps SP A Scroll right Ps columns (default = 1) (SR) ECMA-48 + * + * Notation: (Pn) + * Representation: CSI Pn 02/00 04/01 + * Parameter default value: Pn = 1 + * SR causes the data in the presentation component to be moved by n character positions + * if the line orientation is horizontal, or by n line positions if the line orientation + * is vertical, such that the data appear to move to the right; where n equals the value of Pn. + * The active presentation position is not affected by this control function. + * + * Supported: + * - always right shift (no line orientation setting respected) + * + * @vt: #Y CSI SR "Scroll Right" "CSI Ps SP A" "Scroll viewport `Ps` times to the right." + * SL moves the content of all lines within the scroll margins `Ps` times to the right. + * Content at the right margin is lost. + * SL has no effect outside of the scroll margins. + */ + public scrollRight(params: IParams): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.insertCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()), this._eraseAttrData()); + line.isWrapped = false; + } + this._dirtyRowService.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Pm ' } + * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up. + * + * @vt: #Y CSI DECIC "Insert Columns" "CSI Ps ' }" "Insert `Ps` columns at cursor position." + * DECIC inserts `Ps` times blank columns at the cursor position for all lines with the scroll margins, + * moving content to the right. Content at the right margin is lost. + * DECIC has no effect outside the scrolling margins. + */ + public insertColumns(params: IParams): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.insertCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()), this._eraseAttrData()); + line.isWrapped = false; + } + this._dirtyRowService.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Pm ' ~ + * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up. + * + * @vt: #Y CSI DECDC "Delete Columns" "CSI Ps ' ~" "Delete `Ps` columns at cursor position." + * DECDC deletes `Ps` times columns at the cursor position for all lines with the scroll margins, + * 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): boolean { + if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) { + return true; + } + const param = params.params[0] || 1; + for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) { + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!; + line.deleteCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()), this._eraseAttrData()); + line.isWrapped = false; + } + this._dirtyRowService.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + return true; + } + + /** + * CSI Ps X + * Erase Ps Character(s) (default = 1) (ECH). + * + * @vt: #Y CSI ECH "Erase Character" "CSI Ps X" "Erase `Ps` characters from current cursor position to the right (default=1)." + * ED erases `Ps` characters from current cursor position to the right. + * ED works inside or outside the scrolling margins. + */ + public eraseChars(params: IParams): boolean { + this._restrictCursor(); + const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); + if (line) { + line.replaceCells( + this._activeBuffer.x, + this._activeBuffer.x + (params.params[0] || 1), + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData() + ); + this._dirtyRowService.markDirty(this._activeBuffer.y); + } + return true; + } + + /** + * CSI Ps b Repeat the preceding graphic character Ps times (REP). + * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf) + * Notation: (Pn) + * Representation: CSI Pn 06/02 + * Parameter default value: Pn = 1 + * REP is used to indicate that the preceding character in the data stream, + * if it is a graphic character (represented by one or more bit combinations) including SPACE, + * is to be repeated n times, where n equals the value of Pn. + * If the character preceding REP is a control function or part of a control function, + * the effect of REP is not defined by this Standard. + * + * Since we propagate the terminal as xterm-256color we have to follow xterm's behavior: + * - fullwidth + surrogate chars are ignored + * - for combining chars only the base char gets repeated + * - text attrs are applied normally + * - wrap around is respected + * - any valid sequence resets the carried forward char + * + * Note: To get reset on a valid sequence working correctly without much runtime penalty, + * the preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`. + * + * @vt: #Y CSI REP "Repeat Preceding Character" "CSI Ps b" "Repeat preceding character `Ps` times (default=1)." + * REP repeats the previous character `Ps` times advancing the cursor, also wrapping if DECAWM is set. + * 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): boolean { + if (!this._parser.precedingCodepoint) { + return true; + } + // call print to insert the chars and handle correct wrapping + const length = params.params[0] || 1; + const data = new Uint32Array(length); + for (let i = 0; i < length; ++i) { + data[i] = this._parser.precedingCodepoint; + } + this.print(data, 0, data.length); + return true; + } + + /** + * CSI Ps c Send Device Attributes (Primary DA). + * Ps = 0 or omitted -> request attributes from terminal. The + * response depends on the decTerminalID resource setting. + * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'') + * -> CSI ? 1 ; 0 c (``VT101 with No Options'') + * -> CSI ? 6 c (``VT102'') + * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'') + * The VT100-style response parameters do not mean anything by + * themselves. VT220 parameters do, telling the host what fea- + * tures the terminal supports: + * Ps = 1 -> 132-columns. + * Ps = 2 -> Printer. + * Ps = 6 -> Selective erase. + * Ps = 8 -> User-defined keys. + * Ps = 9 -> National replacement character sets. + * Ps = 1 5 -> Technical characters. + * Ps = 2 2 -> ANSI color, e.g., VT525. + * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode). + * + * @vt: #Y CSI DA1 "Primary Device Attributes" "CSI c" "Send primary device attributes." + * + * + * TODO: fix and cleanup response + */ + public sendDeviceAttributesPrimary(params: IParams): boolean { + if (params.params[0] > 0) { + 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; + } + + /** + * CSI > Ps c + * Send Device Attributes (Secondary DA). + * Ps = 0 or omitted -> request the terminal's identification + * code. The response depends on the decTerminalID resource set- + * ting. It should apply only to VT220 and up, but xterm extends + * this to VT100. + * -> CSI > Pp ; Pv ; Pc c + * where Pp denotes the terminal type + * Pp = 0 -> ``VT100''. + * Pp = 1 -> ``VT220''. + * and Pv is the firmware version (for xterm, this was originally + * the XFree86 patch number, starting with 95). In a DEC termi- + * nal, Pc indicates the ROM cartridge registration number and is + * always zero. + * More information: + * xterm/charproc.c - line 2012, for more information. + * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?) + * + * @vt: #Y CSI DA2 "Secondary Device Attributes" "CSI > c" "Send primary device attributes." + * + * + * TODO: fix and cleanup response + */ + public sendDeviceAttributesSecondary(params: IParams): boolean { + if (params.params[0] > 0) { + return true; + } + // xterm and urxvt + // seem to spit this + // out around ~370 times (?). + if (this._is('xterm')) { + this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c'); + } else if (this._is('rxvt-unicode')) { + this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c'); + } else if (this._is('linux')) { + // not supported by linux console. + // linux console echoes parameters. + this._coreService.triggerDataEvent(params.params[0] + 'c'); + } else if (this._is('screen')) { + this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c'); + } + return true; + } + + /** + * Evaluate if the current terminal is the given argument. + * @param term The terminal name to evaluate + */ + private _is(term: string): boolean { + return (this._optionsService.rawOptions.termName + '').indexOf(term) === 0; + } + + /** + * CSI Pm h Set Mode (SM). + * Ps = 2 -> Keyboard Action Mode (AM). + * Ps = 4 -> Insert Mode (IRM). + * Ps = 1 2 -> Send/receive (SRM). + * Ps = 2 0 -> Automatic Newline (LNM). + * + * @vt: #P[Only IRM is supported.] CSI SM "Set Mode" "CSI Pm h" "Set various terminal modes." + * Supported param values by SM: + * + * | Param | Action | Support | + * | ----- | -------------------------------------- | ------- | + * | 2 | Keyboard Action Mode (KAM). Always on. | #N | + * | 4 | Insert Mode (IRM). | #Y | + * | 12 | Send/receive (SRM). Always off. | #N | + * | 20 | Automatic Newline (LNM). Always off. | #N | + */ + public setMode(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 4: + this._coreService.modes.insertMode = true; + break; + case 20: + // this._t.convertEol = true; + break; + } + } + return true; + } + + /** + * CSI ? Pm h + * DEC Private Mode Set (DECSET). + * Ps = 1 -> Application Cursor Keys (DECCKM). + * Ps = 2 -> Designate USASCII for character sets G0-G3 + * (DECANM), and set VT100 mode. + * Ps = 3 -> 132 Column Mode (DECCOLM). + * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM). + * Ps = 5 -> Reverse Video (DECSCNM). + * Ps = 6 -> Origin Mode (DECOM). + * Ps = 7 -> Wraparound Mode (DECAWM). + * Ps = 8 -> Auto-repeat Keys (DECARM). + * Ps = 9 -> Send Mouse X & Y on button press. See the sec- + * tion Mouse Tracking. + * Ps = 1 0 -> Show toolbar (rxvt). + * Ps = 1 2 -> Start Blinking Cursor (att610). + * Ps = 1 8 -> Print form feed (DECPFF). + * Ps = 1 9 -> Set print extent to full screen (DECPEX). + * Ps = 2 5 -> Show Cursor (DECTCEM). + * Ps = 3 0 -> Show scrollbar (rxvt). + * Ps = 3 5 -> Enable font-shifting functions (rxvt). + * Ps = 3 8 -> Enter Tektronix Mode (DECTEK). + * Ps = 4 0 -> Allow 80 -> 132 Mode. + * Ps = 4 1 -> more(1) fix (see curses resource). + * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN- + * RCM). + * Ps = 4 4 -> Turn On Margin Bell. + * Ps = 4 5 -> Reverse-wraparound Mode. + * Ps = 4 6 -> Start Logging. This is normally disabled by a + * compile-time option. + * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis- + * abled by the titeInhibit resource). + * Ps = 6 6 -> Application keypad (DECNKM). + * Ps = 6 7 -> Backarrow key sends backspace (DECBKM). + * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and + * release. See the section Mouse Tracking. + * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking. + * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking. + * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking. + * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events. + * Ps = 1 0 0 5 -> Enable Extended Mouse Mode. + * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt). + * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt). + * Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit. + * (enables the eightBitInput resource). + * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num- + * Lock keys. (This enables the numLock resource). + * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This + * enables the metaSendsEscape resource). + * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete + * key. + * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This + * enables the altSendsEscape resource). + * Ps = 1 0 4 0 -> Keep selection even if not highlighted. + * (This enables the keepSelection resource). + * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables + * the selectToClipboard resource). + * Ps = 1 0 4 2 -> Enable Urgency window manager hint when + * Control-G is received. (This enables the bellIsUrgent + * resource). + * Ps = 1 0 4 3 -> Enable raising of the window when Control-G + * is received. (enables the popOnBell resource). + * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be + * disabled by the titeInhibit resource). + * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis- + * abled by the titeInhibit resource). + * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate + * Screen Buffer, clearing it first. (This may be disabled by + * the titeInhibit resource). This combines the effects of the 1 + * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based + * applications rather than the 4 7 mode. + * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode. + * Ps = 1 0 5 1 -> Set Sun function-key mode. + * Ps = 1 0 5 2 -> Set HP function-key mode. + * Ps = 1 0 5 3 -> Set SCO function-key mode. + * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6). + * Ps = 1 0 6 1 -> Set VT220 keyboard emulation. + * Ps = 2 0 0 4 -> Set bracketed paste mode. + * Modes: + * http: *vt100.net/docs/vt220-rm/chapter4.html + * + * @vt: #P[See below for supported modes.] CSI DECSET "DEC Private Set Mode" "CSI ? Pm h" "Set various terminal attributes." + * Supported param values by DECSET: + * + * | param | Action | Support | + * | ----- | ------------------------------------------------------- | --------| + * | 1 | Application Cursor Keys (DECCKM). | #Y | + * | 2 | Designate US-ASCII for character sets G0-G3 (DECANM). | #Y | + * | 3 | 132 Column Mode (DECCOLM). | #Y | + * | 6 | Origin Mode (DECOM). | #Y | + * | 7 | Auto-wrap Mode (DECAWM). | #Y | + * | 8 | Auto-repeat Keys (DECARM). Always on. | #N | + * | 9 | X10 xterm mouse protocol. | #Y | + * | 12 | Start Blinking Cursor. | #Y | + * | 25 | Show Cursor (DECTCEM). | #Y | + * | 45 | Reverse wrap-around. | #Y | + * | 47 | Use Alternate Screen Buffer. | #Y | + * | 66 | Application keypad (DECNKM). | #Y | + * | 1000 | X11 xterm mouse protocol. | #Y | + * | 1002 | Use Cell Motion Mouse Tracking. | #Y | + * | 1003 | Use All Motion Mouse Tracking. | #Y | + * | 1004 | Send FocusIn/FocusOut events | #Y | + * | 1005 | Enable UTF-8 Mouse Mode. | #N | + * | 1006 | Enable SGR Mouse Mode. | #Y | + * | 1015 | Enable urxvt Mouse Mode. | #N | + * | 1047 | Use Alternate Screen Buffer. | #Y | + * | 1048 | Save cursor as in DECSC. | #Y | + * | 1049 | Save cursor and switch to alternate buffer clearing it. | #P[Does not clear the alternate buffer.] | + * | 2004 | Set bracketed paste mode. | #Y | + * + * + * FIXME: implement DECSCNM, 1049 should clear altbuffer + */ + public setModePrivate(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 1: + this._coreService.decPrivateModes.applicationCursorKeys = true; + break; + case 2: + this._charsetService.setgCharset(0, DEFAULT_CHARSET); + this._charsetService.setgCharset(1, DEFAULT_CHARSET); + this._charsetService.setgCharset(2, DEFAULT_CHARSET); + this._charsetService.setgCharset(3, DEFAULT_CHARSET); + // set VT100 mode here + break; + case 3: + /** + * DECCOLM - 132 column mode. + * This is only active if 'SetWinLines' (24) is enabled + * through `options.windowsOptions`. + */ + if (this._optionsService.rawOptions.windowOptions.setWinLines) { + this._bufferService.resize(132, this._bufferService.rows); + this._onRequestReset.fire(); + } + break; + case 6: + this._coreService.decPrivateModes.origin = true; + this._setCursor(0, 0); + break; + case 7: + this._coreService.decPrivateModes.wraparound = true; + break; + case 12: + // this.cursorBlink = true; + break; + case 45: + this._coreService.decPrivateModes.reverseWraparound = true; + break; + case 66: + this._logService.debug('Serial port requested application keypad.'); + this._coreService.decPrivateModes.applicationKeypad = true; + this._onRequestSyncScrollBar.fire(); + break; + case 9: // X10 Mouse + // no release, no motion, no wheel, no modifiers. + this._coreMouseService.activeProtocol = 'X10'; + break; + case 1000: // vt200 mouse + // no motion. + this._coreMouseService.activeProtocol = 'VT200'; + break; + case 1002: // button event mouse + this._coreMouseService.activeProtocol = 'DRAG'; + break; + case 1003: // any event mouse + // any event - sends motion events, + // even if there is no button held down. + this._coreMouseService.activeProtocol = 'ANY'; + break; + case 1004: // send focusin/focusout events + // focusin: ^[[I + // focusout: ^[[O + this._coreService.decPrivateModes.sendFocus = true; + this._onRequestSendFocus.fire(); + break; + case 1005: // utf8 ext mode mouse - removed in #2507 + this._logService.debug('DECSET 1005 not supported (see #2507)'); + break; + case 1006: // sgr ext mode mouse + this._coreMouseService.activeEncoding = 'SGR'; + break; + case 1015: // urxvt ext mode mouse - removed in #2507 + this._logService.debug('DECSET 1015 not supported (see #2507)'); + break; + case 25: // show cursor + this._coreService.isCursorHidden = false; + break; + case 1048: // alt screen cursor + this.saveCursor(); + break; + case 1049: // alt screen buffer cursor + this.saveCursor(); + // FALL-THROUGH + case 47: // alt screen buffer + case 1047: // alt screen buffer + this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()); + this._coreService.isCursorInitialized = true; + this._onRequestRefreshRows.fire(0, this._bufferService.rows - 1); + this._onRequestSyncScrollBar.fire(); + break; + case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste) + this._coreService.decPrivateModes.bracketedPasteMode = true; + break; + } + } + return true; + } + + + /** + * CSI Pm l Reset Mode (RM). + * Ps = 2 -> Keyboard Action Mode (AM). + * Ps = 4 -> Replace Mode (IRM). + * Ps = 1 2 -> Send/receive (SRM). + * Ps = 2 0 -> Normal Linefeed (LNM). + * + * @vt: #P[Only IRM is supported.] CSI RM "Reset Mode" "CSI Pm l" "Set various terminal attributes." + * Supported param values by RM: + * + * | Param | Action | Support | + * | ----- | -------------------------------------- | ------- | + * | 2 | Keyboard Action Mode (KAM). Always on. | #N | + * | 4 | Replace Mode (IRM). (default) | #Y | + * | 12 | Send/receive (SRM). Always off. | #N | + * | 20 | Normal Linefeed (LNM). Always off. | #N | + * + * + * FIXME: why is LNM commented out? + */ + public resetMode(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 4: + this._coreService.modes.insertMode = false; + break; + case 20: + // this._t.convertEol = false; + break; + } + } + return true; + } + + /** + * CSI ? Pm l + * DEC Private Mode Reset (DECRST). + * Ps = 1 -> Normal Cursor Keys (DECCKM). + * Ps = 2 -> Designate VT52 mode (DECANM). + * Ps = 3 -> 80 Column Mode (DECCOLM). + * Ps = 4 -> Jump (Fast) Scroll (DECSCLM). + * Ps = 5 -> Normal Video (DECSCNM). + * Ps = 6 -> Normal Cursor Mode (DECOM). + * Ps = 7 -> No Wraparound Mode (DECAWM). + * Ps = 8 -> No Auto-repeat Keys (DECARM). + * Ps = 9 -> Don't send Mouse X & Y on button press. + * Ps = 1 0 -> Hide toolbar (rxvt). + * Ps = 1 2 -> Stop Blinking Cursor (att610). + * Ps = 1 8 -> Don't print form feed (DECPFF). + * Ps = 1 9 -> Limit print to scrolling region (DECPEX). + * Ps = 2 5 -> Hide Cursor (DECTCEM). + * Ps = 3 0 -> Don't show scrollbar (rxvt). + * Ps = 3 5 -> Disable font-shifting functions (rxvt). + * Ps = 4 0 -> Disallow 80 -> 132 Mode. + * Ps = 4 1 -> No more(1) fix (see curses resource). + * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC- + * NRCM). + * Ps = 4 4 -> Turn Off Margin Bell. + * Ps = 4 5 -> No Reverse-wraparound Mode. + * Ps = 4 6 -> Stop Logging. (This is normally disabled by a + * compile-time option). + * Ps = 4 7 -> Use Normal Screen Buffer. + * Ps = 6 6 -> Numeric keypad (DECNKM). + * Ps = 6 7 -> Backarrow key sends delete (DECBKM). + * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and + * release. See the section Mouse Tracking. + * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking. + * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking. + * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking. + * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events. + * Ps = 1 0 0 5 -> Disable Extended Mouse Mode. + * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output + * (rxvt). + * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt). + * Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables + * the eightBitInput resource). + * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num- + * Lock keys. (This disables the numLock resource). + * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key. + * (This disables the metaSendsEscape resource). + * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad + * Delete key. + * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key. + * (This disables the altSendsEscape resource). + * Ps = 1 0 4 0 -> Do not keep selection when not highlighted. + * (This disables the keepSelection resource). + * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables + * the selectToClipboard resource). + * Ps = 1 0 4 2 -> Disable Urgency window manager hint when + * Control-G is received. (This disables the bellIsUrgent + * resource). + * Ps = 1 0 4 3 -> Disable raising of the window when Control- + * G is received. (This disables the popOnBell resource). + * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen + * first if in the Alternate Screen. (This may be disabled by + * the titeInhibit resource). + * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be + * disabled by the titeInhibit resource). + * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor + * as in DECRC. (This may be disabled by the titeInhibit + * resource). This combines the effects of the 1 0 4 7 and 1 0 + * 4 8 modes. Use this with terminfo-based applications rather + * than the 4 7 mode. + * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode. + * Ps = 1 0 5 1 -> Reset Sun function-key mode. + * Ps = 1 0 5 2 -> Reset HP function-key mode. + * Ps = 1 0 5 3 -> Reset SCO function-key mode. + * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6). + * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style. + * Ps = 2 0 0 4 -> Reset bracketed paste mode. + * + * @vt: #P[See below for supported modes.] CSI DECRST "DEC Private Reset Mode" "CSI ? Pm l" "Reset various terminal attributes." + * Supported param values by DECRST: + * + * | param | Action | Support | + * | ----- | ------------------------------------------------------- | ------- | + * | 1 | Normal Cursor Keys (DECCKM). | #Y | + * | 2 | Designate VT52 mode (DECANM). | #N | + * | 3 | 80 Column Mode (DECCOLM). | #B[Switches to old column width instead of 80.] | + * | 6 | Normal Cursor Mode (DECOM). | #Y | + * | 7 | No Wraparound Mode (DECAWM). | #Y | + * | 8 | No Auto-repeat Keys (DECARM). | #N | + * | 9 | Don't send Mouse X & Y on button press. | #Y | + * | 12 | Stop Blinking Cursor. | #Y | + * | 25 | Hide Cursor (DECTCEM). | #Y | + * | 45 | No reverse wrap-around. | #Y | + * | 47 | Use Normal Screen Buffer. | #Y | + * | 66 | Numeric keypad (DECNKM). | #Y | + * | 1000 | Don't send Mouse reports. | #Y | + * | 1002 | Don't use Cell Motion Mouse Tracking. | #Y | + * | 1003 | Don't use All Motion Mouse Tracking. | #Y | + * | 1004 | Don't send FocusIn/FocusOut events. | #Y | + * | 1005 | Disable UTF-8 Mouse Mode. | #N | + * | 1006 | Disable SGR Mouse Mode. | #Y | + * | 1015 | Disable urxvt Mouse Mode. | #N | + * | 1047 | Use Normal Screen Buffer (clearing screen if in alt). | #Y | + * | 1048 | Restore cursor as in DECRC. | #Y | + * | 1049 | Use Normal Screen Buffer and restore cursor. | #Y | + * | 2004 | Reset bracketed paste mode. | #Y | + * + * + * FIXME: DECCOLM is currently broken (already fixed in window options PR) + */ + public resetModePrivate(params: IParams): boolean { + for (let i = 0; i < params.length; i++) { + switch (params.params[i]) { + case 1: + this._coreService.decPrivateModes.applicationCursorKeys = false; + break; + case 3: + /** + * DECCOLM - 80 column mode. + * This is only active if 'SetWinLines' (24) is enabled + * through `options.windowsOptions`. + */ + if (this._optionsService.rawOptions.windowOptions.setWinLines) { + this._bufferService.resize(80, this._bufferService.rows); + this._onRequestReset.fire(); + } + break; + case 6: + this._coreService.decPrivateModes.origin = false; + this._setCursor(0, 0); + break; + case 7: + this._coreService.decPrivateModes.wraparound = false; + break; + case 12: + // this.cursorBlink = false; + break; + case 45: + this._coreService.decPrivateModes.reverseWraparound = false; + break; + case 66: + this._logService.debug('Switching back to normal keypad.'); + this._coreService.decPrivateModes.applicationKeypad = false; + this._onRequestSyncScrollBar.fire(); + break; + case 9: // X10 Mouse + case 1000: // vt200 mouse + case 1002: // button event mouse + case 1003: // any event mouse + this._coreMouseService.activeProtocol = 'NONE'; + break; + case 1004: // send focusin/focusout events + this._coreService.decPrivateModes.sendFocus = false; + break; + case 1005: // utf8 ext mode mouse - removed in #2507 + this._logService.debug('DECRST 1005 not supported (see #2507)'); + break; + case 1006: // sgr ext mode mouse + this._coreMouseService.activeEncoding = 'DEFAULT'; + break; + case 1015: // urxvt ext mode mouse - removed in #2507 + this._logService.debug('DECRST 1015 not supported (see #2507)'); + break; + case 25: // hide cursor + this._coreService.isCursorHidden = true; + break; + case 1048: // alt screen cursor + this.restoreCursor(); + break; + case 1049: // alt screen buffer cursor + // FALL-THROUGH + case 47: // normal screen buffer + case 1047: // normal screen buffer - clearing it first + // Ensure the selection manager has the correct buffer + this._bufferService.buffers.activateNormalBuffer(); + if (params.params[i] === 1049) { + this.restoreCursor(); + } + this._coreService.isCursorInitialized = true; + this._onRequestRefreshRows.fire(0, this._bufferService.rows - 1); + this._onRequestSyncScrollBar.fire(); + break; + case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste) + this._coreService.decPrivateModes.bracketedPasteMode = false; + break; + } + } + return true; + } + + /** + * Helper to write color information packed with color mode. + */ + private _updateAttrColor(color: number, mode: number, c1: number, c2: number, c3: number): number { + if (mode === 2) { + color |= Attributes.CM_RGB; + color &= ~Attributes.RGB_MASK; + color |= AttributeData.fromColorRGB([c1, c2, c3]); + } else if (mode === 5) { + color &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + color |= Attributes.CM_P256 | (c1 & 0xff); + } + return color; + } + + /** + * Helper to extract and apply color params/subparams. + * Returns advance for params index. + */ + private _extractColor(params: IParams, pos: number, attr: IAttributeData): number { + // normalize params + // meaning: [target, CM, ign, val, val, val] + // RGB : [ 38/48, 2, ign, r, g, b] + // P256 : [ 38/48, 5, ign, v, ign, ign] + const accu = [0, 0, -1, 0, 0, 0]; + + // alignment placeholder for non color space sequences + let cSpace = 0; + + // return advance we took in params + let advance = 0; + + do { + accu[advance + cSpace] = params.params[pos + advance]; + if (params.hasSubParams(pos + advance)) { + const subparams = params.getSubParams(pos + advance)!; + let i = 0; + do { + if (accu[1] === 5) { + cSpace = 1; + } + accu[advance + i + 1 + cSpace] = subparams[i]; + } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length); + break; + } + // exit early if can decide color mode with semicolons + if ((accu[1] === 5 && advance + cSpace >= 2) + || (accu[1] === 2 && advance + cSpace >= 5)) { + break; + } + // offset colorSpace slot for semicolon mode + if (accu[1]) { + cSpace = 1; + } + } while (++advance + pos < params.length && advance + cSpace < accu.length); + + // set default values to 0 + for (let i = 2; i < accu.length; ++i) { + if (accu[i] === -1) { + accu[i] = 0; + } + } + + // apply colors + switch (accu[0]) { + case 38: + attr.fg = this._updateAttrColor(attr.fg, accu[1], accu[3], accu[4], accu[5]); + break; + case 48: + attr.bg = this._updateAttrColor(attr.bg, accu[1], accu[3], accu[4], accu[5]); + break; + case 58: + attr.extended = attr.extended.clone(); + attr.extended.underlineColor = this._updateAttrColor(attr.extended.underlineColor, accu[1], accu[3], accu[4], accu[5]); + } + + return advance; + } + + /** + * SGR 4 subparams: + * 4:0 - equal to SGR 24 (turn off all underline) + * 4:1 - equal to SGR 4 (single underline) + * 4:2 - equal to SGR 21 (double underline) + * 4:3 - curly underline + * 4:4 - dotted underline + * 4:5 - dashed underline + */ + private _processUnderline(style: number, attr: IAttributeData): void { + // treat extended attrs as immutable, thus always clone from old one + // this is needed since the buffer only holds references to it + attr.extended = attr.extended.clone(); + + // default to 1 == single underline + if (!~style || style > 5) { + style = 1; + } + attr.extended.underlineStyle = style; + attr.fg |= FgFlags.UNDERLINE; + + // 0 deactivates underline + if (style === 0) { + attr.fg &= ~FgFlags.UNDERLINE; + } + + // update HAS_EXTENDED in BG + attr.updateExtended(); + } + + /** + * CSI Pm m Character Attributes (SGR). + * + * @vt: #P[See below for supported attributes.] CSI SGR "Select Graphic Rendition" "CSI Pm m" "Set/Reset various text attributes." + * SGR selects one or more character attributes at the same time. Multiple params (up to 32) + * are applied in order from left to right. The changed attributes are applied to all new + * characters received. If you move characters in the viewport by scrolling or any other means, + * then the attributes move with the characters. + * + * Supported param values by SGR: + * + * | Param | Meaning | Support | + * | --------- | -------------------------------------------------------- | ------- | + * | 0 | Normal (default). Resets any other preceding SGR. | #Y | + * | 1 | Bold. (also see `options.drawBoldTextInBrightColors`) | #Y | + * | 2 | Faint, decreased intensity. | #Y | + * | 3 | Italic. | #Y | + * | 4 | Underlined (see below for style support). | #Y | + * | 5 | Slowly blinking. | #N | + * | 6 | Rapidly blinking. | #N | + * | 7 | Inverse. Flips foreground and background color. | #Y | + * | 8 | Invisible (hidden). | #Y | + * | 9 | Crossed-out characters (strikethrough). | #Y | + * | 21 | Doubly underlined. | #P[Currently outputs a single underline.] | + * | 22 | Normal (neither bold nor faint). | #Y | + * | 23 | No italic. | #Y | + * | 24 | Not underlined. | #Y | + * | 25 | Steady (not blinking). | #Y | + * | 27 | Positive (not inverse). | #Y | + * | 28 | Visible (not hidden). | #Y | + * | 29 | Not Crossed-out (strikethrough). | #Y | + * | 30 | Foreground color: Black. | #Y | + * | 31 | Foreground color: Red. | #Y | + * | 32 | Foreground color: Green. | #Y | + * | 33 | Foreground color: Yellow. | #Y | + * | 34 | Foreground color: Blue. | #Y | + * | 35 | Foreground color: Magenta. | #Y | + * | 36 | Foreground color: Cyan. | #Y | + * | 37 | Foreground color: White. | #Y | + * | 38 | Foreground color: Extended color. | #P[Support for RGB and indexed colors, see below.] | + * | 39 | Foreground color: Default (original). | #Y | + * | 40 | Background color: Black. | #Y | + * | 41 | Background color: Red. | #Y | + * | 42 | Background color: Green. | #Y | + * | 43 | Background color: Yellow. | #Y | + * | 44 | Background color: Blue. | #Y | + * | 45 | Background color: Magenta. | #Y | + * | 46 | Background color: Cyan. | #Y | + * | 47 | Background color: White. | #Y | + * | 48 | Background color: Extended color. | #P[Support for RGB and indexed colors, see below.] | + * | 49 | Background color: Default (original). | #Y | + * | 90 - 97 | Bright foreground color (analogous to 30 - 37). | #Y | + * | 100 - 107 | Bright background color (analogous to 40 - 47). | #Y | + * + * Underline supports subparams to denote the style in the form `4 : x`: + * + * | x | Meaning | Support | + * | ------ | ------------------------------------------------------------- | ------- | + * | 0 | No underline. Same as `SGR 24 m`. | #Y | + * | 1 | Single underline. Same as `SGR 4 m`. | #Y | + * | 2 | Double underline. | #P[Currently outputs a single underline.] | + * | 3 | Curly underline. | #P[Currently outputs a single underline.] | + * | 4 | Dotted underline. | #P[Currently outputs a single underline.] | + * | 5 | Dashed underline. | #P[Currently outputs a single underline.] | + * | other | Single underline. Same as `SGR 4 m`. | #Y | + * + * Extended colors are supported for foreground (Ps=38) and background (Ps=48) as follows: + * + * | Ps + 1 | Meaning | Support | + * | ------ | ------------------------------------------------------------- | ------- | + * | 0 | Implementation defined. | #N | + * | 1 | Transparent. | #N | + * | 2 | RGB color as `Ps ; 2 ; R ; G ; B` or `Ps : 2 : : R : G : B`. | #Y | + * | 3 | CMY color. | #N | + * | 4 | CMYK color. | #N | + * | 5 | Indexed (256 colors) as `Ps ; 5 ; INDEX` or `Ps : 5 : INDEX`. | #Y | + * + * + * FIXME: blinking is implemented in attrs, but not working in renderers? + * FIXME: remove dead branch for p=100 + */ + 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 true; + } + + const l = params.length; + let p; + const attr = this._curAttrData; + + for (let i = 0; i < l; i++) { + p = params.params[i]; + if (p >= 30 && p <= 37) { + // fg color 8 + attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.fg |= Attributes.CM_P16 | (p - 30); + } else if (p >= 40 && p <= 47) { + // bg color 8 + attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.bg |= Attributes.CM_P16 | (p - 40); + } else if (p >= 90 && p <= 97) { + // fg color 16 + attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.fg |= Attributes.CM_P16 | (p - 90) | 8; + } else if (p >= 100 && p <= 107) { + // bg color 16 + attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK); + attr.bg |= Attributes.CM_P16 | (p - 100) | 8; + } else if (p === 0) { + // default + attr.fg = DEFAULT_ATTR_DATA.fg; + attr.bg = DEFAULT_ATTR_DATA.bg; + } else if (p === 1) { + // bold text + attr.fg |= FgFlags.BOLD; + } else if (p === 3) { + // italic text + attr.bg |= BgFlags.ITALIC; + } else if (p === 4) { + // underlined text + attr.fg |= FgFlags.UNDERLINE; + this._processUnderline(params.hasSubParams(i) ? params.getSubParams(i)![0] : UnderlineStyle.SINGLE, attr); + } else if (p === 5) { + // blink + attr.fg |= FgFlags.BLINK; + } else if (p === 7) { + // inverse and positive + // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m' + attr.fg |= FgFlags.INVERSE; + } else if (p === 8) { + // invisible + attr.fg |= FgFlags.INVISIBLE; + } else if (p === 9) { + // strikethrough + attr.fg |= FgFlags.STRIKETHROUGH; + } else if (p === 2) { + // dimmed text + attr.bg |= BgFlags.DIM; + } else if (p === 21) { + // double underline + this._processUnderline(UnderlineStyle.DOUBLE, attr); + } else if (p === 22) { + // not bold nor faint + attr.fg &= ~FgFlags.BOLD; + attr.bg &= ~BgFlags.DIM; + } else if (p === 23) { + // not italic + attr.bg &= ~BgFlags.ITALIC; + } else if (p === 24) { + // not underlined + attr.fg &= ~FgFlags.UNDERLINE; + } else if (p === 25) { + // not blink + attr.fg &= ~FgFlags.BLINK; + } else if (p === 27) { + // not inverse + attr.fg &= ~FgFlags.INVERSE; + } else if (p === 28) { + // not invisible + attr.fg &= ~FgFlags.INVISIBLE; + } else if (p === 29) { + // not strikethrough + attr.fg &= ~FgFlags.STRIKETHROUGH; + } else if (p === 39) { + // reset fg + attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + } else if (p === 49) { + // reset bg + attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + } else if (p === 38 || p === 48 || p === 58) { + // fg color 256 and RGB + i += this._extractColor(params, i, attr); + } else if (p === 59) { + attr.extended = attr.extended.clone(); + attr.extended.underlineColor = -1; + attr.updateExtended(); + } else if (p === 100) { // FIXME: dead branch, p=100 already handled above! + // reset fg/bg + attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK); + attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK); + } else { + this._logService.debug('Unknown SGR attribute: %d.', p); + } + } + return true; + } + + /** + * CSI Ps n Device Status Report (DSR). + * Ps = 5 -> Status Report. Result (``OK'') is + * CSI 0 n + * Ps = 6 -> Report Cursor Position (CPR) [row;column]. + * Result is + * CSI r ; c R + * CSI ? Ps n + * Device Status Report (DSR, DEC-specific). + * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI + * ? r ; c R (assumes page is zero). + * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready). + * or CSI ? 1 1 n (not ready). + * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked) + * or CSI ? 2 1 n (locked). + * Ps = 2 6 -> Report Keyboard status as + * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American). + * The last two parameters apply to VT400 & up, and denote key- + * board ready and LK01 respectively. + * Ps = 5 3 -> Report Locator status as + * CSI ? 5 3 n Locator available, if compiled-in, or + * CSI ? 5 0 n No Locator, if not. + * + * @vt: #Y CSI DSR "Device Status Report" "CSI Ps n" "Request cursor position (CPR) with `Ps` = 6." + */ + public deviceStatus(params: IParams): boolean { + switch (params.params[0]) { + case 5: + // status report + this._coreService.triggerDataEvent(`${C0.ESC}[0n`); + break; + case 6: + // cursor position + const y = this._activeBuffer.y + 1; + const x = this._activeBuffer.x + 1; + 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): boolean { + // modern xterm doesnt seem to + // respond to any of these except ?6, 6, and 5 + switch (params.params[0]) { + case 6: + // cursor position + const y = this._activeBuffer.y + 1; + const x = this._activeBuffer.x + 1; + this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`); + break; + case 15: + // no printer + // this.handler(C0.ESC + '[?11n'); + break; + case 25: + // dont support user defined keys + // this.handler(C0.ESC + '[?21n'); + break; + case 26: + // north american keyboard + // this.handler(C0.ESC + '[?27;1;0;0n'); + break; + case 53: + // no dec locator/mouse + // this.handler(C0.ESC + '[?50n'); + break; + } + return true; + } + + /** + * CSI ! p Soft terminal reset (DECSTR). + * http://vt100.net/docs/vt220-rm/table4-10.html + * + * @vt: #Y CSI DECSTR "Soft Terminal Reset" "CSI ! p" "Reset several terminal attributes to initial state." + * There are two terminal reset sequences - RIS and DECSTR. While RIS performs almost a full terminal bootstrap, + * DECSTR only resets certain attributes. For most needs DECSTR should be sufficient. + * + * The following terminal attributes are reset to default values: + * - IRM is reset (dafault = false) + * - scroll margins are reset (default = viewport size) + * - erase attributes are reset to default + * - charsets are reset + * - DECSC data is reset to initial values + * - DECOM is reset to absolute mode + * + * + * FIXME: there are several more attributes missing (see VT520 manual) + */ + public softReset(params: IParams): boolean { + this._coreService.isCursorHidden = false; + this._onRequestSyncScrollBar.fire(); + this._activeBuffer.scrollTop = 0; + this._activeBuffer.scrollBottom = this._bufferService.rows - 1; + this._curAttrData = DEFAULT_ATTR_DATA.clone(); + this._coreService.reset(); + this._charsetService.reset(); + + // reset DECSC data + this._activeBuffer.savedX = 0; + this._activeBuffer.savedY = this._activeBuffer.ybase; + this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg; + this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg; + this._activeBuffer.savedCharset = this._charsetService.charset; + + // reset DECOM + this._coreService.decPrivateModes.origin = false; + return true; + } + + /** + * CSI Ps SP q Set cursor style (DECSCUSR, VT520). + * Ps = 0 -> blinking block. + * Ps = 1 -> blinking block (default). + * Ps = 2 -> steady block. + * Ps = 3 -> blinking underline. + * Ps = 4 -> steady underline. + * Ps = 5 -> blinking bar (xterm). + * Ps = 6 -> steady bar (xterm). + * + * @vt: #Y CSI DECSCUSR "Set Cursor Style" "CSI Ps SP q" "Set cursor style." + * Supported cursor styles: + * - empty, 0 or 1: steady block + * - 2: blink block + * - 3: steady underline + * - 4: blink underline + * - 5: steady bar + * - 6: blink bar + */ + public setCursorStyle(params: IParams): boolean { + const param = params.params[0] || 1; + switch (param) { + case 1: + case 2: + this._optionsService.options.cursorStyle = 'block'; + break; + case 3: + case 4: + this._optionsService.options.cursorStyle = 'underline'; + break; + case 5: + case 6: + this._optionsService.options.cursorStyle = 'bar'; + break; + } + const isBlinking = param % 2 === 1; + this._optionsService.options.cursorBlink = isBlinking; + return true; + } + + /** + * CSI Ps ; Ps r + * Set Scrolling Region [top;bottom] (default = full size of win- + * dow) (DECSTBM). + * + * @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): boolean { + const top = params.params[0] || 1; + let bottom: number; + + if (params.length < 2 || (bottom = params.params[1]) > this._bufferService.rows || bottom === 0) { + bottom = this._bufferService.rows; + } + + if (bottom > top) { + this._activeBuffer.scrollTop = top - 1; + this._activeBuffer.scrollBottom = bottom - 1; + this._setCursor(0, 0); + } + return true; + } + + /** + * CSI Ps ; Ps ; Ps t - Various window manipulations and reports (xterm) + * + * Note: Only those listed below are supported. All others are left to integrators and + * need special treatment based on the embedding environment. + * + * Ps = 1 4 supported + * Report xterm text area size in pixels. + * Result is CSI 4 ; height ; width t + * Ps = 14 ; 2 not implemented + * Ps = 16 supported + * Report xterm character cell size in pixels. + * Result is CSI 6 ; height ; width t + * Ps = 18 supported + * Report the size of the text area in characters. + * Result is CSI 8 ; height ; width t + * Ps = 20 supported + * Report xterm window's icon label. + * Result is OSC L label ST + * Ps = 21 supported + * Report xterm window's title. + * Result is OSC l label ST + * Ps = 22 ; 0 -> Save xterm icon and window title on stack. supported + * Ps = 22 ; 1 -> Save xterm icon title on stack. supported + * Ps = 22 ; 2 -> Save xterm window title on stack. supported + * Ps = 23 ; 0 -> Restore xterm icon and window title from stack. supported + * Ps = 23 ; 1 -> Restore xterm icon title from stack. supported + * Ps = 23 ; 2 -> Restore xterm window title from stack. supported + * Ps >= 24 not implemented + */ + public windowOptions(params: IParams): boolean { + if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) { + return true; + } + const second = (params.length > 1) ? params.params[1] : 0; + switch (params.params[0]) { + case 14: // GetWinSizePixels, returns CSI 4 ; height ; width t + if (second !== 2) { + this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_WIN_SIZE_PIXELS); + } + break; + case 16: // GetCellSizePixels, returns CSI 6 ; height ; width t + this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_CELL_SIZE_PIXELS); + break; + case 18: // GetWinSizeChars, returns CSI 8 ; height ; width t + if (this._bufferService) { + this._coreService.triggerDataEvent(`${C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`); + } + break; + case 22: // PushTitle + if (second === 0 || second === 2) { + this._windowTitleStack.push(this._windowTitle); + if (this._windowTitleStack.length > STACK_LIMIT) { + this._windowTitleStack.shift(); + } + } + if (second === 0 || second === 1) { + this._iconNameStack.push(this._iconName); + if (this._iconNameStack.length > STACK_LIMIT) { + this._iconNameStack.shift(); + } + } + break; + case 23: // PopTitle + if (second === 0 || second === 2) { + if (this._windowTitleStack.length) { + this.setTitle(this._windowTitleStack.pop()!); + } + } + if (second === 0 || second === 1) { + if (this._iconNameStack.length) { + this.setIconName(this._iconNameStack.pop()!); + } + } + break; + } + return true; + } + + + /** + * CSI s + * ESC 7 + * Save cursor (ANSI.SYS). + * + * @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): boolean { + this._activeBuffer.savedX = this._activeBuffer.x; + this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y; + this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg; + this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg; + this._activeBuffer.savedCharset = this._charsetService.charset; + return true; + } + + + /** + * CSI u + * ESC 8 + * Restore cursor (ANSI.SYS). + * + * @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): boolean { + this._activeBuffer.x = this._activeBuffer.savedX || 0; + this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0); + this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg; + this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg; + this._charsetService.charset = (this as any)._savedCharset; + if (this._activeBuffer.savedCharset) { + this._charsetService.charset = this._activeBuffer.savedCharset; + } + this._restrictCursor(); + return true; + } + + + /** + * OSC 2; <data> ST (set window title) + * Proxy to set window title. + * + * @vt: #P[Icon name is not exposed.] OSC 0 "Set Windows Title and Icon Name" "OSC 0 ; Pt BEL" "Set window title and icon name." + * Icon name is not supported. For Window Title see below. + * + * @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): boolean { + this._windowTitle = data; + this._onTitleChange.fire(data); + return true; + } + + /** + * OSC 1; <data> ST + * Note: Icon name is not exposed. + */ + public setIconName(data: string): boolean { + this._iconName = data; + return true; + } + + /** + * OSC 4; <num> ; <text> ST (set ANSI color <num> to <text>) + * + * @vt: #Y OSC 4 "Set ANSI color" "OSC 4 ; c ; spec BEL" "Change color number `c` to the color specified by `spec`." + * `c` is the color index between 0 and 255. The color format of `spec` is derived from `XParseColor` (see OSC 10 for supported formats). + * There may be multipe `c ; spec` pairs present in the same instruction. + * If `spec` contains `?` the terminal returns a sequence with the currently set color. + */ + public setOrReportIndexedColor(data: string): boolean { + const event: IColorEvent = []; + const slots = data.split(';'); + while (slots.length > 1) { + const idx = slots.shift() as string; + const spec = slots.shift() as string; + if (/^\d+$/.exec(idx)) { + const index = parseInt(idx); + if (0 <= index && index < 256) { + if (spec === '?') { + event.push({ type: ColorRequestType.REPORT, index }); + } else { + const color = parseColor(spec); + if (color) { + event.push({ type: ColorRequestType.SET, index, color }); + } + } + } + } + } + if (event.length) { + this._onColor.fire(event); + } + return true; + } + + // special colors - OSC 10 | 11 | 12 + private _specialColors = [ColorIndex.FOREGROUND, ColorIndex.BACKGROUND, ColorIndex.CURSOR]; + + /** + * Apply colors requests for special colors in OSC 10 | 11 | 12. + * Since these commands are stacking from multiple parameters, + * we handle them in a loop with an entry offset to `_specialColors`. + */ + private _setOrReportSpecialColor(data: string, offset: number): boolean { + const slots = data.split(';'); + for (let i = 0; i < slots.length; ++i, ++offset) { + if (offset >= this._specialColors.length) break; + if (slots[i] === '?') { + this._onColor.fire([{ type: ColorRequestType.REPORT, index: this._specialColors[offset] }]); + } else { + const color = parseColor(slots[i]); + if (color) { + this._onColor.fire([{ type: ColorRequestType.SET, index: this._specialColors[offset], color }]); + } + } + } + return true; + } + + /** + * OSC 10 ; <xcolor name>|<?> ST - set or query default foreground color + * + * @vt: #Y OSC 10 "Set or query default foreground color" "OSC 10 ; Pt BEL" "Set or query default foreground color." + * To set the color, the following color specification formats are supported: + * - `rgb:<red>/<green>/<blue>` for `<red>, <green>, <blue>` in `h | hh | hhh | hhhh`, where + * `h` is a single hexadecimal digit (case insignificant). The different widths scale + * from 4 bit (`h`) to 16 bit (`hhhh`) and get converted to 8 bit (`hh`). + * - `#RGB` - 4 bits per channel, expanded to `#R0G0B0` + * - `#RRGGBB` - 8 bits per channel + * - `#RRRGGGBBB` - 12 bits per channel, truncated to `#RRGGBB` + * - `#RRRRGGGGBBBB` - 16 bits per channel, truncated to `#RRGGBB` + * + * **Note:** X11 named colors are currently unsupported. + * + * If `Pt` contains `?` instead of a color specification, the terminal + * returns a sequence with the current default foreground color + * (use that sequence to restore the color after changes). + * + * **Note:** Other than xterm, xterm.js does not support OSC 12 - 19. + * Therefore stacking multiple `Pt` separated by `;` only works for the first two entries. + */ + public setOrReportFgColor(data: string): boolean { + return this._setOrReportSpecialColor(data, 0); + } + + /** + * OSC 11 ; <xcolor name>|<?> ST - set or query default background color + * + * @vt: #Y OSC 11 "Set or query default background color" "OSC 11 ; Pt BEL" "Same as OSC 10, but for default background." + */ + public setOrReportBgColor(data: string): boolean { + return this._setOrReportSpecialColor(data, 1); + } + + /** + * OSC 12 ; <xcolor name>|<?> ST - set or query default cursor color + * + * @vt: #Y OSC 12 "Set or query default cursor color" "OSC 12 ; Pt BEL" "Same as OSC 10, but for default cursor color." + */ + public setOrReportCursorColor(data: string): boolean { + return this._setOrReportSpecialColor(data, 2); + } + + /** + * OSC 104 ; <num> ST - restore ANSI color <num> + * + * @vt: #Y OSC 104 "Reset ANSI color" "OSC 104 ; c BEL" "Reset color number `c` to themed color." + * `c` is the color index between 0 and 255. This function restores the default color for `c` as + * specified by the loaded theme. Any number of `c` parameters may be given. + * If no parameters are given, the entire indexed color table will be reset. + */ + public restoreIndexedColor(data: string): boolean { + if (!data) { + this._onColor.fire([{ type: ColorRequestType.RESTORE }]); + return true; + } + const event: IColorEvent = []; + const slots = data.split(';'); + for (let i = 0; i < slots.length; ++i) { + if (/^\d+$/.exec(slots[i])) { + const index = parseInt(slots[i]); + if (0 <= index && index < 256) { + event.push({ type: ColorRequestType.RESTORE, index }); + } + } + } + if (event.length) { + this._onColor.fire(event); + } + return true; + } + + /** + * OSC 110 ST - restore default foreground color + * + * @vt: #Y OSC 110 "Restore default foreground color" "OSC 110 BEL" "Restore default foreground to themed color." + */ + public restoreFgColor(data: string): boolean { + this._onColor.fire([{ type: ColorRequestType.RESTORE, index: ColorIndex.FOREGROUND }]); + return true; + } + + /** + * OSC 111 ST - restore default background color + * + * @vt: #Y OSC 111 "Restore default background color" "OSC 111 BEL" "Restore default background to themed color." + */ + public restoreBgColor(data: string): boolean { + this._onColor.fire([{ type: ColorRequestType.RESTORE, index: ColorIndex.BACKGROUND }]); + return true; + } + + /** + * OSC 112 ST - restore default cursor color + * + * @vt: #Y OSC 112 "Restore default cursor color" "OSC 112 BEL" "Restore default cursor to themed color." + */ + public restoreCursorColor(data: string): boolean { + this._onColor.fire([{ type: ColorRequestType.RESTORE, index: ColorIndex.CURSOR }]); + return true; + } + + /** + * ESC E + * C1.NEL + * DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL) + * Moves cursor to first position on next line. + * + * @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(): boolean { + this._activeBuffer.x = 0; + this.index(); + return true; + } + + /** + * ESC = + * DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html) + * Enables the numeric keypad to send application sequences to the host. + */ + public keypadApplicationMode(): boolean { + this._logService.debug('Serial port requested application keypad.'); + this._coreService.decPrivateModes.applicationKeypad = true; + this._onRequestSyncScrollBar.fire(); + return true; + } + + /** + * ESC > + * DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html) + * Enables the keypad to send numeric characters to the host. + */ + public keypadNumericMode(): boolean { + this._logService.debug('Switching back to normal keypad.'); + this._coreService.decPrivateModes.applicationKeypad = false; + this._onRequestSyncScrollBar.fire(); + return true; + } + + /** + * ESC % @ + * ESC % G + * Select default character set. UTF-8 is not supported (string are unicode anyways) + * therefore ESC % G does the same. + */ + public selectDefaultCharset(): boolean { + this._charsetService.setgLevel(0); + this._charsetService.setgCharset(0, DEFAULT_CHARSET); // US (default) + return true; + } + + /** + * ESC ( C + * Designate G0 Character Set, VT100, ISO 2022. + * ESC ) C + * Designate G1 Character Set (ISO 2022, VT100). + * ESC * C + * Designate G2 Character Set (ISO 2022, VT220). + * ESC + C + * Designate G3 Character Set (ISO 2022, VT220). + * ESC - C + * Designate G1 Character Set (VT300). + * ESC . C + * Designate G2 Character Set (VT300). + * ESC / C + * Designate G3 Character Set (VT300). C = A -> ISO Latin-1 Supplemental. - Supported? + */ + public selectCharset(collectAndFlag: string): boolean { + if (collectAndFlag.length !== 2) { + this.selectDefaultCharset(); + return true; + } + if (collectAndFlag[0] === '/') { + return true; // TODO: Is this supported? + } + this._charsetService.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET); + return true; + } + + /** + * ESC D + * C1.IND + * DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html) + * Moves the cursor down one line in the same column. + * + * @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(): boolean { + this._restrictCursor(); + this._activeBuffer.y++; + if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) { + this._activeBuffer.y--; + this._bufferService.scroll(this._eraseAttrData()); + } else if (this._activeBuffer.y >= this._bufferService.rows) { + this._activeBuffer.y = this._bufferService.rows - 1; + } + this._restrictCursor(); + return true; + } + + /** + * ESC H + * C1.HTS + * DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html) + * Sets a horizontal tab stop at the column position indicated by + * the value of the active column when the terminal receives an HTS. + * + * @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(): boolean { + this._activeBuffer.tabs[this._activeBuffer.x] = true; + return true; + } + + /** + * ESC M + * C1.RI + * DEC mnemonic: HTS + * Moves the cursor up one line in the same column. If the cursor is at the top margin, + * the page scrolls down. + * + * @vt: #Y ESC IR "Reverse Index" "ESC M" "Move the cursor one line up scrolling if needed." + */ + public reverseIndex(): boolean { + this._restrictCursor(); + if (this._activeBuffer.y === this._activeBuffer.scrollTop) { + // possibly move the code below to term.reverseScroll(); + // test: echo -ne '\e[1;1H\e[44m\eM\e[0m' + // blankLine(true) is xterm/linux behavior + const scrollRegionHeight = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop; + this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, scrollRegionHeight, 1); + this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData())); + this._dirtyRowService.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); + } else { + this._activeBuffer.y--; + this._restrictCursor(); // quickfix to not run out of bounds + } + return true; + } + + /** + * ESC c + * DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html) + * Reset to initial state. + */ + public fullReset(): boolean { + this._parser.reset(); + this._onRequestReset.fire(); + return true; + } + + public reset(): void { + this._curAttrData = DEFAULT_ATTR_DATA.clone(); + this._eraseAttrDataInternal = DEFAULT_ATTR_DATA.clone(); + } + + /** + * back_color_erase feature for xterm. + */ + private _eraseAttrData(): IAttributeData { + this._eraseAttrDataInternal.bg &= ~(Attributes.CM_MASK | 0xFFFFFF); + this._eraseAttrDataInternal.bg |= this._curAttrData.bg & ~0xFC000000; + return this._eraseAttrDataInternal; + } + + /** + * ESC n + * ESC o + * ESC | + * ESC } + * ESC ~ + * DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html) + * When you use a locking shift, the character set remains in GL or GR until + * you use another locking shift. (partly supported) + */ + public setgLevel(level: number): boolean { + this._charsetService.setgLevel(level); + return true; + } + + /** + * ESC # 8 + * DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html) + * This control function fills the complete screen area with + * a test pattern (E) used for adjusting screen alignment. + * + * @vt: #Y ESC DECALN "Screen Alignment Pattern" "ESC # 8" "Fill viewport with a test pattern (E)." + */ + public screenAlignmentPattern(): boolean { + // prepare cell data + const cell = new CellData(); + cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0); + cell.fg = this._curAttrData.fg; + cell.bg = this._curAttrData.bg; + + + this._setCursor(0, 0); + for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) { + const row = this._activeBuffer.ybase + this._activeBuffer.y + yOffset; + const line = this._activeBuffer.lines.get(row); + if (line) { + line.fill(cell); + line.isWrapped = false; + } + } + this._dirtyRowService.markAllDirty(); + this._setCursor(0, 0); + return true; + } +} diff --git a/node_modules/xterm/src/common/Lifecycle.ts b/node_modules/xterm/src/common/Lifecycle.ts new file mode 100644 index 0000000..56bcfdc --- /dev/null +++ b/node_modules/xterm/src/common/Lifecycle.ts @@ -0,0 +1,68 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/Types'; + +/** + * A base class that can be extended to provide convenience methods for managing the lifecycle of an + * object and its components. + */ +export abstract class Disposable implements IDisposable { + protected _disposables: IDisposable[] = []; + protected _isDisposed: boolean = false; + + constructor() { + } + + /** + * Disposes the object, triggering the `dispose` method on all registered IDisposables. + */ + public dispose(): void { + this._isDisposed = true; + for (const d of this._disposables) { + d.dispose(); + } + this._disposables.length = 0; + } + + /** + * Registers a disposable object. + * @param d The disposable to register. + * @returns The disposable. + */ + public register<T extends IDisposable>(d: T): T { + this._disposables.push(d); + return d; + } + + /** + * Unregisters a disposable object if it has been registered, if not do + * nothing. + * @param d The disposable to unregister. + */ + public unregister<T extends IDisposable>(d: T): void { + const index = this._disposables.indexOf(d); + if (index !== -1) { + this._disposables.splice(index, 1); + } + } +} + +/** + * Dispose of all disposables in an array and set its length to 0. + */ +export function disposeArray(disposables: IDisposable[]): void { + for (const d of disposables) { + d.dispose(); + } + disposables.length = 0; +} + +/** + * Creates a disposable that will dispose of an array of disposables when disposed. + */ +export function getDisposeArrayDisposable(array: IDisposable[]): IDisposable { + return { dispose: () => disposeArray(array) }; +} diff --git a/node_modules/xterm/src/common/Platform.ts b/node_modules/xterm/src/common/Platform.ts new file mode 100644 index 0000000..7b823b1 --- /dev/null +++ b/node_modules/xterm/src/common/Platform.ts @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +interface INavigator { + userAgent: string; + language: string; + platform: string; +} + +// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but +// we want this module to live in common. +declare const navigator: INavigator; + +const isNode = (typeof navigator === 'undefined') ? true : false; +const userAgent = (isNode) ? 'node' : navigator.userAgent; +const platform = (isNode) ? 'node' : navigator.platform; + +export const isFirefox = userAgent.includes('Firefox'); +export const isLegacyEdge = userAgent.includes('Edge'); +export const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent); + +// Find the users platform. We use this to interpret the meta key +// and ISO third level shifts. +// http://stackoverflow.com/q/19877924/577598 +export const isMac = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'].includes(platform); +export const isIpad = platform === 'iPad'; +export const isIphone = platform === 'iPhone'; +export const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].includes(platform); +export const isLinux = platform.indexOf('Linux') >= 0; diff --git a/node_modules/xterm/src/common/TypedArrayUtils.ts b/node_modules/xterm/src/common/TypedArrayUtils.ts new file mode 100644 index 0000000..158c717 --- /dev/null +++ b/node_modules/xterm/src/common/TypedArrayUtils.ts @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export type TypedArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; + + +/** + * polyfill for TypedArray.fill + * This is needed to support .fill in all safari versions and IE 11. + */ +export function fill<T extends TypedArray>(array: T, value: number, start?: number, end?: number): T { + // all modern engines that support .fill + if (array.fill) { + return array.fill(value, start, end) as T; + } + return fillFallback(array, value, start, end); +} + +export function fillFallback<T extends TypedArray>(array: T, value: number, start: number = 0, end: number = array.length): T { + // safari and IE 11 + // since IE 11 does not support Array.prototype.fill either + // we cannot use the suggested polyfill from MDN + // instead we simply fall back to looping + if (start >= array.length) { + return array; + } + start = (array.length + start) % array.length; + if (end >= array.length) { + end = array.length; + } else { + end = (array.length + end) % array.length; + } + for (let i = start; i < end; ++i) { + array[i] = value; + } + return array; +} + +/** + * Concat two typed arrays `a` and `b`. + * Returns a new typed array. + */ +export function concat<T extends TypedArray>(a: T, b: T): T { + const result = new (a.constructor as any)(a.length + b.length); + result.set(a); + result.set(b, a.length); + return result; +} diff --git a/node_modules/xterm/src/common/Types.d.ts b/node_modules/xterm/src/common/Types.d.ts new file mode 100644 index 0000000..fee426e --- /dev/null +++ b/node_modules/xterm/src/common/Types.d.ts @@ -0,0 +1,483 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +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'; +import { ICoreMouseService, ICoreService, IOptionsService, IUnicodeService } from 'common/services/Services'; +import { IBufferSet } from 'common/buffer/Types'; + +export interface ICoreTerminal { + coreMouseService: ICoreMouseService; + coreService: ICoreService; + optionsService: IOptionsService; + unicodeService: IUnicodeService; + buffers: IBufferSet; + options: ITerminalOptions; + registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable; + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable; + registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable; + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable; +} + +export interface IDisposable { + dispose(): void; +} + +// TODO: The options that are not in the public API should be reviewed +export interface ITerminalOptions extends IPublicTerminalOptions { + [key: string]: any; + cancelEvents?: boolean; + convertEol?: boolean; + termName?: string; +} + +export type XtermListener = (...args: any[]) => void; + +/** + * A keyboard event interface which does not depend on the DOM, KeyboardEvent implicitly extends + * this event. + */ +export interface IKeyboardEvent { + altKey: boolean; + ctrlKey: boolean; + shiftKey: boolean; + metaKey: boolean; + /** @deprecated See KeyboardEvent.keyCode */ + keyCode: number; + key: string; + type: string; +} + +export interface IScrollEvent { + position: number; + source: ScrollSource; +} + +export const enum ScrollSource { + TERMINAL, + VIEWPORT, +} + +export interface ICircularList<T> { + length: number; + maxLength: number; + isFull: boolean; + + onDeleteEmitter: IEventEmitter<IDeleteEvent>; + onDelete: IEvent<IDeleteEvent>; + onInsertEmitter: IEventEmitter<IInsertEvent>; + onInsert: IEvent<IInsertEvent>; + onTrimEmitter: IEventEmitter<number>; + onTrim: IEvent<number>; + + get(index: number): T | undefined; + set(index: number, value: T): void; + push(value: T): void; + recycle(): T; + pop(): T | undefined; + splice(start: number, deleteCount: number, ...items: T[]): void; + trimStart(count: number): void; + shiftElements(start: number, count: number, offset: number): void; +} + +export const enum KeyboardResultType { + SEND_KEY, + SELECT_ALL, + PAGE_UP, + PAGE_DOWN +} + +export interface IKeyboardResult { + type: KeyboardResultType; + cancel: boolean; + key: string | undefined; +} + +export interface ICharset { + [key: string]: string | undefined; +} + +export type CharData = [number, string, number, number]; +export type IColorRGB = [number, number, number]; + +export interface IExtendedAttrs { + underlineStyle: number; + underlineColor: number; + clone(): IExtendedAttrs; + isEmpty(): boolean; +} + +/** Attribute data */ +export interface IAttributeData { + fg: number; + bg: number; + extended: IExtendedAttrs; + + clone(): IAttributeData; + + // flags + isInverse(): number; + isBold(): number; + isUnderline(): number; + isBlink(): number; + isInvisible(): number; + isItalic(): number; + isDim(): number; + isStrikethrough(): number; + + // color modes + getFgColorMode(): number; + getBgColorMode(): number; + isFgRGB(): boolean; + isBgRGB(): boolean; + isFgPalette(): boolean; + isBgPalette(): boolean; + isFgDefault(): boolean; + isBgDefault(): boolean; + isAttributeDefault(): boolean; + + // colors + getFgColor(): number; + getBgColor(): number; + + // extended attrs + hasExtendedAttrs(): number; + updateExtended(): void; + getUnderlineColor(): number; + getUnderlineColorMode(): number; + isUnderlineColorRGB(): boolean; + isUnderlineColorPalette(): boolean; + isUnderlineColorDefault(): boolean; + getUnderlineStyle(): number; +} + +/** Cell data */ +export interface ICellData extends IAttributeData { + content: number; + combinedData: string; + isCombined(): number; + getWidth(): number; + getChars(): string; + getCode(): number; + setFromCharData(value: CharData): void; + getAsCharData(): CharData; +} + +/** + * Interface for a line in the terminal buffer. + */ +export interface IBufferLine { + length: number; + isWrapped: boolean; + get(index: number): CharData; + set(index: number, value: CharData): void; + loadCell(index: number, cell: ICellData): ICellData; + setCell(index: number, cell: ICellData): void; + setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number, eAttrs: IExtendedAttrs): void; + addCodepointToCell(index: number, codePoint: number): void; + insertCells(pos: number, n: number, ch: ICellData, eraseAttr?: IAttributeData): void; + deleteCells(pos: number, n: number, fill: ICellData, eraseAttr?: IAttributeData): void; + replaceCells(start: number, end: number, fill: ICellData, eraseAttr?: IAttributeData): void; + resize(cols: number, fill: ICellData): void; + fill(fillCellData: ICellData): void; + copyFrom(line: IBufferLine): void; + clone(): IBufferLine; + getTrimmedLength(): number; + translateToString(trimRight?: boolean, startCol?: number, endCol?: number): string; + + /* direct access to cell attrs */ + getWidth(index: number): number; + hasWidth(index: number): number; + getFg(index: number): number; + getBg(index: number): number; + hasContent(index: number): number; + getCodePoint(index: number): number; + isCombined(index: number): number; + getString(index: number): string; +} + +export interface IMarker extends IDisposable { + readonly id: number; + readonly isDisposed: boolean; + readonly line: number; + onDispose: IEvent<void>; +} +export interface IModes { + insertMode: boolean; +} + +export interface IDecPrivateModes { + applicationCursorKeys: boolean; + applicationKeypad: boolean; + bracketedPasteMode: boolean; + origin: boolean; + reverseWraparound: boolean; + sendFocus: boolean; + wraparound: boolean; // defaults: xterm - true, vt100 - false +} + +export interface IRowRange { + start: number; + end: number; +} + +/** + * Interface for mouse events in the core. + */ +export const enum CoreMouseButton { + LEFT = 0, + MIDDLE = 1, + RIGHT = 2, + NONE = 3, + WHEEL = 4, + // additional buttons 1..8 + // untested! + AUX1 = 8, + AUX2 = 9, + AUX3 = 10, + AUX4 = 11, + AUX5 = 12, + AUX6 = 13, + AUX7 = 14, + AUX8 = 15 +} + +export const enum CoreMouseAction { + UP = 0, // buttons, wheel + DOWN = 1, // buttons, wheel + LEFT = 2, // wheel only + RIGHT = 3, // wheel only + MOVE = 32 // buttons only +} + +export interface ICoreMouseEvent { + /** column (zero based). */ + col: number; + /** row (zero based). */ + row: number; + /** + * Button the action occured. Due to restrictions of the tracking protocols + * it is not possible to report multiple buttons at once. + * Wheel is treated as a button. + * There are invalid combinations of buttons and actions possible + * (like move + wheel), those are silently ignored by the CoreMouseService. + */ + button: CoreMouseButton; + action: CoreMouseAction; + /** + * Modifier states. + * Protocols will add/ignore those based on specific restrictions. + */ + ctrl?: boolean; + alt?: boolean; + shift?: boolean; +} + +/** + * CoreMouseEventType + * To be reported to the browser component which events a mouse + * protocol wants to be catched and forwarded as an ICoreMouseEvent + * to CoreMouseService. + */ +export const enum CoreMouseEventType { + NONE = 0, + /** any mousedown event */ + DOWN = 1, + /** any mouseup event */ + UP = 2, + /** any mousemove event while a button is held */ + DRAG = 4, + /** any mousemove event without a button */ + MOVE = 8, + /** any wheel event */ + WHEEL = 16 +} + +/** + * Mouse protocol interface. + * A mouse protocol can be registered and activated at the CoreMouseService. + * `events` should contain a list of needed events as a hint for the browser component + * to install/remove the appropriate event handlers. + * `restrict` applies further protocol specific restrictions like not allowed + * modifiers or filtering invalid event types. + */ +export interface ICoreMouseProtocol { + events: CoreMouseEventType; + restrict: (e: ICoreMouseEvent) => boolean; +} + +/** + * CoreMouseEncoding + * The tracking encoding can be registered and activated at the CoreMouseService. + * If a ICoreMouseEvent passes all procotol restrictions it will be encoded + * with the active encoding and sent out. + * Note: Returning an empty string will supress sending a mouse report, + * which can be used to skip creating falsey reports in limited encodings + * (DEFAULT only supports up to 223 1-based as coord value). + */ +export type CoreMouseEncoding = (event: ICoreMouseEvent) => string; + +/** + * windowOptions + */ +export interface IWindowOptions { + restoreWin?: boolean; + minimizeWin?: boolean; + setWinPosition?: boolean; + setWinSizePixels?: boolean; + raiseWin?: boolean; + lowerWin?: boolean; + refreshWin?: boolean; + setWinSizeChars?: boolean; + maximizeWin?: boolean; + fullscreenWin?: boolean; + getWinState?: boolean; + getWinPosition?: boolean; + getWinSizePixels?: boolean; + getScreenSizePixels?: boolean; + getCellSizePixels?: boolean; + getWinSizeChars?: boolean; + getScreenSizeChars?: boolean; + getIconTitle?: boolean; + getWinTitle?: boolean; + pushTitle?: boolean; + popTitle?: boolean; + setWinLines?: boolean; +} + +// color events from common, used for OSC 4/10/11/12 and 104/110/111/112 +export const enum ColorRequestType { + REPORT = 0, + SET = 1, + RESTORE = 2 +} +export const enum ColorIndex { + FOREGROUND = 256, + BACKGROUND = 257, + CURSOR = 258 +} +export interface IColorReportRequest { + type: ColorRequestType.REPORT; + index: ColorIndex; +} +export interface IColorSetRequest { + type: ColorRequestType.SET; + index: ColorIndex; + color: IColorRGB; +} +export interface IColorRestoreRequest { + type: ColorRequestType.RESTORE; + index?: ColorIndex; +} +export type IColorEvent = (IColorReportRequest | IColorSetRequest | IColorRestoreRequest)[]; + + +/** + * Calls the parser and handles actions generated by the parser. + */ +export interface IInputHandler { + onTitleChange: IEvent<string>; + + parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise<boolean>; + print(data: Uint32Array, start: number, end: number): void; + registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable; + registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable; + registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable; + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable; + + /** C0 BEL */ bell(): boolean; + /** C0 LF */ lineFeed(): boolean; + /** C0 CR */ carriageReturn(): boolean; + /** C0 BS */ backspace(): boolean; + /** C0 HT */ tab(): boolean; + /** C0 SO */ shiftOut(): boolean; + /** C0 SI */ shiftIn(): boolean; + + /** CSI @ */ insertChars(params: IParams): boolean; + /** CSI SP @ */ scrollLeft(params: IParams): boolean; + /** CSI A */ cursorUp(params: IParams): boolean; + /** CSI SP A */ scrollRight(params: IParams): boolean; + /** CSI B */ cursorDown(params: IParams): boolean; + /** CSI C */ cursorForward(params: IParams): boolean; + /** CSI D */ cursorBackward(params: IParams): boolean; + /** CSI E */ cursorNextLine(params: IParams): boolean; + /** CSI F */ cursorPrecedingLine(params: IParams): boolean; + /** CSI G */ cursorCharAbsolute(params: IParams): boolean; + /** CSI H */ cursorPosition(params: IParams): boolean; + /** CSI I */ cursorForwardTab(params: IParams): boolean; + /** CSI J */ eraseInDisplay(params: IParams): boolean; + /** CSI K */ eraseInLine(params: IParams): boolean; + /** CSI L */ insertLines(params: IParams): boolean; + /** CSI M */ deleteLines(params: IParams): boolean; + /** CSI P */ deleteChars(params: IParams): boolean; + /** CSI S */ scrollUp(params: IParams): boolean; + /** CSI T */ scrollDown(params: IParams, collect?: string): boolean; + /** CSI X */ eraseChars(params: IParams): boolean; + /** CSI Z */ cursorBackwardTab(params: IParams): boolean; + /** CSI ` */ charPosAbsolute(params: IParams): boolean; + /** CSI a */ hPositionRelative(params: IParams): boolean; + /** CSI b */ repeatPrecedingCharacter(params: IParams): boolean; + /** CSI c */ sendDeviceAttributesPrimary(params: IParams): boolean; + /** CSI > c */ sendDeviceAttributesSecondary(params: IParams): boolean; + /** CSI d */ linePosAbsolute(params: IParams): boolean; + /** CSI e */ vPositionRelative(params: IParams): boolean; + /** CSI f */ hVPosition(params: IParams): boolean; + /** CSI g */ tabClear(params: IParams): boolean; + /** CSI h */ setMode(params: IParams, collect?: string): boolean; + /** CSI l */ resetMode(params: IParams, collect?: string): boolean; + /** CSI m */ charAttributes(params: IParams): boolean; + /** CSI n */ deviceStatus(params: IParams, collect?: string): boolean; + /** CSI p */ softReset(params: IParams, collect?: string): boolean; + /** CSI q */ setCursorStyle(params: IParams, collect?: string): boolean; + /** CSI r */ setScrollRegion(params: IParams, collect?: string): boolean; + /** CSI s */ saveCursor(params: IParams): boolean; + /** CSI u */ restoreCursor(params: IParams): boolean; + /** CSI ' } */ insertColumns(params: IParams): boolean; + /** CSI ' ~ */ deleteColumns(params: IParams): boolean; + + /** OSC 0 + OSC 2 */ setTitle(data: string): boolean; + /** OSC 4 */ setOrReportIndexedColor(data: string): boolean; + /** OSC 10 */ setOrReportFgColor(data: string): boolean; + /** OSC 11 */ setOrReportBgColor(data: string): boolean; + /** OSC 12 */ setOrReportCursorColor(data: string): boolean; + /** OSC 104 */ restoreIndexedColor(data: string): boolean; + /** OSC 110 */ restoreFgColor(data: string): boolean; + /** OSC 111 */ restoreBgColor(data: string): boolean; + /** OSC 112 */ restoreCursorColor(data: string): boolean; + + /** ESC E */ nextLine(): boolean; + /** ESC = */ keypadApplicationMode(): boolean; + /** ESC > */ keypadNumericMode(): boolean; + /** ESC % G + ESC % @ */ selectDefaultCharset(): boolean; + /** ESC ( C + ESC ) C + ESC * C + ESC + C + ESC - C + ESC . C + ESC / C */ selectCharset(collectAndFlag: string): boolean; + /** ESC D */ index(): boolean; + /** ESC H */ tabSet(): boolean; + /** ESC M */ reverseIndex(): boolean; + /** ESC c */ fullReset(): boolean; + /** ESC n + ESC o + ESC | + ESC } + ESC ~ */ setgLevel(level: number): boolean; + /** ESC # 8 */ screenAlignmentPattern(): boolean; +} + +interface IParseStack { + paused: boolean; + cursorStartX: number; + cursorStartY: number; + decodedLength: number; + position: number; +} diff --git a/node_modules/xterm/src/common/WindowsMode.ts b/node_modules/xterm/src/common/WindowsMode.ts new file mode 100644 index 0000000..7cff094 --- /dev/null +++ b/node_modules/xterm/src/common/WindowsMode.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants'; +import { IBufferService } from 'common/services/Services'; + +export function updateWindowsModeWrappedState(bufferService: IBufferService): void { + // Winpty does not support wraparound mode which means that lines will never + // be marked as wrapped. This causes issues for things like copying a line + // retaining the wrapped new line characters or if consumers are listening + // in on the data stream. + // + // The workaround for this is to listen to every incoming line feed and mark + // the line as wrapped if the last character in the previous line is not a + // space. This is certainly not without its problems, but generally on + // Windows when text reaches the end of the terminal it's likely going to be + // wrapped. + const line = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y - 1); + const lastChar = line?.get(bufferService.cols - 1); + + const nextLine = bufferService.buffer.lines.get(bufferService.buffer.ybase + bufferService.buffer.y); + if (nextLine && lastChar) { + nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE); + } +} diff --git a/node_modules/xterm/src/common/buffer/AttributeData.ts b/node_modules/xterm/src/common/buffer/AttributeData.ts new file mode 100644 index 0000000..43d378e --- /dev/null +++ b/node_modules/xterm/src/common/buffer/AttributeData.ts @@ -0,0 +1,148 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IAttributeData, IColorRGB, IExtendedAttrs } from 'common/Types'; +import { Attributes, FgFlags, BgFlags, UnderlineStyle } from 'common/buffer/Constants'; + +export class AttributeData implements IAttributeData { + public static toColorRGB(value: number): IColorRGB { + return [ + value >>> Attributes.RED_SHIFT & 255, + value >>> Attributes.GREEN_SHIFT & 255, + value & 255 + ]; + } + + public static fromColorRGB(value: IColorRGB): number { + return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255; + } + + public clone(): IAttributeData { + const newObj = new AttributeData(); + newObj.fg = this.fg; + newObj.bg = this.bg; + newObj.extended = this.extended.clone(); + return newObj; + } + + // data + public fg = 0; + public bg = 0; + public extended = new ExtendedAttrs(); + + // flags + public isInverse(): number { return this.fg & FgFlags.INVERSE; } + public isBold(): number { return this.fg & FgFlags.BOLD; } + public isUnderline(): number { return this.fg & FgFlags.UNDERLINE; } + public isBlink(): number { return this.fg & FgFlags.BLINK; } + public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; } + public isItalic(): number { return this.bg & BgFlags.ITALIC; } + public isDim(): number { return this.bg & BgFlags.DIM; } + public isStrikethrough(): number { return this.fg & FgFlags.STRIKETHROUGH; } + + // color modes + public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; } + public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; } + public isFgRGB(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; } + public isBgRGB(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; } + public isFgPalette(): boolean { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; } + public isBgPalette(): boolean { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; } + public isFgDefault(): boolean { return (this.fg & Attributes.CM_MASK) === 0; } + public isBgDefault(): boolean { return (this.bg & Attributes.CM_MASK) === 0; } + public isAttributeDefault(): boolean { return this.fg === 0 && this.bg === 0; } + + // colors + public getFgColor(): number { + switch (this.fg & Attributes.CM_MASK) { + case Attributes.CM_P16: + case Attributes.CM_P256: return this.fg & Attributes.PCOLOR_MASK; + case Attributes.CM_RGB: return this.fg & Attributes.RGB_MASK; + default: return -1; // CM_DEFAULT defaults to -1 + } + } + public getBgColor(): number { + switch (this.bg & Attributes.CM_MASK) { + case Attributes.CM_P16: + case Attributes.CM_P256: return this.bg & Attributes.PCOLOR_MASK; + case Attributes.CM_RGB: return this.bg & Attributes.RGB_MASK; + default: return -1; // CM_DEFAULT defaults to -1 + } + } + + // extended attrs + public hasExtendedAttrs(): number { + return this.bg & BgFlags.HAS_EXTENDED; + } + public updateExtended(): void { + if (this.extended.isEmpty()) { + this.bg &= ~BgFlags.HAS_EXTENDED; + } else { + this.bg |= BgFlags.HAS_EXTENDED; + } + } + public getUnderlineColor(): number { + if ((this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor) { + switch (this.extended.underlineColor & Attributes.CM_MASK) { + case Attributes.CM_P16: + case Attributes.CM_P256: return this.extended.underlineColor & Attributes.PCOLOR_MASK; + case Attributes.CM_RGB: return this.extended.underlineColor & Attributes.RGB_MASK; + default: return this.getFgColor(); + } + } + return this.getFgColor(); + } + public getUnderlineColorMode(): number { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? this.extended.underlineColor & Attributes.CM_MASK + : this.getFgColorMode(); + } + public isUnderlineColorRGB(): boolean { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_RGB + : this.isFgRGB(); + } + public isUnderlineColorPalette(): boolean { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P16 + || (this.extended.underlineColor & Attributes.CM_MASK) === Attributes.CM_P256 + : this.isFgPalette(); + } + public isUnderlineColorDefault(): boolean { + return (this.bg & BgFlags.HAS_EXTENDED) && ~this.extended.underlineColor + ? (this.extended.underlineColor & Attributes.CM_MASK) === 0 + : this.isFgDefault(); + } + public getUnderlineStyle(): UnderlineStyle { + return this.fg & FgFlags.UNDERLINE + ? (this.bg & BgFlags.HAS_EXTENDED ? this.extended.underlineStyle : UnderlineStyle.SINGLE) + : UnderlineStyle.NONE; + } +} + + +/** + * Extended attributes for a cell. + * Holds information about different underline styles and color. + */ +export class ExtendedAttrs implements IExtendedAttrs { + constructor( + // underline style, NONE is empty + public underlineStyle: UnderlineStyle = UnderlineStyle.NONE, + // underline color, -1 is empty (same as FG) + public underlineColor: number = -1 + ) {} + + public clone(): IExtendedAttrs { + return new ExtendedAttrs(this.underlineStyle, this.underlineColor); + } + + /** + * Convenient method to indicate whether the object holds no additional information, + * that needs to be persistant in the buffer. + */ + public isEmpty(): boolean { + return this.underlineStyle === UnderlineStyle.NONE; + } +} diff --git a/node_modules/xterm/src/common/buffer/Buffer.ts b/node_modules/xterm/src/common/buffer/Buffer.ts new file mode 100644 index 0000000..02ce7c8 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Buffer.ts @@ -0,0 +1,681 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CircularList, IInsertEvent } from 'common/CircularList'; +import { IBuffer, BufferIndex, IBufferStringIterator, IBufferStringIteratorResult } from 'common/buffer/Types'; +import { IBufferLine, ICellData, IAttributeData, ICharset } from 'common/Types'; +import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine'; +import { CellData } from 'common/buffer/CellData'; +import { NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_CHAR_INDEX } from 'common/buffer/Constants'; +import { reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths, getWrappedLineTrimmedLength } from 'common/buffer/BufferReflow'; +import { Marker } from 'common/buffer/Marker'; +import { IOptionsService, IBufferService } from 'common/services/Services'; +import { DEFAULT_CHARSET } from 'common/data/Charsets'; +import { ExtendedAttrs } from 'common/buffer/AttributeData'; + +export const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1 + +/** + * This class represents a terminal buffer (an internal state of the terminal), where the + * following information is stored (in high-level): + * - text content of this particular buffer + * - cursor position + * - scroll position + */ +export class Buffer implements IBuffer { + public lines: CircularList<IBufferLine>; + public ydisp: number = 0; + public ybase: number = 0; + public y: number = 0; + public x: number = 0; + public scrollBottom: number; + public scrollTop: number; + // TODO: Type me + public tabs: any; + public savedY: number = 0; + public savedX: number = 0; + public savedCurAttrData = DEFAULT_ATTR_DATA.clone(); + public savedCharset: ICharset | undefined = DEFAULT_CHARSET; + public markers: Marker[] = []; + private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); + private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]); + private _cols: number; + private _rows: number; + + constructor( + private _hasScrollback: boolean, + private _optionsService: IOptionsService, + private _bufferService: IBufferService + ) { + this._cols = this._bufferService.cols; + this._rows = this._bufferService.rows; + this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows)); + this.scrollTop = 0; + this.scrollBottom = this._rows - 1; + this.setupTabStops(); + } + + public getNullCell(attr?: IAttributeData): ICellData { + if (attr) { + this._nullCell.fg = attr.fg; + this._nullCell.bg = attr.bg; + this._nullCell.extended = attr.extended; + } else { + this._nullCell.fg = 0; + this._nullCell.bg = 0; + this._nullCell.extended = new ExtendedAttrs(); + } + return this._nullCell; + } + + public getWhitespaceCell(attr?: IAttributeData): ICellData { + if (attr) { + this._whitespaceCell.fg = attr.fg; + this._whitespaceCell.bg = attr.bg; + this._whitespaceCell.extended = attr.extended; + } else { + this._whitespaceCell.fg = 0; + this._whitespaceCell.bg = 0; + this._whitespaceCell.extended = new ExtendedAttrs(); + } + return this._whitespaceCell; + } + + public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine { + return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped); + } + + public get hasScrollback(): boolean { + return this._hasScrollback && this.lines.maxLength > this._rows; + } + + public get isCursorInViewport(): boolean { + const absoluteY = this.ybase + this.y; + const relativeY = absoluteY - this.ydisp; + return (relativeY >= 0 && relativeY < this._rows); + } + + /** + * Gets the correct buffer length based on the rows provided, the terminal's + * scrollback and whether this buffer is flagged to have scrollback or not. + * @param rows The terminal rows to use in the calculation. + */ + private _getCorrectBufferLength(rows: number): number { + if (!this._hasScrollback) { + return rows; + } + + const correctBufferLength = rows + this._optionsService.rawOptions.scrollback; + + return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength; + } + + /** + * Fills the buffer's viewport with blank lines. + */ + public fillViewportRows(fillAttr?: IAttributeData): void { + if (this.lines.length === 0) { + if (fillAttr === undefined) { + fillAttr = DEFAULT_ATTR_DATA; + } + let i = this._rows; + while (i--) { + this.lines.push(this.getBlankLine(fillAttr)); + } + } + } + + /** + * Clears the buffer to it's initial state, discarding all previous data. + */ + public clear(): void { + this.ydisp = 0; + this.ybase = 0; + this.y = 0; + this.x = 0; + this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows)); + this.scrollTop = 0; + this.scrollBottom = this._rows - 1; + this.setupTabStops(); + } + + /** + * Resizes the buffer, adjusting its data accordingly. + * @param newCols The new number of columns. + * @param newRows The new number of rows. + */ + public resize(newCols: number, newRows: number): void { + // store reference to null cell with default attrs + const nullCell = this.getNullCell(DEFAULT_ATTR_DATA); + + // Increase max length if needed before adjustments to allow space to fill + // as required. + const newMaxLength = this._getCorrectBufferLength(newRows); + if (newMaxLength > this.lines.maxLength) { + this.lines.maxLength = newMaxLength; + } + + // The following adjustments should only happen if the buffer has been + // initialized/filled. + if (this.lines.length > 0) { + // Deal with columns increasing (reducing needs to happen after reflow) + if (this._cols < newCols) { + for (let i = 0; i < this.lines.length; i++) { + this.lines.get(i)!.resize(newCols, nullCell); + } + } + + // Resize rows in both directions as needed + let addToY = 0; + if (this._rows < newRows) { + for (let y = this._rows; y < newRows; y++) { + if (this.lines.length < newRows + this.ybase) { + if (this._optionsService.rawOptions.windowsMode) { + // Just add the new missing rows on Windows as conpty reprints the screen with it's + // view of the world. Once a line enters scrollback for conpty it remains there + this.lines.push(new BufferLine(newCols, nullCell)); + } else { + if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) { + // There is room above the buffer and there are no empty elements below the line, + // scroll up + this.ybase--; + addToY++; + if (this.ydisp > 0) { + // Viewport is at the top of the buffer, must increase downwards + this.ydisp--; + } + } else { + // Add a blank line if there is no buffer left at the top to scroll to, or if there + // are blank lines after the cursor + this.lines.push(new BufferLine(newCols, nullCell)); + } + } + } + } + } else { // (this._rows >= newRows) + for (let y = this._rows; y > newRows; y--) { + if (this.lines.length > newRows + this.ybase) { + if (this.lines.length > this.ybase + this.y + 1) { + // The line is a blank line below the cursor, remove it + this.lines.pop(); + } else { + // The line is the cursor, scroll down + this.ybase++; + this.ydisp++; + } + } + } + } + + // Reduce max length if needed after adjustments, this is done after as it + // would otherwise cut data from the bottom of the buffer. + if (newMaxLength < this.lines.maxLength) { + // Trim from the top of the buffer and adjust ybase and ydisp. + const amountToTrim = this.lines.length - newMaxLength; + if (amountToTrim > 0) { + this.lines.trimStart(amountToTrim); + this.ybase = Math.max(this.ybase - amountToTrim, 0); + this.ydisp = Math.max(this.ydisp - amountToTrim, 0); + this.savedY = Math.max(this.savedY - amountToTrim, 0); + } + this.lines.maxLength = newMaxLength; + } + + // Make sure that the cursor stays on screen + this.x = Math.min(this.x, newCols - 1); + this.y = Math.min(this.y, newRows - 1); + if (addToY) { + this.y += addToY; + } + this.savedX = Math.min(this.savedX, newCols - 1); + + this.scrollTop = 0; + } + + this.scrollBottom = newRows - 1; + + if (this._isReflowEnabled) { + this._reflow(newCols, newRows); + + // Trim the end of the line off if cols shrunk + if (this._cols > newCols) { + for (let i = 0; i < this.lines.length; i++) { + this.lines.get(i)!.resize(newCols, nullCell); + } + } + } + + this._cols = newCols; + this._rows = newRows; + } + + private get _isReflowEnabled(): boolean { + return this._hasScrollback && !this._optionsService.rawOptions.windowsMode; + } + + private _reflow(newCols: number, newRows: number): void { + if (this._cols === newCols) { + return; + } + + // Iterate through rows, ignore the last one as it cannot be wrapped + if (newCols > this._cols) { + this._reflowLarger(newCols, newRows); + } else { + this._reflowSmaller(newCols, newRows); + } + } + + private _reflowLarger(newCols: number, newRows: number): void { + const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA)); + if (toRemove.length > 0) { + const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove); + reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout); + this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved); + } + } + + private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void { + const nullCell = this.getNullCell(DEFAULT_ATTR_DATA); + // Adjust viewport based on number of items removed + let viewportAdjustments = countRemoved; + while (viewportAdjustments-- > 0) { + if (this.ybase === 0) { + if (this.y > 0) { + this.y--; + } + if (this.lines.length < newRows) { + // Add an extra row at the bottom of the viewport + this.lines.push(new BufferLine(newCols, nullCell)); + } + } else { + if (this.ydisp === this.ybase) { + this.ydisp--; + } + this.ybase--; + } + } + this.savedY = Math.max(this.savedY - countRemoved, 0); + } + + private _reflowSmaller(newCols: number, newRows: number): void { + const nullCell = this.getNullCell(DEFAULT_ATTR_DATA); + // Gather all BufferLines that need to be inserted into the Buffer here so that they can be + // batched up and only committed once + const toInsert = []; + let countToInsert = 0; + // Go backwards as many lines may be trimmed and this will avoid considering them + for (let y = this.lines.length - 1; y >= 0; y--) { + // Check whether this line is a problem + let nextLine = this.lines.get(y) as BufferLine; + if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) { + continue; + } + + // Gather wrapped lines and adjust y to be the starting line + const wrappedLines: BufferLine[] = [nextLine]; + while (nextLine.isWrapped && y > 0) { + nextLine = this.lines.get(--y) as BufferLine; + wrappedLines.unshift(nextLine); + } + + // If these lines contain the cursor don't touch them, the program will handle fixing up + // wrapped lines with the cursor + const absoluteY = this.ybase + this.y; + if (absoluteY >= y && absoluteY < y + wrappedLines.length) { + continue; + } + + const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength(); + const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols); + const linesToAdd = destLineLengths.length - wrappedLines.length; + let trimmedLines: number; + if (this.ybase === 0 && this.y !== this.lines.length - 1) { + // If the top section of the buffer is not yet filled + trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd); + } else { + trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd); + } + + // Add the new lines + const newLines: BufferLine[] = []; + for (let i = 0; i < linesToAdd; i++) { + const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine; + newLines.push(newLine); + } + if (newLines.length > 0) { + toInsert.push({ + // countToInsert here gets the actual index, taking into account other inserted items. + // using this we can iterate through the list forwards + start: y + wrappedLines.length + countToInsert, + newLines + }); + countToInsert += newLines.length; + } + wrappedLines.push(...newLines); + + // Copy buffer data to new locations, this needs to happen backwards to do in-place + let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols); + let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols; + if (destCol === 0) { + destLineIndex--; + destCol = destLineLengths[destLineIndex]; + } + let srcLineIndex = wrappedLines.length - linesToAdd - 1; + let srcCol = lastLineLength; + while (srcLineIndex >= 0) { + const cellsToCopy = Math.min(srcCol, destCol); + if (wrappedLines[destLineIndex] === undefined) { + // Sanity check that the line exists, this has been known to fail for an unknown reason + // which would stop the reflow from happening if an exception would throw. + break; + } + wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true); + destCol -= cellsToCopy; + if (destCol === 0) { + destLineIndex--; + destCol = destLineLengths[destLineIndex]; + } + srcCol -= cellsToCopy; + if (srcCol === 0) { + srcLineIndex--; + const wrappedLinesIndex = Math.max(srcLineIndex, 0); + srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols); + } + } + + // Null out the end of the line ends if a wide character wrapped to the following line + for (let i = 0; i < wrappedLines.length; i++) { + if (destLineLengths[i] < newCols) { + wrappedLines[i].setCell(destLineLengths[i], nullCell); + } + } + + // Adjust viewport as needed + let viewportAdjustments = linesToAdd - trimmedLines; + while (viewportAdjustments-- > 0) { + if (this.ybase === 0) { + if (this.y < newRows - 1) { + this.y++; + this.lines.pop(); + } else { + this.ybase++; + this.ydisp++; + } + } else { + // Ensure ybase does not exceed its maximum value + if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) { + if (this.ybase === this.ydisp) { + this.ydisp++; + } + this.ybase++; + } + } + } + this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1); + } + + // Rearrange lines in the buffer if there are any insertions, this is done at the end rather + // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many + // costly calls to CircularList.splice. + if (toInsert.length > 0) { + // Record buffer insert events and then play them back backwards so that the indexes are + // correct + const insertEvents: IInsertEvent[] = []; + + // Record original lines so they don't get overridden when we rearrange the list + const originalLines: BufferLine[] = []; + for (let i = 0; i < this.lines.length; i++) { + originalLines.push(this.lines.get(i) as BufferLine); + } + const originalLinesLength = this.lines.length; + + let originalLineIndex = originalLinesLength - 1; + let nextToInsertIndex = 0; + let nextToInsert = toInsert[nextToInsertIndex]; + this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert); + let countInsertedSoFar = 0; + for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) { + if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) { + // Insert extra lines here, adjusting i as needed + for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) { + this.lines.set(i--, nextToInsert.newLines[nextI]); + } + i++; + + // Create insert events for later + insertEvents.push({ + index: originalLineIndex + 1, + amount: nextToInsert.newLines.length + }); + + countInsertedSoFar += nextToInsert.newLines.length; + nextToInsert = toInsert[++nextToInsertIndex]; + } else { + this.lines.set(i, originalLines[originalLineIndex--]); + } + } + + // Update markers + let insertCountEmitted = 0; + for (let i = insertEvents.length - 1; i >= 0; i--) { + insertEvents[i].index += insertCountEmitted; + this.lines.onInsertEmitter.fire(insertEvents[i]); + insertCountEmitted += insertEvents[i].amount; + } + const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength); + if (amountToTrim > 0) { + this.lines.onTrimEmitter.fire(amountToTrim); + } + } + } + + // private _reflowSmallerGetLinesNeeded() + + /** + * Translates a string index back to a BufferIndex. + * To get the correct buffer position the string must start at `startCol` 0 + * (default in translateBufferLineToString). + * The method also works on wrapped line strings given rows were not trimmed. + * The method operates on the CharData string length, there are no + * additional content or boundary checks. Therefore the string and the buffer + * should not be altered in between. + * TODO: respect trim flag after fixing #1685 + * @param lineIndex line index the string was retrieved from + * @param stringIndex index within the string + * @param startCol column offset the string was retrieved from + */ + public stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight: boolean = false): BufferIndex { + while (stringIndex) { + const line = this.lines.get(lineIndex); + if (!line) { + return [-1, -1]; + } + const length = (trimRight) ? line.getTrimmedLength() : line.length; + for (let i = 0; i < length; ++i) { + if (line.get(i)[CHAR_DATA_WIDTH_INDEX]) { + // empty cells report a string length of 0, but get replaced + // with a whitespace in translateToString, thus replace with 1 + stringIndex -= line.get(i)[CHAR_DATA_CHAR_INDEX].length || 1; + } + if (stringIndex < 0) { + return [lineIndex, i]; + } + } + lineIndex++; + } + return [lineIndex, 0]; + } + + /** + * Translates a buffer line to a string, with optional start and end columns. + * Wide characters will count as two columns in the resulting string. This + * function is useful for getting the actual text underneath the raw selection + * position. + * @param line The line being translated. + * @param trimRight Whether to trim whitespace to the right. + * @param startCol The column to start at. + * @param endCol The column to end at. + */ + public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string { + const line = this.lines.get(lineIndex); + if (!line) { + return ''; + } + return line.translateToString(trimRight, startCol, endCol); + } + + public getWrappedRangeForLine(y: number): { first: number, last: number } { + let first = y; + let last = y; + // Scan upwards for wrapped lines + while (first > 0 && this.lines.get(first)!.isWrapped) { + first--; + } + // Scan downwards for wrapped lines + while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) { + last++; + } + return { first, last }; + } + + /** + * Setup the tab stops. + * @param i The index to start setting up tab stops from. + */ + public setupTabStops(i?: number): void { + if (i !== null && i !== undefined) { + if (!this.tabs[i]) { + i = this.prevStop(i); + } + } else { + this.tabs = {}; + i = 0; + } + + for (; i < this._cols; i += this._optionsService.rawOptions.tabStopWidth) { + this.tabs[i] = true; + } + } + + /** + * Move the cursor to the previous tab stop from the given position (default is current). + * @param x The position to move the cursor to the previous tab stop. + */ + public prevStop(x?: number): number { + if (x === null || x === undefined) { + x = this.x; + } + while (!this.tabs[--x] && x > 0); + return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x; + } + + /** + * Move the cursor one tab stop forward from the given position (default is current). + * @param x The position to move the cursor one tab stop forward. + */ + public nextStop(x?: number): number { + if (x === null || x === undefined) { + x = this.x; + } + while (!this.tabs[++x] && x < this._cols); + return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x; + } + + public addMarker(y: number): Marker { + const marker = new Marker(y); + this.markers.push(marker); + marker.register(this.lines.onTrim(amount => { + marker.line -= amount; + // The marker should be disposed when the line is trimmed from the buffer + if (marker.line < 0) { + marker.dispose(); + } + })); + marker.register(this.lines.onInsert(event => { + if (marker.line >= event.index) { + marker.line += event.amount; + } + })); + marker.register(this.lines.onDelete(event => { + // Delete the marker if it's within the range + if (marker.line >= event.index && marker.line < event.index + event.amount) { + marker.dispose(); + } + + // Shift the marker if it's after the deleted range + if (marker.line > event.index) { + marker.line -= event.amount; + } + })); + marker.register(marker.onDispose(() => this._removeMarker(marker))); + return marker; + } + + private _removeMarker(marker: Marker): void { + this.markers.splice(this.markers.indexOf(marker), 1); + } + + public iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator { + return new BufferStringIterator(this, trimRight, startIndex, endIndex, startOverscan, endOverscan); + } +} + +/** + * Iterator to get unwrapped content strings from the buffer. + * The iterator returns at least the string data between the borders + * `startIndex` and `endIndex` (exclusive) and will expand the lines + * by `startOverscan` to the top and by `endOverscan` to the bottom, + * if no new line was found in between. + * It will never read/return string data beyond `startIndex - startOverscan` + * or `endIndex + endOverscan`. Therefore the first and last line might be truncated. + * It is possible to always get the full string for the first and last line as well + * by setting the overscan values to the actual buffer length. This not recommended + * since it might return the whole buffer within a single string in a worst case scenario. + */ +export class BufferStringIterator implements IBufferStringIterator { + private _current: number; + + constructor ( + private _buffer: IBuffer, + private _trimRight: boolean, + private _startIndex: number = 0, + private _endIndex: number = _buffer.lines.length, + private _startOverscan: number = 0, + private _endOverscan: number = 0 + ) { + if (this._startIndex < 0) { + this._startIndex = 0; + } + if (this._endIndex > this._buffer.lines.length) { + this._endIndex = this._buffer.lines.length; + } + this._current = this._startIndex; + } + + public hasNext(): boolean { + return this._current < this._endIndex; + } + + public next(): IBufferStringIteratorResult { + const range = this._buffer.getWrappedRangeForLine(this._current); + // limit search window to overscan value at both borders + if (range.first < this._startIndex - this._startOverscan) { + range.first = this._startIndex - this._startOverscan; + } + if (range.last > this._endIndex + this._endOverscan) { + range.last = this._endIndex + this._endOverscan; + } + // limit to current buffer length + range.first = Math.max(range.first, 0); + range.last = Math.min(range.last, this._buffer.lines.length); + let content = ''; + for (let i = range.first; i <= range.last; ++i) { + content += this._buffer.translateBufferLineToString(i, this._trimRight); + } + this._current = range.last + 1; + return { range, content }; + } +} diff --git a/node_modules/xterm/src/common/buffer/BufferLine.ts b/node_modules/xterm/src/common/buffer/BufferLine.ts new file mode 100644 index 0000000..f0bf4fc --- /dev/null +++ b/node_modules/xterm/src/common/buffer/BufferLine.ts @@ -0,0 +1,441 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CharData, IBufferLine, ICellData, IAttributeData, IExtendedAttrs } from 'common/Types'; +import { stringFromCodePoint } from 'common/input/TextDecoder'; +import { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, Content, BgFlags } from 'common/buffer/Constants'; +import { CellData } from 'common/buffer/CellData'; +import { AttributeData, ExtendedAttrs } from 'common/buffer/AttributeData'; + +/** + * buffer memory layout: + * + * | uint32_t | uint32_t | uint32_t | + * | `content` | `FG` | `BG` | + * | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) | + */ + + +/** typed array slots taken by one cell */ +const CELL_SIZE = 3; + +/** + * Cell member indices. + * + * Direct access: + * `content = data[column * CELL_SIZE + Cell.CONTENT];` + * `fg = data[column * CELL_SIZE + Cell.FG];` + * `bg = data[column * CELL_SIZE + Cell.BG];` + */ +const enum Cell { + CONTENT = 0, + FG = 1, // currently simply holds all known attrs + BG = 2 // currently unused +} + +export const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData()); + +/** + * Typed array based bufferline implementation. + * + * There are 2 ways to insert data into the cell buffer: + * - `setCellFromCodepoint` + `addCodepointToCell` + * Use these for data that is already UTF32. + * Used during normal input in `InputHandler` for faster buffer access. + * - `setCell` + * This method takes a CellData object and stores the data in the buffer. + * Use `CellData.fromCharData` to create the CellData object (e.g. from JS string). + * + * To retrieve data from the buffer use either one of the primitive methods + * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop + * memory allocs / GC pressure can be greatly reduced by reusing the CellData object. + */ +export class BufferLine implements IBufferLine { + protected _data: Uint32Array; + protected _combined: {[index: number]: string} = {}; + protected _extendedAttrs: {[index: number]: ExtendedAttrs} = {}; + public length: number; + + constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) { + this._data = new Uint32Array(cols * CELL_SIZE); + const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]); + for (let i = 0; i < cols; ++i) { + this.setCell(i, cell); + } + this.length = cols; + } + + /** + * Get cell data CharData. + * @deprecated + */ + public get(index: number): CharData { + const content = this._data[index * CELL_SIZE + Cell.CONTENT]; + const cp = content & Content.CODEPOINT_MASK; + return [ + this._data[index * CELL_SIZE + Cell.FG], + (content & Content.IS_COMBINED_MASK) + ? this._combined[index] + : (cp) ? stringFromCodePoint(cp) : '', + content >> Content.WIDTH_SHIFT, + (content & Content.IS_COMBINED_MASK) + ? this._combined[index].charCodeAt(this._combined[index].length - 1) + : cp + ]; + } + + /** + * Set cell data from CharData. + * @deprecated + */ + public set(index: number, value: CharData): void { + this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX]; + if (value[CHAR_DATA_CHAR_INDEX].length > 1) { + this._combined[index] = value[1]; + this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } else { + this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + } + + /** + * primitive getters + * use these when only one value is needed, otherwise use `loadCell` + */ + public getWidth(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT; + } + + /** Test whether content has width. */ + public hasWidth(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK; + } + + /** Get FG cell component. */ + public getFg(index: number): number { + return this._data[index * CELL_SIZE + Cell.FG]; + } + + /** Get BG cell component. */ + public getBg(index: number): number { + return this._data[index * CELL_SIZE + Cell.BG]; + } + + /** + * Test whether contains any chars. + * Basically an empty has no content, but other cells might differ in FG/BG + * from real empty cells. + * */ + public hasContent(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK; + } + + /** + * Get codepoint of the cell. + * To be in line with `code` in CharData this either returns + * a single UTF32 codepoint or the last codepoint of a combined string. + */ + public getCodePoint(index: number): number { + const content = this._data[index * CELL_SIZE + Cell.CONTENT]; + if (content & Content.IS_COMBINED_MASK) { + return this._combined[index].charCodeAt(this._combined[index].length - 1); + } + return content & Content.CODEPOINT_MASK; + } + + /** Test whether the cell contains a combined string. */ + public isCombined(index: number): number { + return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK; + } + + /** Returns the string content of the cell. */ + public getString(index: number): string { + const content = this._data[index * CELL_SIZE + Cell.CONTENT]; + if (content & Content.IS_COMBINED_MASK) { + return this._combined[index]; + } + if (content & Content.CODEPOINT_MASK) { + return stringFromCodePoint(content & Content.CODEPOINT_MASK); + } + // return empty string for empty cells + return ''; + } + + /** + * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly + * to GC as it significantly reduced the amount of new objects/references needed. + */ + public loadCell(index: number, cell: ICellData): ICellData { + const startIndex = index * CELL_SIZE; + cell.content = this._data[startIndex + Cell.CONTENT]; + cell.fg = this._data[startIndex + Cell.FG]; + cell.bg = this._data[startIndex + Cell.BG]; + if (cell.content & Content.IS_COMBINED_MASK) { + cell.combinedData = this._combined[index]; + } + if (cell.bg & BgFlags.HAS_EXTENDED) { + cell.extended = this._extendedAttrs[index]; + } + return cell; + } + + /** + * Set data at `index` to `cell`. + */ + public setCell(index: number, cell: ICellData): void { + if (cell.content & Content.IS_COMBINED_MASK) { + this._combined[index] = cell.combinedData; + } + if (cell.bg & BgFlags.HAS_EXTENDED) { + this._extendedAttrs[index] = cell.extended; + } + this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content; + this._data[index * CELL_SIZE + Cell.FG] = cell.fg; + this._data[index * CELL_SIZE + Cell.BG] = cell.bg; + } + + /** + * Set cell data from input handler. + * Since the input handler see the incoming chars as UTF32 codepoints, + * it gets an optimized access method. + */ + public setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number, eAttrs: IExtendedAttrs): void { + if (bg & BgFlags.HAS_EXTENDED) { + this._extendedAttrs[index] = eAttrs; + } + this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT); + this._data[index * CELL_SIZE + Cell.FG] = fg; + this._data[index * CELL_SIZE + Cell.BG] = bg; + } + + /** + * Add a codepoint to a cell from input handler. + * During input stage combining chars with a width of 0 follow and stack + * onto a leading char. Since we already set the attrs + * by the previous `setDataFromCodePoint` call, we can omit it here. + */ + public addCodepointToCell(index: number, codePoint: number): void { + let content = this._data[index * CELL_SIZE + Cell.CONTENT]; + if (content & Content.IS_COMBINED_MASK) { + // we already have a combined string, simply add + this._combined[index] += stringFromCodePoint(codePoint); + } else { + if (content & Content.CODEPOINT_MASK) { + // normal case for combining chars: + // - move current leading char + new one into combined string + // - set combined flag + this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint); + content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0 + content |= Content.IS_COMBINED_MASK; + } else { + // should not happen - we actually have no data in the cell yet + // simply set the data in the cell buffer with a width of 1 + content = codePoint | (1 << Content.WIDTH_SHIFT); + } + this._data[index * CELL_SIZE + Cell.CONTENT] = content; + } + } + + public insertCells(pos: number, n: number, fillCellData: ICellData, eraseAttr?: IAttributeData): void { + pos %= this.length; + + // handle fullwidth at pos: reset cell one to the left if pos is second cell of a wide char + if (pos && this.getWidth(pos - 1) === 2) { + this.setCellFromCodePoint(pos - 1, 0, 1, eraseAttr?.fg || 0, eraseAttr?.bg || 0, eraseAttr?.extended || new ExtendedAttrs()); + } + + if (n < this.length - pos) { + const cell = new CellData(); + for (let i = this.length - pos - n - 1; i >= 0; --i) { + this.setCell(pos + n + i, this.loadCell(pos + i, cell)); + } + for (let i = 0; i < n; ++i) { + this.setCell(pos + i, fillCellData); + } + } else { + for (let i = pos; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } + + // handle fullwidth at line end: reset last cell if it is first cell of a wide char + if (this.getWidth(this.length - 1) === 2) { + this.setCellFromCodePoint(this.length - 1, 0, 1, eraseAttr?.fg || 0, eraseAttr?.bg || 0, eraseAttr?.extended || new ExtendedAttrs()); + } + } + + public deleteCells(pos: number, n: number, fillCellData: ICellData, eraseAttr?: IAttributeData): void { + pos %= this.length; + if (n < this.length - pos) { + const cell = new CellData(); + for (let i = 0; i < this.length - pos - n; ++i) { + this.setCell(pos + i, this.loadCell(pos + n + i, cell)); + } + for (let i = this.length - n; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } else { + for (let i = pos; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } + + // handle fullwidth at pos: + // - reset pos-1 if wide char + // - reset pos if width==0 (previous second cell of a wide char) + if (pos && this.getWidth(pos - 1) === 2) { + this.setCellFromCodePoint(pos - 1, 0, 1, eraseAttr?.fg || 0, eraseAttr?.bg || 0, eraseAttr?.extended || new ExtendedAttrs()); + } + if (this.getWidth(pos) === 0 && !this.hasContent(pos)) { + this.setCellFromCodePoint(pos, 0, 1, eraseAttr?.fg || 0, eraseAttr?.bg || 0, eraseAttr?.extended || new ExtendedAttrs()); + } + } + + public replaceCells(start: number, end: number, fillCellData: ICellData, eraseAttr?: IAttributeData): void { + // handle fullwidth at start: reset cell one to the left if start is second cell of a wide char + if (start && this.getWidth(start - 1) === 2) { + this.setCellFromCodePoint(start - 1, 0, 1, eraseAttr?.fg || 0, eraseAttr?.bg || 0, eraseAttr?.extended || new ExtendedAttrs()); + } + // handle fullwidth at last cell + 1: reset to empty cell if it is second part of a wide char + if (end < this.length && this.getWidth(end - 1) === 2) { + this.setCellFromCodePoint(end, 0, 1, eraseAttr?.fg || 0, eraseAttr?.bg || 0, eraseAttr?.extended || new ExtendedAttrs()); + } + + while (start < end && start < this.length) { + this.setCell(start++, fillCellData); + } + } + + public resize(cols: number, fillCellData: ICellData): void { + if (cols === this.length) { + return; + } + if (cols > this.length) { + const data = new Uint32Array(cols * CELL_SIZE); + if (this.length) { + if (cols * CELL_SIZE < this._data.length) { + data.set(this._data.subarray(0, cols * CELL_SIZE)); + } else { + data.set(this._data); + } + } + this._data = data; + for (let i = this.length; i < cols; ++i) { + this.setCell(i, fillCellData); + } + } else { + if (cols) { + const data = new Uint32Array(cols * CELL_SIZE); + data.set(this._data.subarray(0, cols * CELL_SIZE)); + this._data = data; + // Remove any cut off combined data, FIXME: repeat this for extended attrs + const keys = Object.keys(this._combined); + for (let i = 0; i < keys.length; i++) { + const key = parseInt(keys[i], 10); + if (key >= cols) { + delete this._combined[key]; + } + } + } else { + this._data = new Uint32Array(0); + this._combined = {}; + } + } + this.length = cols; + } + + /** fill a line with fillCharData */ + public fill(fillCellData: ICellData): void { + this._combined = {}; + this._extendedAttrs = {}; + for (let i = 0; i < this.length; ++i) { + this.setCell(i, fillCellData); + } + } + + /** alter to a full copy of line */ + public copyFrom(line: BufferLine): void { + if (this.length !== line.length) { + this._data = new Uint32Array(line._data); + } else { + // use high speed copy if lengths are equal + this._data.set(line._data); + } + this.length = line.length; + this._combined = {}; + for (const el in line._combined) { + this._combined[el] = line._combined[el]; + } + this._extendedAttrs = {}; + for (const el in line._extendedAttrs) { + this._extendedAttrs[el] = line._extendedAttrs[el]; + } + this.isWrapped = line.isWrapped; + } + + /** create a new clone */ + public clone(): IBufferLine { + const newLine = new BufferLine(0); + newLine._data = new Uint32Array(this._data); + newLine.length = this.length; + for (const el in this._combined) { + newLine._combined[el] = this._combined[el]; + } + for (const el in this._extendedAttrs) { + newLine._extendedAttrs[el] = this._extendedAttrs[el]; + } + newLine.isWrapped = this.isWrapped; + return newLine; + } + + public getTrimmedLength(): number { + for (let i = this.length - 1; i >= 0; --i) { + if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) { + return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT); + } + } + return 0; + } + + public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void { + const srcData = src._data; + if (applyInReverse) { + for (let cell = length - 1; cell >= 0; cell--) { + for (let i = 0; i < CELL_SIZE; i++) { + this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i]; + } + } + } else { + for (let cell = 0; cell < length; cell++) { + for (let i = 0; i < CELL_SIZE; i++) { + this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i]; + } + } + } + + // Move any combined data over as needed, FIXME: repeat for extended attrs + const srcCombinedKeys = Object.keys(src._combined); + for (let i = 0; i < srcCombinedKeys.length; i++) { + const key = parseInt(srcCombinedKeys[i], 10); + if (key >= srcCol) { + this._combined[key - srcCol + destCol] = src._combined[key]; + } + } + } + + public translateToString(trimRight: boolean = false, startCol: number = 0, endCol: number = this.length): string { + if (trimRight) { + endCol = Math.min(endCol, this.getTrimmedLength()); + } + let result = ''; + while (startCol < endCol) { + const content = this._data[startCol * CELL_SIZE + Cell.CONTENT]; + const cp = content & Content.CODEPOINT_MASK; + result += (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR; + startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by 1 + } + return result; + } +} diff --git a/node_modules/xterm/src/common/buffer/BufferRange.ts b/node_modules/xterm/src/common/buffer/BufferRange.ts new file mode 100644 index 0000000..a49cf48 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/BufferRange.ts @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferRange } from 'xterm'; + +export function getRangeLength(range: IBufferRange, bufferCols: number): number { + if (range.start.y > range.end.y) { + throw new Error(`Buffer range end (${range.end.x}, ${range.end.y}) cannot be before start (${range.start.x}, ${range.start.y})`); + } + return bufferCols * (range.end.y - range.start.y) + (range.end.x - range.start.x + 1); +} diff --git a/node_modules/xterm/src/common/buffer/BufferReflow.ts b/node_modules/xterm/src/common/buffer/BufferReflow.ts new file mode 100644 index 0000000..ece9a96 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/BufferReflow.ts @@ -0,0 +1,220 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { BufferLine } from 'common/buffer/BufferLine'; +import { CircularList } from 'common/CircularList'; +import { IBufferLine, ICellData } from 'common/Types'; + +export interface INewLayoutResult { + layout: number[]; + countRemoved: number; +} + +/** + * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed + * when a wrapped line unwraps. + * @param lines The buffer lines. + * @param newCols The columns after resize. + */ +export function reflowLargerGetLinesToRemove(lines: CircularList<IBufferLine>, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData): number[] { + // Gather all BufferLines that need to be removed from the Buffer here so that they can be + // batched up and only committed once + const toRemove: number[] = []; + + for (let y = 0; y < lines.length - 1; y++) { + // Check if this row is wrapped + let i = y; + let nextLine = lines.get(++i) as BufferLine; + if (!nextLine.isWrapped) { + continue; + } + + // Check how many lines it's wrapped for + const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine]; + while (i < lines.length && nextLine.isWrapped) { + wrappedLines.push(nextLine); + nextLine = lines.get(++i) as BufferLine; + } + + // If these lines contain the cursor don't touch them, the program will handle fixing up wrapped + // lines with the cursor + if (bufferAbsoluteY >= y && bufferAbsoluteY < i) { + y += wrappedLines.length - 1; + continue; + } + + // Copy buffer data to new locations + let destLineIndex = 0; + let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols); + let srcLineIndex = 1; + let srcCol = 0; + while (srcLineIndex < wrappedLines.length) { + const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols); + const srcRemainingCells = srcTrimmedTineLength - srcCol; + const destRemainingCells = newCols - destCol; + const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells); + + wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false); + + destCol += cellsToCopy; + if (destCol === newCols) { + destLineIndex++; + destCol = 0; + } + srcCol += cellsToCopy; + if (srcCol === srcTrimmedTineLength) { + srcLineIndex++; + srcCol = 0; + } + + // Make sure the last cell isn't wide, if it is copy it to the current dest + if (destCol === 0 && destLineIndex !== 0) { + if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) { + wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false); + // Null out the end of the last row + wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell); + } + } + } + + // Clear out remaining cells or fragments could remain; + wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell); + + // Work backwards and remove any rows at the end that only contain null cells + let countToRemove = 0; + for (let i = wrappedLines.length - 1; i > 0; i--) { + if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) { + countToRemove++; + } else { + break; + } + } + + if (countToRemove > 0) { + toRemove.push(y + wrappedLines.length - countToRemove); // index + toRemove.push(countToRemove); + } + + y += wrappedLines.length - 1; + } + return toRemove; +} + +/** + * Creates and return the new layout for lines given an array of indexes to be removed. + * @param lines The buffer lines. + * @param toRemove The indexes to remove. + */ +export function reflowLargerCreateNewLayout(lines: CircularList<IBufferLine>, toRemove: number[]): INewLayoutResult { + const layout: number[] = []; + // First iterate through the list and get the actual indexes to use for rows + let nextToRemoveIndex = 0; + let nextToRemoveStart = toRemove[nextToRemoveIndex]; + let countRemovedSoFar = 0; + for (let i = 0; i < lines.length; i++) { + if (nextToRemoveStart === i) { + const countToRemove = toRemove[++nextToRemoveIndex]; + + // Tell markers that there was a deletion + lines.onDeleteEmitter.fire({ + index: i - countRemovedSoFar, + amount: countToRemove + }); + + i += countToRemove - 1; + countRemovedSoFar += countToRemove; + nextToRemoveStart = toRemove[++nextToRemoveIndex]; + } else { + layout.push(i); + } + } + return { + layout, + countRemoved: countRemovedSoFar + }; +} + +/** + * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's + * done all at once in a single iteration through the list since splice is very expensive. + * @param lines The buffer lines. + * @param newLayout The new layout to apply. + */ +export function reflowLargerApplyNewLayout(lines: CircularList<IBufferLine>, newLayout: number[]): void { + // Record original lines so they don't get overridden when we rearrange the list + const newLayoutLines: BufferLine[] = []; + for (let i = 0; i < newLayout.length; i++) { + newLayoutLines.push(lines.get(newLayout[i]) as BufferLine); + } + + // Rearrange the list + for (let i = 0; i < newLayoutLines.length; i++) { + lines.set(i, newLayoutLines[i]); + } + lines.length = newLayout.length; +} + +/** + * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre- + * compute the wrapping points since wide characters may need to be wrapped onto the following line. + * This function will return an array of numbers of where each line wraps to, the resulting array + * will only contain the values `newCols` (when the line does not end with a wide character) and + * `newCols - 1` (when the line does end with a wide character), except for the last value which + * will contain the remaining items to fill the line. + * + * Calling this with a `newCols` value of `1` will lock up. + * + * @param wrappedLines The wrapped lines to evaluate. + * @param oldCols The columns before resize. + * @param newCols The columns after resize. + */ +export function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] { + const newLineLengths: number[] = []; + const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c); + + // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and + // linesNeeded + let srcCol = 0; + let srcLine = 0; + let cellsAvailable = 0; + while (cellsAvailable < cellsNeeded) { + if (cellsNeeded - cellsAvailable < newCols) { + // Add the final line and exit the loop + newLineLengths.push(cellsNeeded - cellsAvailable); + break; + } + srcCol += newCols; + const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols); + if (srcCol > oldTrimmedLength) { + srcCol -= oldTrimmedLength; + srcLine++; + } + const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2; + if (endsWithWide) { + srcCol--; + } + const lineLength = endsWithWide ? newCols - 1 : newCols; + newLineLengths.push(lineLength); + cellsAvailable += lineLength; + } + + return newLineLengths; +} + +export function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number { + // If this is the last row in the wrapped line, get the actual trimmed length + if (i === lines.length - 1) { + return lines[i].getTrimmedLength(); + } + // Detect whether the following line starts with a wide character and the end of the current line + // is null, if so then we can be pretty sure the null character should be excluded from the line + // length] + const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1; + const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2; + if (endsInNull && followingLineStartsWithWide) { + return cols - 1; + } + return cols; +} diff --git a/node_modules/xterm/src/common/buffer/BufferSet.ts b/node_modules/xterm/src/common/buffer/BufferSet.ts new file mode 100644 index 0000000..de220e8 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/BufferSet.ts @@ -0,0 +1,131 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBuffer, IBufferSet } from 'common/buffer/Types'; +import { IAttributeData } from 'common/Types'; +import { Buffer } from 'common/buffer/Buffer'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { IOptionsService, IBufferService } from 'common/services/Services'; +import { Disposable } from 'common/Lifecycle'; + +/** + * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and + * provides also utilities for working with them. + */ +export class BufferSet extends Disposable implements IBufferSet { + private _normal!: Buffer; + private _alt!: Buffer; + private _activeBuffer!: Buffer; + + private _onBufferActivate = this.register(new EventEmitter<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}>()); + public get onBufferActivate(): IEvent<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}> { return this._onBufferActivate.event; } + + /** + * Create a new BufferSet for the given terminal. + * @param _terminal - The terminal the BufferSet will belong to + */ + constructor( + private readonly _optionsService: IOptionsService, + private readonly _bufferService: IBufferService + ) { + super(); + this.reset(); + } + + public reset(): void { + this._normal = new Buffer(true, this._optionsService, this._bufferService); + this._normal.fillViewportRows(); + + // The alt buffer should never have scrollback. + // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer + this._alt = new Buffer(false, this._optionsService, this._bufferService); + this._activeBuffer = this._normal; + this._onBufferActivate.fire({ + activeBuffer: this._normal, + inactiveBuffer: this._alt + }); + + this.setupTabStops(); + } + + /** + * Returns the alt Buffer of the BufferSet + */ + public get alt(): Buffer { + return this._alt; + } + + /** + * Returns the normal Buffer of the BufferSet + */ + public get active(): Buffer { + return this._activeBuffer; + } + + /** + * Returns the currently active Buffer of the BufferSet + */ + public get normal(): Buffer { + return this._normal; + } + + /** + * Sets the normal Buffer of the BufferSet as its currently active Buffer + */ + public activateNormalBuffer(): void { + if (this._activeBuffer === this._normal) { + return; + } + this._normal.x = this._alt.x; + this._normal.y = this._alt.y; + // The alt buffer should always be cleared when we switch to the normal + // buffer. This frees up memory since the alt buffer should always be new + // when activated. + this._alt.clear(); + this._activeBuffer = this._normal; + this._onBufferActivate.fire({ + activeBuffer: this._normal, + inactiveBuffer: this._alt + }); + } + + /** + * Sets the alt Buffer of the BufferSet as its currently active Buffer + */ + public activateAltBuffer(fillAttr?: IAttributeData): void { + if (this._activeBuffer === this._alt) { + return; + } + // Since the alt buffer is always cleared when the normal buffer is + // activated, we want to fill it when switching to it. + this._alt.fillViewportRows(fillAttr); + this._alt.x = this._normal.x; + this._alt.y = this._normal.y; + this._activeBuffer = this._alt; + this._onBufferActivate.fire({ + activeBuffer: this._alt, + inactiveBuffer: this._normal + }); + } + + /** + * Resizes both normal and alt buffers, adjusting their data accordingly. + * @param newCols The new number of columns. + * @param newRows The new number of rows. + */ + public resize(newCols: number, newRows: number): void { + this._normal.resize(newCols, newRows); + this._alt.resize(newCols, newRows); + } + + /** + * Setup the tab stops. + * @param i The index to start setting up tab stops from. + */ + public setupTabStops(i?: number): void { + this._normal.setupTabStops(i); + this._alt.setupTabStops(i); + } +} diff --git a/node_modules/xterm/src/common/buffer/CellData.ts b/node_modules/xterm/src/common/buffer/CellData.ts new file mode 100644 index 0000000..a87b579 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/CellData.ts @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CharData, ICellData, IExtendedAttrs } from 'common/Types'; +import { stringFromCodePoint } from 'common/input/TextDecoder'; +import { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants'; +import { AttributeData, ExtendedAttrs } from 'common/buffer/AttributeData'; + +/** + * CellData - represents a single Cell in the terminal buffer. + */ +export class CellData extends AttributeData implements ICellData { + /** Helper to create CellData from CharData. */ + public static fromCharData(value: CharData): CellData { + const obj = new CellData(); + obj.setFromCharData(value); + return obj; + } + /** Primitives from terminal buffer. */ + public content = 0; + public fg = 0; + public bg = 0; + public extended: IExtendedAttrs = new ExtendedAttrs(); + public combinedData = ''; + /** Whether cell contains a combined string. */ + public isCombined(): number { + return this.content & Content.IS_COMBINED_MASK; + } + /** Width of the cell. */ + public getWidth(): number { + return this.content >> Content.WIDTH_SHIFT; + } + /** JS string of the content. */ + public getChars(): string { + if (this.content & Content.IS_COMBINED_MASK) { + return this.combinedData; + } + if (this.content & Content.CODEPOINT_MASK) { + return stringFromCodePoint(this.content & Content.CODEPOINT_MASK); + } + return ''; + } + /** + * Codepoint of cell + * Note this returns the UTF32 codepoint of single chars, + * if content is a combined string it returns the codepoint + * of the last char in string to be in line with code in CharData. + * */ + public getCode(): number { + return (this.isCombined()) + ? this.combinedData.charCodeAt(this.combinedData.length - 1) + : this.content & Content.CODEPOINT_MASK; + } + /** Set data from CharData */ + public setFromCharData(value: CharData): void { + this.fg = value[CHAR_DATA_ATTR_INDEX]; + this.bg = 0; + let combined = false; + // surrogates and combined strings need special treatment + if (value[CHAR_DATA_CHAR_INDEX].length > 2) { + combined = true; + } + else if (value[CHAR_DATA_CHAR_INDEX].length === 2) { + const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0); + // if the 2-char string is a surrogate create single codepoint + // everything else is combined + if (0xD800 <= code && code <= 0xDBFF) { + const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1); + if (0xDC00 <= second && second <= 0xDFFF) { + this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + else { + combined = true; + } + } + else { + combined = true; + } + } + else { + this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + if (combined) { + this.combinedData = value[CHAR_DATA_CHAR_INDEX]; + this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT); + } + } + /** Get data as CharData. */ + public getAsCharData(): CharData { + return [this.fg, this.getChars(), this.getWidth(), this.getCode()]; + } +} diff --git a/node_modules/xterm/src/common/buffer/Constants.ts b/node_modules/xterm/src/common/buffer/Constants.ts new file mode 100644 index 0000000..a2c1b88 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Constants.ts @@ -0,0 +1,139 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +export const DEFAULT_COLOR = 256; +export const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0); + +export const CHAR_DATA_ATTR_INDEX = 0; +export const CHAR_DATA_CHAR_INDEX = 1; +export const CHAR_DATA_WIDTH_INDEX = 2; +export const CHAR_DATA_CODE_INDEX = 3; + +/** + * Null cell - a real empty cell (containing nothing). + * Note that code should always be 0 for a null cell as + * several test condition of the buffer line rely on this. + */ +export const NULL_CELL_CHAR = ''; +export const NULL_CELL_WIDTH = 1; +export const NULL_CELL_CODE = 0; + +/** + * Whitespace cell. + * This is meant as a replacement for empty cells when needed + * during rendering lines to preserve correct aligment. + */ +export const WHITESPACE_CELL_CHAR = ' '; +export const WHITESPACE_CELL_WIDTH = 1; +export const WHITESPACE_CELL_CODE = 32; + +/** + * Bitmasks for accessing data in `content`. + */ +export const enum Content { + /** + * bit 1..21 codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken) + * read: `codepoint = content & Content.codepointMask;` + * write: `content |= codepoint & Content.codepointMask;` + * shortcut if precondition `codepoint <= 0x10FFFF` is met: + * `content |= codepoint;` + */ + CODEPOINT_MASK = 0x1FFFFF, + + /** + * bit 22 flag indication whether a cell contains combined content + * read: `isCombined = content & Content.isCombined;` + * set: `content |= Content.isCombined;` + * clear: `content &= ~Content.isCombined;` + */ + IS_COMBINED_MASK = 0x200000, // 1 << 21 + + /** + * bit 1..22 mask to check whether a cell contains any string data + * we need to check for codepoint and isCombined bits to see + * whether a cell contains anything + * read: `isEmpty = !(content & Content.hasContent)` + */ + HAS_CONTENT_MASK = 0x3FFFFF, + + /** + * bit 23..24 wcwidth value of cell, takes 2 bits (ranges from 0..2) + * read: `width = (content & Content.widthMask) >> Content.widthShift;` + * `hasWidth = content & Content.widthMask;` + * as long as wcwidth is highest value in `content`: + * `width = content >> Content.widthShift;` + * write: `content |= (width << Content.widthShift) & Content.widthMask;` + * shortcut if precondition `0 <= width <= 3` is met: + * `content |= width << Content.widthShift;` + */ + WIDTH_MASK = 0xC00000, // 3 << 22 + WIDTH_SHIFT = 22 +} + +export const enum Attributes { + /** + * bit 1..8 blue in RGB, color in P256 and P16 + */ + BLUE_MASK = 0xFF, + BLUE_SHIFT = 0, + PCOLOR_MASK = 0xFF, + PCOLOR_SHIFT = 0, + + /** + * bit 9..16 green in RGB + */ + GREEN_MASK = 0xFF00, + GREEN_SHIFT = 8, + + /** + * bit 17..24 red in RGB + */ + RED_MASK = 0xFF0000, + RED_SHIFT = 16, + + /** + * bit 25..26 color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3) + */ + CM_MASK = 0x3000000, + CM_DEFAULT = 0, + CM_P16 = 0x1000000, + CM_P256 = 0x2000000, + CM_RGB = 0x3000000, + + /** + * bit 1..24 RGB room + */ + RGB_MASK = 0xFFFFFF +} + +export const enum FgFlags { + /** + * bit 27..32 + */ + INVERSE = 0x4000000, + BOLD = 0x8000000, + UNDERLINE = 0x10000000, + BLINK = 0x20000000, + INVISIBLE = 0x40000000, + STRIKETHROUGH = 0x80000000, +} + +export const enum BgFlags { + /** + * bit 27..32 (upper 3 unused) + */ + ITALIC = 0x4000000, + DIM = 0x8000000, + HAS_EXTENDED = 0x10000000 +} + +export const enum UnderlineStyle { + NONE = 0, + SINGLE = 1, + DOUBLE = 2, + CURLY = 3, + DOTTED = 4, + DASHED = 5 +} diff --git a/node_modules/xterm/src/common/buffer/Marker.ts b/node_modules/xterm/src/common/buffer/Marker.ts new file mode 100644 index 0000000..72c4085 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Marker.ts @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { Disposable } from 'common/Lifecycle'; +import { IMarker } from 'common/Types'; + +export class Marker extends Disposable implements IMarker { + private static _nextId = 1; + + private _id: number = Marker._nextId++; + public isDisposed: boolean = false; + + public get id(): number { return this._id; } + + private _onDispose = new EventEmitter<void>(); + public get onDispose(): IEvent<void> { return this._onDispose.event; } + + constructor( + public line: number + ) { + super(); + } + + public dispose(): void { + if (this.isDisposed) { + return; + } + this.isDisposed = true; + this.line = -1; + // Emit before super.dispose such that dispose listeners get a change to react + this._onDispose.fire(); + super.dispose(); + } +} diff --git a/node_modules/xterm/src/common/buffer/Types.d.ts b/node_modules/xterm/src/common/buffer/Types.d.ts new file mode 100644 index 0000000..cbf40a0 --- /dev/null +++ b/node_modules/xterm/src/common/buffer/Types.d.ts @@ -0,0 +1,62 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IAttributeData, ICircularList, IBufferLine, ICellData, IMarker, ICharset, IDisposable } from 'common/Types'; +import { IEvent } from 'common/EventEmitter'; + +// BufferIndex denotes a position in the buffer: [rowIndex, colIndex] +export type BufferIndex = [number, number]; + +export interface IBufferStringIteratorResult { + range: {first: number, last: number}; + content: string; +} + +export interface IBufferStringIterator { + hasNext(): boolean; + next(): IBufferStringIteratorResult; +} + +export interface IBuffer { + readonly lines: ICircularList<IBufferLine>; + ydisp: number; + ybase: number; + y: number; + x: number; + tabs: any; + scrollBottom: number; + scrollTop: number; + hasScrollback: boolean; + savedY: number; + savedX: number; + savedCharset: ICharset | undefined; + savedCurAttrData: IAttributeData; + isCursorInViewport: boolean; + markers: IMarker[]; + translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol?: number, endCol?: number): string; + getWrappedRangeForLine(y: number): { first: number, last: number }; + nextStop(x?: number): number; + prevStop(x?: number): number; + getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine; + stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight?: boolean): number[]; + iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator; + getNullCell(attr?: IAttributeData): ICellData; + getWhitespaceCell(attr?: IAttributeData): ICellData; + addMarker(y: number): IMarker; +} + +export interface IBufferSet extends IDisposable { + alt: IBuffer; + normal: IBuffer; + active: IBuffer; + + onBufferActivate: IEvent<{ activeBuffer: IBuffer, inactiveBuffer: IBuffer }>; + + activateNormalBuffer(): void; + activateAltBuffer(fillAttr?: IAttributeData): void; + reset(): void; + resize(newCols: number, newRows: number): void; + setupTabStops(i?: number): void; +} diff --git a/node_modules/xterm/src/common/data/Charsets.ts b/node_modules/xterm/src/common/data/Charsets.ts new file mode 100644 index 0000000..c72d5a2 --- /dev/null +++ b/node_modules/xterm/src/common/data/Charsets.ts @@ -0,0 +1,256 @@ +/** + * Copyright (c) 2016 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICharset } from 'common/Types'; + +/** + * The character sets supported by the terminal. These enable several languages + * to be represented within the terminal with only 8-bit encoding. See ISO 2022 + * for a discussion on character sets. Only VT100 character sets are supported. + */ +export const CHARSETS: { [key: string]: ICharset | undefined } = {}; + +/** + * The default character set, US. + */ +export const DEFAULT_CHARSET: ICharset | undefined = CHARSETS['B']; + +/** + * DEC Special Character and Line Drawing Set. + * Reference: http://vt100.net/docs/vt102-ug/table5-13.html + * A lot of curses apps use this if they see TERM=xterm. + * testing: echo -e '\e(0a\e(B' + * The xterm output sometimes seems to conflict with the + * reference above. xterm seems in line with the reference + * when running vttest however. + * The table below now uses xterm's output from vttest. + */ +CHARSETS['0'] = { + '`': '\u25c6', // '◆' + 'a': '\u2592', // '▒' + 'b': '\u2409', // '␉' (HT) + 'c': '\u240c', // '␌' (FF) + 'd': '\u240d', // '␍' (CR) + 'e': '\u240a', // '␊' (LF) + 'f': '\u00b0', // '°' + 'g': '\u00b1', // '±' + 'h': '\u2424', // '' (NL) + 'i': '\u240b', // '␋' (VT) + 'j': '\u2518', // '┘' + 'k': '\u2510', // '┐' + 'l': '\u250c', // '┌' + 'm': '\u2514', // '└' + 'n': '\u253c', // '┼' + 'o': '\u23ba', // '⎺' + 'p': '\u23bb', // '⎻' + 'q': '\u2500', // '─' + 'r': '\u23bc', // '⎼' + 's': '\u23bd', // '⎽' + 't': '\u251c', // '├' + 'u': '\u2524', // '┤' + 'v': '\u2534', // '┴' + 'w': '\u252c', // '┬' + 'x': '\u2502', // '│' + 'y': '\u2264', // '≤' + 'z': '\u2265', // '≥' + '{': '\u03c0', // 'π' + '|': '\u2260', // '≠' + '}': '\u00a3', // '£' + '~': '\u00b7' // '·' +}; + +/** + * British character set + * ESC (A + * Reference: http://vt100.net/docs/vt220-rm/table2-5.html + */ +CHARSETS['A'] = { + '#': '£' +}; + +/** + * United States character set + * ESC (B + */ +CHARSETS['B'] = undefined; + +/** + * Dutch character set + * ESC (4 + * Reference: http://vt100.net/docs/vt220-rm/table2-6.html + */ +CHARSETS['4'] = { + '#': '£', + '@': '¾', + '[': 'ij', + '\\': '½', + ']': '|', + '{': '¨', + '|': 'f', + '}': '¼', + '~': '´' +}; + +/** + * Finnish character set + * ESC (C or ESC (5 + * Reference: http://vt100.net/docs/vt220-rm/table2-7.html + */ +CHARSETS['C'] = +CHARSETS['5'] = { + '[': 'Ä', + '\\': 'Ö', + ']': 'Å', + '^': 'Ü', + '`': 'é', + '{': 'ä', + '|': 'ö', + '}': 'å', + '~': 'ü' +}; + +/** + * French character set + * ESC (R + * Reference: http://vt100.net/docs/vt220-rm/table2-8.html + */ +CHARSETS['R'] = { + '#': '£', + '@': 'à', + '[': '°', + '\\': 'ç', + ']': '§', + '{': 'é', + '|': 'ù', + '}': 'è', + '~': '¨' +}; + +/** + * French Canadian character set + * ESC (Q + * Reference: http://vt100.net/docs/vt220-rm/table2-9.html + */ +CHARSETS['Q'] = { + '@': 'à', + '[': 'â', + '\\': 'ç', + ']': 'ê', + '^': 'î', + '`': 'ô', + '{': 'é', + '|': 'ù', + '}': 'è', + '~': 'û' +}; + +/** + * German character set + * ESC (K + * Reference: http://vt100.net/docs/vt220-rm/table2-10.html + */ +CHARSETS['K'] = { + '@': '§', + '[': 'Ä', + '\\': 'Ö', + ']': 'Ü', + '{': 'ä', + '|': 'ö', + '}': 'ü', + '~': 'ß' +}; + +/** + * Italian character set + * ESC (Y + * Reference: http://vt100.net/docs/vt220-rm/table2-11.html + */ +CHARSETS['Y'] = { + '#': '£', + '@': '§', + '[': '°', + '\\': 'ç', + ']': 'é', + '`': 'ù', + '{': 'à', + '|': 'ò', + '}': 'è', + '~': 'ì' +}; + +/** + * Norwegian/Danish character set + * ESC (E or ESC (6 + * Reference: http://vt100.net/docs/vt220-rm/table2-12.html + */ +CHARSETS['E'] = +CHARSETS['6'] = { + '@': 'Ä', + '[': 'Æ', + '\\': 'Ø', + ']': 'Å', + '^': 'Ü', + '`': 'ä', + '{': 'æ', + '|': 'ø', + '}': 'å', + '~': 'ü' +}; + +/** + * Spanish character set + * ESC (Z + * Reference: http://vt100.net/docs/vt220-rm/table2-13.html + */ +CHARSETS['Z'] = { + '#': '£', + '@': '§', + '[': '¡', + '\\': 'Ñ', + ']': '¿', + '{': '°', + '|': 'ñ', + '}': 'ç' +}; + +/** + * Swedish character set + * ESC (H or ESC (7 + * Reference: http://vt100.net/docs/vt220-rm/table2-14.html + */ +CHARSETS['H'] = +CHARSETS['7'] = { + '@': 'É', + '[': 'Ä', + '\\': 'Ö', + ']': 'Å', + '^': 'Ü', + '`': 'é', + '{': 'ä', + '|': 'ö', + '}': 'å', + '~': 'ü' +}; + +/** + * Swiss character set + * ESC (= + * Reference: http://vt100.net/docs/vt220-rm/table2-15.html + */ +CHARSETS['='] = { + '#': 'ù', + '@': 'à', + '[': 'é', + '\\': 'ç', + ']': 'ê', + '^': 'î', + // eslint-disable-next-line @typescript-eslint/naming-convention + '_': 'è', + '`': 'ô', + '{': 'ä', + '|': 'ö', + '}': 'ü', + '~': 'û' +}; diff --git a/node_modules/xterm/src/common/data/EscapeSequences.ts b/node_modules/xterm/src/common/data/EscapeSequences.ts new file mode 100644 index 0000000..e35f01d --- /dev/null +++ b/node_modules/xterm/src/common/data/EscapeSequences.ts @@ -0,0 +1,150 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/** + * C0 control codes + * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes + */ +export namespace C0 { + /** Null (Caret = ^@, C = \0) */ + export const NUL = '\x00'; + /** Start of Heading (Caret = ^A) */ + export const SOH = '\x01'; + /** Start of Text (Caret = ^B) */ + export const STX = '\x02'; + /** End of Text (Caret = ^C) */ + export const ETX = '\x03'; + /** End of Transmission (Caret = ^D) */ + export const EOT = '\x04'; + /** Enquiry (Caret = ^E) */ + export const ENQ = '\x05'; + /** Acknowledge (Caret = ^F) */ + export const ACK = '\x06'; + /** Bell (Caret = ^G, C = \a) */ + export const BEL = '\x07'; + /** Backspace (Caret = ^H, C = \b) */ + export const BS = '\x08'; + /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \t) */ + export const HT = '\x09'; + /** Line Feed (Caret = ^J, C = \n) */ + export const LF = '\x0a'; + /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \v) */ + export const VT = '\x0b'; + /** Form Feed (Caret = ^L, C = \f) */ + export const FF = '\x0c'; + /** Carriage Return (Caret = ^M, C = \r) */ + export const CR = '\x0d'; + /** Shift Out (Caret = ^N) */ + export const SO = '\x0e'; + /** Shift In (Caret = ^O) */ + export const SI = '\x0f'; + /** Data Link Escape (Caret = ^P) */ + export const DLE = '\x10'; + /** Device Control One (XON) (Caret = ^Q) */ + export const DC1 = '\x11'; + /** Device Control Two (Caret = ^R) */ + export const DC2 = '\x12'; + /** Device Control Three (XOFF) (Caret = ^S) */ + export const DC3 = '\x13'; + /** Device Control Four (Caret = ^T) */ + export const DC4 = '\x14'; + /** Negative Acknowledge (Caret = ^U) */ + export const NAK = '\x15'; + /** Synchronous Idle (Caret = ^V) */ + export const SYN = '\x16'; + /** End of Transmission Block (Caret = ^W) */ + export const ETB = '\x17'; + /** Cancel (Caret = ^X) */ + export const CAN = '\x18'; + /** End of Medium (Caret = ^Y) */ + export const EM = '\x19'; + /** Substitute (Caret = ^Z) */ + export const SUB = '\x1a'; + /** Escape (Caret = ^[, C = \e) */ + export const ESC = '\x1b'; + /** File Separator (Caret = ^\) */ + export const FS = '\x1c'; + /** Group Separator (Caret = ^]) */ + export const GS = '\x1d'; + /** Record Separator (Caret = ^^) */ + export const RS = '\x1e'; + /** Unit Separator (Caret = ^_) */ + export const US = '\x1f'; + /** Space */ + export const SP = '\x20'; + /** Delete (Caret = ^?) */ + export const DEL = '\x7f'; +} + +/** + * C1 control codes + * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes + */ +export namespace C1 { + /** padding character */ + export const PAD = '\x80'; + /** High Octet Preset */ + export const HOP = '\x81'; + /** Break Permitted Here */ + export const BPH = '\x82'; + /** No Break Here */ + export const NBH = '\x83'; + /** Index */ + export const IND = '\x84'; + /** Next Line */ + export const NEL = '\x85'; + /** Start of Selected Area */ + export const SSA = '\x86'; + /** End of Selected Area */ + export const ESA = '\x87'; + /** Horizontal Tabulation Set */ + export const HTS = '\x88'; + /** Horizontal Tabulation With Justification */ + export const HTJ = '\x89'; + /** Vertical Tabulation Set */ + export const VTS = '\x8a'; + /** Partial Line Down */ + export const PLD = '\x8b'; + /** Partial Line Up */ + export const PLU = '\x8c'; + /** Reverse Index */ + export const RI = '\x8d'; + /** Single-Shift 2 */ + export const SS2 = '\x8e'; + /** Single-Shift 3 */ + export const SS3 = '\x8f'; + /** Device Control String */ + export const DCS = '\x90'; + /** Private Use 1 */ + export const PU1 = '\x91'; + /** Private Use 2 */ + export const PU2 = '\x92'; + /** Set Transmit State */ + export const STS = '\x93'; + /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */ + export const CCH = '\x94'; + /** Message Waiting */ + export const MW = '\x95'; + /** Start of Protected Area */ + export const SPA = '\x96'; + /** End of Protected Area */ + export const EPA = '\x97'; + /** Start of String */ + export const SOS = '\x98'; + /** Single Graphic Character Introducer */ + export const SGCI = '\x99'; + /** Single Character Introducer */ + export const SCI = '\x9a'; + /** Control Sequence Introducer */ + export const CSI = '\x9b'; + /** String Terminator */ + export const ST = '\x9c'; + /** Operating System Command */ + export const OSC = '\x9d'; + /** Privacy Message */ + export const PM = '\x9e'; + /** Application Program Command */ + export const APC = '\x9f'; +} diff --git a/node_modules/xterm/src/common/input/Keyboard.ts b/node_modules/xterm/src/common/input/Keyboard.ts new file mode 100644 index 0000000..b4b3dce --- /dev/null +++ b/node_modules/xterm/src/common/input/Keyboard.ts @@ -0,0 +1,375 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + */ + +import { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types'; +import { C0 } from 'common/data/EscapeSequences'; + +// reg + shift key mappings for digits and special chars +const KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = { + // digits 0-9 + 48: ['0', ')'], + 49: ['1', '!'], + 50: ['2', '@'], + 51: ['3', '#'], + 52: ['4', '$'], + 53: ['5', '%'], + 54: ['6', '^'], + 55: ['7', '&'], + 56: ['8', '*'], + 57: ['9', '('], + + // special chars + 186: [';', ':'], + 187: ['=', '+'], + 188: [',', '<'], + 189: ['-', '_'], + 190: ['.', '>'], + 191: ['/', '?'], + 192: ['`', '~'], + 219: ['[', '{'], + 220: ['\\', '|'], + 221: [']', '}'], + 222: ['\'', '"'] +}; + +export function evaluateKeyboardEvent( + ev: IKeyboardEvent, + applicationCursorMode: boolean, + isMac: boolean, + macOptionIsMeta: boolean +): IKeyboardResult { + const result: IKeyboardResult = { + type: KeyboardResultType.SEND_KEY, + // Whether to cancel event propagation (NOTE: this may not be needed since the event is + // canceled at the end of keyDown + cancel: false, + // The new key even to emit + key: undefined + }; + const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0); + switch (ev.keyCode) { + case 0: + if (ev.key === 'UIKeyInputUpArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OA'; + } else { + result.key = C0.ESC + '[A'; + } + } + else if (ev.key === 'UIKeyInputLeftArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OD'; + } else { + result.key = C0.ESC + '[D'; + } + } + else if (ev.key === 'UIKeyInputRightArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OC'; + } else { + result.key = C0.ESC + '[C'; + } + } + else if (ev.key === 'UIKeyInputDownArrow') { + if (applicationCursorMode) { + result.key = C0.ESC + 'OB'; + } else { + result.key = C0.ESC + '[B'; + } + } + break; + case 8: + // backspace + if (ev.shiftKey) { + result.key = C0.BS; // ^H + break; + } else if (ev.altKey) { + result.key = C0.ESC + C0.DEL; // \e ^? + break; + } + result.key = C0.DEL; // ^? + break; + case 9: + // tab + if (ev.shiftKey) { + result.key = C0.ESC + '[Z'; + break; + } + result.key = C0.HT; + result.cancel = true; + break; + case 13: + // return/enter + result.key = ev.altKey ? C0.ESC + C0.CR : C0.CR; + result.cancel = true; + break; + case 27: + // escape + result.key = C0.ESC; + if (ev.altKey) { + result.key = C0.ESC + C0.ESC; + } + result.cancel = true; + break; + case 37: + // left-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D'; + // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards + // http://unix.stackexchange.com/a/108106 + // macOS uses different escape sequences than linux + if (result.key === C0.ESC + '[1;3D') { + result.key = C0.ESC + (isMac ? 'b' : '[1;5D'); + } + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OD'; + } else { + result.key = C0.ESC + '[D'; + } + break; + case 39: + // right-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C'; + // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward + // http://unix.stackexchange.com/a/108106 + // macOS uses different escape sequences than linux + if (result.key === C0.ESC + '[1;3C') { + result.key = C0.ESC + (isMac ? 'f' : '[1;5C'); + } + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OC'; + } else { + result.key = C0.ESC + '[C'; + } + break; + case 38: + // up-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A'; + // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow + // http://unix.stackexchange.com/a/108106 + // macOS uses different escape sequences than linux + if (!isMac && result.key === C0.ESC + '[1;3A') { + result.key = C0.ESC + '[1;5A'; + } + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OA'; + } else { + result.key = C0.ESC + '[A'; + } + break; + case 40: + // down-arrow + if (ev.metaKey) { + break; + } + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B'; + // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow + // http://unix.stackexchange.com/a/108106 + // macOS uses different escape sequences than linux + if (!isMac && result.key === C0.ESC + '[1;3B') { + result.key = C0.ESC + '[1;5B'; + } + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OB'; + } else { + result.key = C0.ESC + '[B'; + } + break; + case 45: + // insert + if (!ev.shiftKey && !ev.ctrlKey) { + // <Ctrl> or <Shift> + <Insert> are used to + // copy-paste on some systems. + result.key = C0.ESC + '[2~'; + } + break; + case 46: + // delete + if (modifiers) { + result.key = C0.ESC + '[3;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[3~'; + } + break; + case 36: + // home + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OH'; + } else { + result.key = C0.ESC + '[H'; + } + break; + case 35: + // end + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F'; + } else if (applicationCursorMode) { + result.key = C0.ESC + 'OF'; + } else { + result.key = C0.ESC + '[F'; + } + break; + case 33: + // page up + if (ev.shiftKey) { + result.type = KeyboardResultType.PAGE_UP; + } else { + result.key = C0.ESC + '[5~'; + } + break; + case 34: + // page down + if (ev.shiftKey) { + result.type = KeyboardResultType.PAGE_DOWN; + } else { + result.key = C0.ESC + '[6~'; + } + break; + case 112: + // F1-F12 + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P'; + } else { + result.key = C0.ESC + 'OP'; + } + break; + case 113: + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q'; + } else { + result.key = C0.ESC + 'OQ'; + } + break; + case 114: + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R'; + } else { + result.key = C0.ESC + 'OR'; + } + break; + case 115: + if (modifiers) { + result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S'; + } else { + result.key = C0.ESC + 'OS'; + } + break; + case 116: + if (modifiers) { + result.key = C0.ESC + '[15;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[15~'; + } + break; + case 117: + if (modifiers) { + result.key = C0.ESC + '[17;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[17~'; + } + break; + case 118: + if (modifiers) { + result.key = C0.ESC + '[18;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[18~'; + } + break; + case 119: + if (modifiers) { + result.key = C0.ESC + '[19;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[19~'; + } + break; + case 120: + if (modifiers) { + result.key = C0.ESC + '[20;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[20~'; + } + break; + case 121: + if (modifiers) { + result.key = C0.ESC + '[21;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[21~'; + } + break; + case 122: + if (modifiers) { + result.key = C0.ESC + '[23;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[23~'; + } + break; + case 123: + if (modifiers) { + result.key = C0.ESC + '[24;' + (modifiers + 1) + '~'; + } else { + result.key = C0.ESC + '[24~'; + } + break; + default: + // a-z and space + if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) { + if (ev.keyCode >= 65 && ev.keyCode <= 90) { + result.key = String.fromCharCode(ev.keyCode - 64); + } else if (ev.keyCode === 32) { + result.key = C0.NUL; + } else if (ev.keyCode >= 51 && ev.keyCode <= 55) { + // escape, file sep, group sep, record sep, unit sep + result.key = String.fromCharCode(ev.keyCode - 51 + 27); + } else if (ev.keyCode === 56) { + result.key = C0.DEL; + } else if (ev.keyCode === 219) { + result.key = C0.ESC; + } else if (ev.keyCode === 220) { + result.key = C0.FS; + } else if (ev.keyCode === 221) { + result.key = C0.GS; + } + } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) { + // On macOS this is a third level shift when !macOptionIsMeta. Use <Esc> instead. + const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode]; + const key = keyMapping?.[!ev.shiftKey ? 0 : 1]; + if (key) { + result.key = C0.ESC + key; + } else if (ev.keyCode >= 65 && ev.keyCode <= 90) { + const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32; + result.key = C0.ESC + String.fromCharCode(keyCode); + } + } else if (isMac && !ev.altKey && !ev.ctrlKey && !ev.shiftKey && ev.metaKey) { + if (ev.keyCode === 65) { // cmd + a + result.type = KeyboardResultType.SELECT_ALL; + } + } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) { + // Include only keys that that result in a _single_ character; don't include num lock, volume up, etc. + result.key = ev.key; + } else if (ev.key && ev.ctrlKey) { + if (ev.key === '_') { // ^_ + result.key = C0.US; + } + } + break; + } + + return result; +} diff --git a/node_modules/xterm/src/common/input/TextDecoder.ts b/node_modules/xterm/src/common/input/TextDecoder.ts new file mode 100644 index 0000000..715e919 --- /dev/null +++ b/node_modules/xterm/src/common/input/TextDecoder.ts @@ -0,0 +1,346 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/** + * Polyfill - Convert UTF32 codepoint into JS string. + * Note: The built-in String.fromCodePoint happens to be much slower + * due to additional sanity checks. We can avoid them since + * we always operate on legal UTF32 (granted by the input decoders) + * and use this faster version instead. + */ +export function stringFromCodePoint(codePoint: number): string { + if (codePoint > 0xFFFF) { + codePoint -= 0x10000; + return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00); + } + return String.fromCharCode(codePoint); +} + +/** + * Convert UTF32 char codes into JS string. + * Basically the same as `stringFromCodePoint` but for multiple codepoints + * in a loop (which is a lot faster). + */ +export function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string { + let result = ''; + for (let i = start; i < end; ++i) { + let codepoint = data[i]; + if (codepoint > 0xFFFF) { + // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate pair + // conversion rules: + // - subtract 0x10000 from code point, leaving a 20 bit number + // - add high 10 bits to 0xD800 --> first surrogate + // - add low 10 bits to 0xDC00 --> second surrogate + codepoint -= 0x10000; + result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00); + } else { + result += String.fromCharCode(codepoint); + } + } + return result; +} + +/** + * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints. + * To keep the decoder in line with JS strings it handles single surrogates as UCS2. + */ +export class StringToUtf32 { + private _interim: number = 0; + + /** + * Clears interim and resets decoder to clean state. + */ + public clear(): void { + this._interim = 0; + } + + /** + * Decode JS string to UTF32 codepoints. + * The methods assumes stream input and will store partly transmitted + * surrogate pairs and decode them with the next data chunk. + * Note: The method does no bound checks for target, therefore make sure + * the provided input data does not exceed the size of `target`. + * Returns the number of written codepoints in `target`. + */ + public decode(input: string, target: Uint32Array): number { + const length = input.length; + + if (!length) { + return 0; + } + + let size = 0; + let startPos = 0; + + // handle leftover surrogate high + if (this._interim) { + const second = input.charCodeAt(startPos++); + if (0xDC00 <= second && second <= 0xDFFF) { + target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } else { + // illegal codepoint (USC2 handling) + target[size++] = this._interim; + target[size++] = second; + } + this._interim = 0; + } + + for (let i = startPos; i < length; ++i) { + const code = input.charCodeAt(i); + // surrogate pair first + if (0xD800 <= code && code <= 0xDBFF) { + if (++i >= length) { + this._interim = code; + return size; + } + const second = input.charCodeAt(i); + if (0xDC00 <= second && second <= 0xDFFF) { + target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } else { + // illegal codepoint (USC2 handling) + target[size++] = code; + target[size++] = second; + } + continue; + } + if (code === 0xFEFF) { + // BOM + continue; + } + target[size++] = code; + } + return size; + } +} + +/** + * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints. + */ +export class Utf8ToUtf32 { + public interim: Uint8Array = new Uint8Array(3); + + /** + * Clears interim bytes and resets decoder to clean state. + */ + public clear(): void { + this.interim.fill(0); + } + + /** + * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`. + * The methods assumes stream input and will store partly transmitted bytes + * and decode them with the next data chunk. + * Note: The method does no bound checks for target, therefore make sure + * the provided data chunk does not exceed the size of `target`. + * Returns the number of written codepoints in `target`. + */ + public decode(input: Uint8Array, target: Uint32Array): number { + const length = input.length; + + if (!length) { + return 0; + } + + let size = 0; + let byte1: number; + let byte2: number; + let byte3: number; + let byte4: number; + let codepoint = 0; + let startPos = 0; + + // handle leftover bytes + if (this.interim[0]) { + let discardInterim = false; + let cp = this.interim[0]; + cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07); + let pos = 0; + let tmp: number; + while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) { + cp <<= 6; + cp |= tmp; + } + // missing bytes - read ahead from input + const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4; + const missing = type - pos; + while (startPos < missing) { + if (startPos >= length) { + return 0; + } + tmp = input[startPos++]; + if ((tmp & 0xC0) !== 0x80) { + // wrong continuation, discard interim bytes completely + startPos--; + discardInterim = true; + break; + } else { + // need to save so we can continue short inputs in next call + this.interim[pos++] = tmp; + cp <<= 6; + cp |= tmp & 0x3F; + } + } + if (!discardInterim) { + // final test is type dependent + if (type === 2) { + if (cp < 0x80) { + // wrong starter byte + startPos--; + } else { + target[size++] = cp; + } + } else if (type === 3) { + if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF) || cp === 0xFEFF) { + // illegal codepoint or BOM + } else { + target[size++] = cp; + } + } else { + if (cp < 0x010000 || cp > 0x10FFFF) { + // illegal codepoint + } else { + target[size++] = cp; + } + } + } + this.interim.fill(0); + } + + // loop through input + const fourStop = length - 4; + let i = startPos; + while (i < length) { + /** + * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars. + * This is a compromise between speed gain for ASCII + * and penalty for non ASCII: + * For best ASCII performance the char should be stored directly into target, + * but even a single attempt to write to target and compare afterwards + * penalizes non ASCII really bad (-50%), thus we load the char into byteX first, + * which reduces ASCII performance by ~15%. + * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible + * compared to the gains. + * Note that this optimization only takes place for 4 consecutive ASCII chars, + * for any shorter it bails out. Worst case - all 4 bytes being read but + * thrown away due to the last being a non ASCII char (-10% performance). + */ + while (i < fourStop + && !((byte1 = input[i]) & 0x80) + && !((byte2 = input[i + 1]) & 0x80) + && !((byte3 = input[i + 2]) & 0x80) + && !((byte4 = input[i + 3]) & 0x80)) + { + target[size++] = byte1; + target[size++] = byte2; + target[size++] = byte3; + target[size++] = byte4; + i += 4; + } + + // reread byte1 + byte1 = input[i++]; + + // 1 byte + if (byte1 < 0x80) { + target[size++] = byte1; + + // 2 bytes + } else if ((byte1 & 0xE0) === 0xC0) { + if (i >= length) { + this.interim[0] = byte1; + return size; + } + byte2 = input[i++]; + if ((byte2 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F); + if (codepoint < 0x80) { + // wrong starter byte + i--; + continue; + } + target[size++] = codepoint; + + // 3 bytes + } else if ((byte1 & 0xF0) === 0xE0) { + if (i >= length) { + this.interim[0] = byte1; + return size; + } + byte2 = input[i++]; + if ((byte2 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + if (i >= length) { + this.interim[0] = byte1; + this.interim[1] = byte2; + return size; + } + byte3 = input[i++]; + if ((byte3 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F); + if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint === 0xFEFF) { + // illegal codepoint or BOM, no i-- here + continue; + } + target[size++] = codepoint; + + // 4 bytes + } else if ((byte1 & 0xF8) === 0xF0) { + if (i >= length) { + this.interim[0] = byte1; + return size; + } + byte2 = input[i++]; + if ((byte2 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + if (i >= length) { + this.interim[0] = byte1; + this.interim[1] = byte2; + return size; + } + byte3 = input[i++]; + if ((byte3 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + if (i >= length) { + this.interim[0] = byte1; + this.interim[1] = byte2; + this.interim[2] = byte3; + return size; + } + byte4 = input[i++]; + if ((byte4 & 0xC0) !== 0x80) { + // wrong continuation + i--; + continue; + } + codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F); + if (codepoint < 0x010000 || codepoint > 0x10FFFF) { + // illegal codepoint, no i-- here + continue; + } + target[size++] = codepoint; + } else { + // illegal byte, just skip + } + } + return size; + } +} diff --git a/node_modules/xterm/src/common/input/UnicodeV6.ts b/node_modules/xterm/src/common/input/UnicodeV6.ts new file mode 100644 index 0000000..b308203 --- /dev/null +++ b/node_modules/xterm/src/common/input/UnicodeV6.ts @@ -0,0 +1,133 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IUnicodeVersionProvider } from 'common/services/Services'; +import { fill } from 'common/TypedArrayUtils'; + +type CharWidth = 0 | 1 | 2; + +const BMP_COMBINING = [ + [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489], + [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2], + [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603], + [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670], + [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED], + [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A], + [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902], + [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D], + [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981], + [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD], + [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C], + [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D], + [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC], + [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD], + [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C], + [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D], + [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0], + [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48], + [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC], + [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD], + [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D], + [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6], + [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E], + [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC], + [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35], + [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E], + [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97], + [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030], + [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039], + [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F], + [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753], + [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD], + [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD], + [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922], + [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B], + [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34], + [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42], + [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF], + [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063], + [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F], + [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B], + [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F], + [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB] +]; +const HIGH_COMBINING = [ + [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F], + [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169], + [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD], + [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F], + [0xE0100, 0xE01EF] +]; + +// BMP lookup table, lazy initialized during first addon loading +let table: Uint8Array; + +function bisearch(ucs: number, data: number[][]): boolean { + let min = 0; + let max = data.length - 1; + let mid; + if (ucs < data[0][0] || ucs > data[max][1]) { + return false; + } + while (max >= min) { + mid = (min + max) >> 1; + if (ucs > data[mid][1]) { + min = mid + 1; + } else if (ucs < data[mid][0]) { + max = mid - 1; + } else { + return true; + } + } + return false; +} + +export class UnicodeV6 implements IUnicodeVersionProvider { + public readonly version = '6'; + + constructor() { + // init lookup table once + if (!table) { + table = new Uint8Array(65536); + fill(table, 1); + table[0] = 0; + // control chars + fill(table, 0, 1, 32); + fill(table, 0, 0x7f, 0xa0); + + // apply wide char rules first + // wide chars + fill(table, 2, 0x1100, 0x1160); + table[0x2329] = 2; + table[0x232a] = 2; + fill(table, 2, 0x2e80, 0xa4d0); + table[0x303f] = 1; // wrongly in last line + + fill(table, 2, 0xac00, 0xd7a4); + fill(table, 2, 0xf900, 0xfb00); + fill(table, 2, 0xfe10, 0xfe1a); + fill(table, 2, 0xfe30, 0xfe70); + fill(table, 2, 0xff00, 0xff61); + fill(table, 2, 0xffe0, 0xffe7); + + // apply combining last to ensure we overwrite + // wrongly wide set chars: + // the original algo evals combining first and falls + // through to wide check so we simply do here the opposite + // combining 0 + for (let r = 0; r < BMP_COMBINING.length; ++r) { + fill(table, 0, BMP_COMBINING[r][0], BMP_COMBINING[r][1] + 1); + } + } + } + + public wcwidth(num: number): CharWidth { + if (num < 32) return 0; + if (num < 127) return 1; + if (num < 65536) return table[num] as CharWidth; + if (bisearch(num, HIGH_COMBINING)) return 0; + if ((num >= 0x20000 && num <= 0x2fffd) || (num >= 0x30000 && num <= 0x3fffd)) return 2; + return 1; + } +} diff --git a/node_modules/xterm/src/common/input/WriteBuffer.ts b/node_modules/xterm/src/common/input/WriteBuffer.ts new file mode 100644 index 0000000..cc84c9a --- /dev/null +++ b/node_modules/xterm/src/common/input/WriteBuffer.ts @@ -0,0 +1,224 @@ + +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +declare const setTimeout: (handler: () => void, timeout?: number) => void; + +/** + * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input. + * Enable flow control to avoid this limit and make sure that your backend correctly + * propagates this to the underlying pty. (see docs for further instructions) + * Since this limit is meant as a safety parachute to prevent browser crashs, + * it is set to a very high number. Typically xterm.js gets unresponsive with + * a 100 times lower number (>500 kB). + */ +const DISCARD_WATERMARK = 50000000; // ~50 MB + +/** + * The max number of ms to spend on writes before allowing the renderer to + * catch up with a 0ms setTimeout. A value of < 33 to keep us close to + * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS + * depends on the time it takes for the renderer to draw the frame. + */ +const WRITE_TIMEOUT_MS = 12; + +/** + * Threshold of max held chunks in the write buffer, that were already processed. + * This is a tradeoff between extensive write buffer shifts (bad runtime) and high + * memory consumption by data thats not used anymore. + */ +const WRITE_BUFFER_LENGTH_THRESHOLD = 50; + +// queueMicrotask polyfill for nodejs < v11 +const qmt: (cb: () => void) => void = (typeof queueMicrotask === 'undefined') + ? (cb: () => void) => { Promise.resolve().then(cb); } + : queueMicrotask; + + +export class WriteBuffer { + private _writeBuffer: (string | Uint8Array)[] = []; + private _callbacks: ((() => void) | undefined)[] = []; + private _pendingData = 0; + private _bufferOffset = 0; + private _isSyncWriting = false; + private _syncCalls = 0; + + constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise<boolean>) { } + + /** + * @deprecated Unreliable, to be removed soon. + */ + public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void { + // stop writeSync recursions with maxSubsequentCalls argument + // This is dangerous to use as it will lose the current data chunk + // and return immediately. + if (maxSubsequentCalls !== undefined && this._syncCalls > maxSubsequentCalls) { + // comment next line if a whole loop block should only contain x `writeSync` calls + // (total flat vs. deep nested limit) + this._syncCalls = 0; + return; + } + // append chunk to buffer + this._pendingData += data.length; + this._writeBuffer.push(data); + this._callbacks.push(undefined); + + // increase recursion counter + this._syncCalls++; + // exit early if another writeSync loop is active + if (this._isSyncWriting) { + return; + } + this._isSyncWriting = true; + + // force sync processing on pending data chunks to avoid in-band data scrambling + // does the same as innerWrite but without event loop + // 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(); + } + // 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 { + if (this._pendingData > DISCARD_WATERMARK) { + throw new Error('write data discarded, use flow control to avoid losing data'); + } + + // schedule chunk processing for next event loop run + if (!this._writeBuffer.length) { + this._bufferOffset = 0; + setTimeout(() => this._innerWrite()); + } + + this._pendingData += data.length; + this._writeBuffer.push(data); + this._callbacks.push(callback); + } + + /** + * Inner write call, that enters the sliced chunk processing by timing. + * + * `lastTime` indicates, when the last _innerWrite call had started. + * It is used to aggregate async handler execution under a timeout constraint + * effectively lowering the redrawing needs, schematically: + * + * macroTask _innerWrite: + * if (Date.now() - (lastTime | 0) < WRITE_TIMEOUT_MS): + * schedule microTask _innerWrite(lastTime) + * else: + * schedule macroTask _innerWrite(0) + * + * overall execution order on task queues: + * + * macrotasks: [...] --> _innerWrite(0) --> [...] --> screenUpdate --> [...] + * m t: | + * i a: [...] + * c s: | + * r k: while < timeout: + * o s: _innerWrite(timeout) + * + * `promiseResult` depicts the promise resolve value of an async handler. + * This value gets carried forward through all saved stack states of the + * paused parser for proper continuation. + * + * Note, for pure sync code `lastTime` and `promiseResult` have no meaning. + */ + protected _innerWrite(lastTime: number = 0, promiseResult: boolean = true): void { + const startTime = lastTime || Date.now(); + while (this._writeBuffer.length > this._bufferOffset) { + const data = this._writeBuffer[this._bufferOffset]; + const result = this._action(data, promiseResult); + if (result) { + /** + * If we get a promise as return value, we re-schedule the continuation + * as thenable on the promise and exit right away. + * + * The exit here means, that we block input processing at the current active chunk, + * the exact execution position within the chunk is preserved by the saved + * stack content in InputHandler and EscapeSequenceParser. + * + * Resuming happens automatically from that saved stack state. + * Also the resolved promise value is passed along the callstack to + * `EscapeSequenceParser.parse` to correctly resume the stopped handler loop. + * + * Exceptions on async handlers will be logged to console async, but do not interrupt + * the input processing (continues with next handler at the current input position). + */ + + /** + * If a promise takes long to resolve, we should schedule continuation behind setTimeout. + * This might already be too late, if our .then enters really late (executor + prev thens took very long). + * This cannot be solved here for the handler itself (it is the handlers responsibility to slice hard work), + * but we can at least schedule a screen update as we gain control. + */ + const continuation: (r: boolean) => void = (r: boolean) => Date.now() - startTime >= WRITE_TIMEOUT_MS + ? setTimeout(() => this._innerWrite(0, r)) + : this._innerWrite(startTime, r); + + /** + * Optimization considerations: + * The continuation above favors FPS over throughput by eval'ing `startTime` on resolve. + * This might schedule too many screen updates with bad throughput drops (in case a slow + * resolving handler sliced its work properly behind setTimeout calls). We cannot spot + * this condition here, also the renderer has no way to spot nonsense updates either. + * FIXME: A proper fix for this would track the FPS at the renderer entry level separately. + * + * If favoring of FPS shows bad throughtput impact, use the following instead. It favors + * throughput by eval'ing `startTime` upfront pulling at least one more chunk into the + * current microtask queue (executed before setTimeout). + */ + // const continuation: (r: boolean) => void = Date.now() - startTime >= WRITE_TIMEOUT_MS + // ? r => setTimeout(() => this._innerWrite(0, r)) + // : r => this._innerWrite(startTime, r); + + // Handle exceptions synchronously to current band position, idea: + // 1. spawn a single microtask which we allow to throw hard + // 2. spawn a promise immediately resolving to `true` + // (executed on the same queue, thus properly aligned before continuation happens) + result.catch(err => { + qmt(() => {throw err;}); + return Promise.resolve(false); + }).then(continuation); + return; + } + + const cb = this._callbacks[this._bufferOffset]; + if (cb) cb(); + this._bufferOffset++; + this._pendingData -= data.length; + + if (Date.now() - startTime >= WRITE_TIMEOUT_MS) { + break; + } + } + if (this._writeBuffer.length > this._bufferOffset) { + // Allow renderer to catch up before processing the next batch + // trim already processed chunks if we are above threshold + if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) { + this._writeBuffer = this._writeBuffer.slice(this._bufferOffset); + this._callbacks = this._callbacks.slice(this._bufferOffset); + this._bufferOffset = 0; + } + setTimeout(() => this._innerWrite()); + } else { + this._writeBuffer.length = 0; + this._callbacks.length = 0; + this._pendingData = 0; + this._bufferOffset = 0; + } + } +} diff --git a/node_modules/xterm/src/common/input/XParseColor.ts b/node_modules/xterm/src/common/input/XParseColor.ts new file mode 100644 index 0000000..8c023a3 --- /dev/null +++ b/node_modules/xterm/src/common/input/XParseColor.ts @@ -0,0 +1,80 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + + +// 'rgb:' rule - matching: r/g/b | rr/gg/bb | rrr/ggg/bbb | rrrr/gggg/bbbb (hex digits) +const RGB_REX = /^([\da-f]{1})\/([\da-f]{1})\/([\da-f]{1})$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/; +// '#...' rule - matching any hex digits +const HASH_REX = /^[\da-f]+$/; + +/** + * Parse color spec to RGB values (8 bit per channel). + * See `man xparsecolor` for details about certain format specifications. + * + * Supported formats: + * - rgb:<red>/<green>/<blue> with <red>, <green>, <blue> in h | hh | hhh | hhhh + * - #RGB, #RRGGBB, #RRRGGGBBB, #RRRRGGGGBBBB + * + * All other formats like rgbi: or device-independent string specifications + * with float numbering are not supported. + */ +export function parseColor(data: string): [number, number, number] | undefined { + if (!data) return; + // also handle uppercases + let low = data.toLowerCase(); + if (low.indexOf('rgb:') === 0) { + // 'rgb:' specifier + low = low.slice(4); + const m = RGB_REX.exec(low); + if (m) { + const base = m[1] ? 15 : m[4] ? 255 : m[7] ? 4095 : 65535; + return [ + Math.round(parseInt(m[1] || m[4] || m[7] || m[10], 16) / base * 255), + Math.round(parseInt(m[2] || m[5] || m[8] || m[11], 16) / base * 255), + Math.round(parseInt(m[3] || m[6] || m[9] || m[12], 16) / base * 255) + ]; + } + } else if (low.indexOf('#') === 0) { + // '#' specifier + low = low.slice(1); + if (HASH_REX.exec(low) && [3, 6, 9, 12].includes(low.length)) { + const adv = low.length / 3; + const result: [number, number, number] = [0, 0, 0]; + for (let i = 0; i < 3; ++i) { + const c = parseInt(low.slice(adv * i, adv * i + adv), 16); + result[i] = adv === 1 ? c << 4 : adv === 2 ? c : adv === 3 ? c >> 4 : c >> 8; + } + return result; + } + } + + // Named colors are currently not supported due to the large addition to the xterm.js bundle size + // they would add. In order to support named colors, we would need some way of optionally loading + // additional payloads so startup/download time is not bloated (see #3530). +} + +// pad hex output to requested bit width +function pad(n: number, bits: number): string { + const s = n.toString(16); + const s2 = s.length < 2 ? '0' + s : s; + switch (bits) { + case 4: + return s[0]; + case 8: + return s2; + case 12: + return (s2 + s2).slice(0, 3); + default: + return s2 + s2; + } +} + +/** + * Convert a given color to rgb:../../.. string of `bits` depth. + */ +export function toRgbString(color: [number, number, number], bits: number = 16): string { + const [r, g, b] = color; + return `rgb:${pad(r, bits)}/${pad(g, bits)}/${pad(b, bits)}`; +} diff --git a/node_modules/xterm/src/common/parser/Constants.ts b/node_modules/xterm/src/common/parser/Constants.ts new file mode 100644 index 0000000..85156c3 --- /dev/null +++ b/node_modules/xterm/src/common/parser/Constants.ts @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +/** + * Internal states of EscapeSequenceParser. + */ +export const enum ParserState { + GROUND = 0, + ESCAPE = 1, + ESCAPE_INTERMEDIATE = 2, + CSI_ENTRY = 3, + CSI_PARAM = 4, + CSI_INTERMEDIATE = 5, + CSI_IGNORE = 6, + SOS_PM_APC_STRING = 7, + OSC_STRING = 8, + DCS_ENTRY = 9, + DCS_PARAM = 10, + DCS_IGNORE = 11, + DCS_INTERMEDIATE = 12, + DCS_PASSTHROUGH = 13 +} + +/** +* Internal actions of EscapeSequenceParser. +*/ +export const enum ParserAction { + IGNORE = 0, + ERROR = 1, + PRINT = 2, + EXECUTE = 3, + OSC_START = 4, + OSC_PUT = 5, + OSC_END = 6, + CSI_DISPATCH = 7, + PARAM = 8, + COLLECT = 9, + ESC_DISPATCH = 10, + CLEAR = 11, + DCS_HOOK = 12, + DCS_PUT = 13, + DCS_UNHOOK = 14 +} + +/** + * Internal states of OscParser. + */ +export const enum OscState { + START = 0, + ID = 1, + PAYLOAD = 2, + ABORT = 3 +} + +// payload limit for OSC and DCS +export const PAYLOAD_LIMIT = 10000000; diff --git a/node_modules/xterm/src/common/parser/DcsParser.ts b/node_modules/xterm/src/common/parser/DcsParser.ts new file mode 100644 index 0000000..b66524b --- /dev/null +++ b/node_modules/xterm/src/common/parser/DcsParser.ts @@ -0,0 +1,192 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/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'; + +const EMPTY_HANDLERS: IDcsHandler[] = []; + +export class DcsParser implements IDcsParser { + private _handlers: IHandlerCollection<IDcsHandler> = Object.create(null); + private _active: IDcsHandler[] = EMPTY_HANDLERS; + private _ident: number = 0; + private _handlerFb: DcsFallbackHandlerType = () => { }; + private _stack: ISubParserStackState = { + paused: false, + loopPosition: 0, + fallThrough: false + }; + + public dispose(): void { + this._handlers = Object.create(null); + this._handlerFb = () => { }; + this._active = EMPTY_HANDLERS; + } + + public registerHandler(ident: number, handler: IDcsHandler): IDisposable { + if (this._handlers[ident] === undefined) { + this._handlers[ident] = []; + } + const handlerList = this._handlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + + public clearHandler(ident: number): void { + if (this._handlers[ident]) delete this._handlers[ident]; + } + + public setHandlerFallback(handler: DcsFallbackHandlerType): void { + this._handlerFb = handler; + } + + public reset(): void { + // force cleanup leftover handlers + if (this._active.length) { + 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; + } + + public hook(ident: number, params: IParams): void { + // always reset leftover handlers + this.reset(); + this._ident = ident; + this._active = this._handlers[ident] || EMPTY_HANDLERS; + if (!this._active.length) { + this._handlerFb(this._ident, 'HOOK', params); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].hook(params); + } + } + } + + public put(data: Uint32Array, start: number, end: number): void { + if (!this._active.length) { + this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end)); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].put(data, start, end); + } + } + } + + public unhook(success: boolean, promiseResult: boolean = true): void | Promise<boolean> { + if (!this._active.length) { + this._handlerFb(this._ident, 'UNHOOK', success); + } else { + let handlerResult: boolean | Promise<boolean> = false; + let j = this._active.length - 1; + let fallThrough = false; + if (this._stack.paused) { + j = this._stack.loopPosition - 1; + handlerResult = promiseResult; + fallThrough = this._stack.fallThrough; + this._stack.paused = false; + } + if (!fallThrough && handlerResult === false) { + for (; j >= 0; j--) { + handlerResult = this._active[j].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--) { + handlerResult = this._active[j].unhook(false); + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } + } + } + this._active = EMPTY_HANDLERS; + this._ident = 0; + } +} + +// 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 = EMPTY_PARAMS; + private _hitLimit: boolean = false; + + constructor(private _handler: (data: string, params: IParams) => boolean | Promise<boolean>) { } + + public hook(params: IParams): void { + // 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; + } + + public put(data: Uint32Array, start: number, end: number): void { + if (this._hitLimit) { + return; + } + this._data += utf32ToString(data, start, end); + if (this._data.length > PAYLOAD_LIMIT) { + this._data = ''; + this._hitLimit = true; + } + } + + public unhook(success: boolean): boolean | Promise<boolean> { + let ret: boolean | Promise<boolean> = false; + if (this._hitLimit) { + ret = false; + } else if (success) { + ret = this._handler(this._data, this._params); + if (ret instanceof Promise) { + // need to hold data and params until `ret` got resolved + // dont care for errors, data will be freed anyway on next start + return ret.then(res => { + this._params = EMPTY_PARAMS; + this._data = ''; + this._hitLimit = false; + return res; + }); + } + } + this._params = EMPTY_PARAMS; + this._data = ''; + this._hitLimit = false; + return ret; + } +} diff --git a/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts b/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts new file mode 100644 index 0000000..f20a7e9 --- /dev/null +++ b/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts @@ -0,0 +1,796 @@ +/** + * Copyright (c) 2018 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType, IParserStackState, ParserStackType, ResumableHandlersType } from 'common/parser/Types'; +import { ParserState, ParserAction } from 'common/parser/Constants'; +import { Disposable } from 'common/Lifecycle'; +import { IDisposable } from 'common/Types'; +import { fill } from 'common/TypedArrayUtils'; +import { Params } from 'common/parser/Params'; +import { OscParser } from 'common/parser/OscParser'; +import { DcsParser } from 'common/parser/DcsParser'; + +/** + * Table values are generated like this: + * index: currentState << TableValue.INDEX_STATE_SHIFT | charCode + * value: action << TableValue.TRANSITION_ACTION_SHIFT | nextState + */ +const enum TableAccess { + TRANSITION_ACTION_SHIFT = 4, + TRANSITION_STATE_MASK = 15, + INDEX_STATE_SHIFT = 8 +} + +/** + * Transition table for EscapeSequenceParser. + */ +export class TransitionTable { + public table: Uint8Array; + + constructor(length: number) { + this.table = new Uint8Array(length); + } + + /** + * Set default transition. + * @param action default action + * @param next default next state + */ + public setDefault(action: ParserAction, next: ParserState): void { + fill(this.table, action << TableAccess.TRANSITION_ACTION_SHIFT | next); + } + + /** + * Add a transition to the transition table. + * @param code input character code + * @param state current parser state + * @param action parser action to be done + * @param next next parser state + */ + public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void { + this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next; + } + + /** + * Add transitions for multiple input character codes. + * @param codes input character code array + * @param state current parser state + * @param action parser action to be done + * @param next next parser state + */ + public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void { + for (let i = 0; i < codes.length; i++) { + this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next; + } + } +} + + +// Pseudo-character placeholder for printable non-ascii characters (unicode). +const NON_ASCII_PRINTABLE = 0xA0; + + +/** + * VT500 compatible transition table. + * Taken from https://vt100.net/emu/dec_ansi_parser. + */ +export const VT500_TRANSITION_TABLE = (function (): TransitionTable { + const table: TransitionTable = new TransitionTable(4095); + + // range macro for byte + const BYTE_VALUES = 256; + const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i); + const r = (start: number, end: number): number[] => blueprint.slice(start, end); + + // Default definitions. + const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded + const EXECUTABLES = r(0x00, 0x18); + EXECUTABLES.push(0x19); + EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20)); + + const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1); + let state: any; + + // set default transition + table.setDefault(ParserAction.ERROR, ParserState.GROUND); + // printables + table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND); + // global anywhere rules + for (state in states) { + table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND); + table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND); + table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND); + table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator + table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE); // ESC + table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING); // OSC + table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY); // CSI + table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY); // DCS + } + // rules for executables and 7f + table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND); + table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE); + table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE); + table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING); + table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY); + table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY); + table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM); + table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM); + table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE); + table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE); + table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE); + table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE); + table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE); + // osc + table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING); + table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING); + table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING); + table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND); + table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING); + // sos/pm/apc does nothing + table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND); + table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING); + // csi entries + table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY); + table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND); + table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM); + table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM); + table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND); + table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE); + table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE); + table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND); + table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE); + // esc_intermediate + table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE); + table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE); + table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND); + // dcs entry + table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY); + table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY); + table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY); + table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY); + table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM); + table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM); + table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM); + table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM); + table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM); + table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE); + table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE); + table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE); + table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH); + table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH); + table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH); + table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH); + table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH); + table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH); + table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND); + // special handling of unicode chars + table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND); + table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING); + table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE); + table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE); + table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH); + return table; +})(); + + +/** + * EscapeSequenceParser. + * This class implements the ANSI/DEC compatible parser described by + * Paul Williams (https://vt100.net/emu/dec_ansi_parser). + * + * To implement custom ANSI compliant escape sequences it is not needed to + * alter this parser, instead consider registering a custom handler. + * For non ANSI compliant sequences change the transition table with + * the optional `transitions` constructor argument and + * reimplement the `parse` method. + * + * This parser is currently hardcoded to operate in ZDM (Zero Default Mode) + * as suggested by the original parser, thus empty parameters are set to 0. + * This this is not in line with the latest ECMA-48 specification + * (ZDM was part of the early specs and got completely removed later on). + * + * Other than the original parser from vt100.net this parser supports + * sub parameters in digital parameters separated by colons. Empty sub parameters + * are set to -1 (no ZDM for sub parameters). + * + * About prefix and intermediate bytes: + * This parser follows the assumptions of the vt100.net parser with these restrictions: + * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f + * - max. two intermediates are respected, byte range 0x20 .. 0x2f + * Note that this is not in line with ECMA-48 which does not limit either of those. + * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently + * there are no known sequences that follow the broader definition of the specification. + * + * TODO: implement error recovery hook via error handler return values + */ +export class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser { + public initialState: number; + public currentState: number; + public precedingCodepoint: number; + + // buffers over several parse calls + protected _params: Params; + protected _collect: number; + + // handler lookup containers + protected _printHandler: PrintHandlerType; + protected _executeHandlers: { [flag: number]: ExecuteHandlerType }; + protected _csiHandlers: IHandlerCollection<CsiHandlerType>; + protected _escHandlers: IHandlerCollection<EscHandlerType>; + protected _oscParser: IOscParser; + protected _dcsParser: IDcsParser; + protected _errorHandler: (state: IParsingState) => IParsingState; + + // fallback handlers + protected _printHandlerFb: PrintFallbackHandlerType; + protected _executeHandlerFb: ExecuteFallbackHandlerType; + protected _csiHandlerFb: CsiFallbackHandlerType; + protected _escHandlerFb: EscFallbackHandlerType; + protected _errorHandlerFb: (state: IParsingState) => IParsingState; + + // 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 + ) { + super(); + + this.initialState = ParserState.GROUND; + this.currentState = this.initialState; + this._params = new Params(); // defaults to 32 storable params/subparams + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingCodepoint = 0; + + // set default fallback handlers and handler lookup containers + this._printHandlerFb = (data, start, end): void => { }; + this._executeHandlerFb = (code: number): void => { }; + this._csiHandlerFb = (ident: number, params: IParams): void => { }; + this._escHandlerFb = (ident: number): void => { }; + this._errorHandlerFb = (state: IParsingState): IParsingState => state; + this._printHandler = this._printHandlerFb; + this._executeHandlers = Object.create(null); + this._csiHandlers = Object.create(null); + this._escHandlers = Object.create(null); + this._oscParser = new OscParser(); + this._dcsParser = new DcsParser(); + this._errorHandler = this._errorHandlerFb; + + // swallow 7bit ST (ESC+\) + this.registerEscHandler({ final: '\\' }, () => true); + } + + protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number { + let res = 0; + if (id.prefix) { + if (id.prefix.length > 1) { + throw new Error('only one byte as prefix supported'); + } + res = id.prefix.charCodeAt(0); + if (res && 0x3c > res || res > 0x3f) { + throw new Error('prefix must be in range 0x3c .. 0x3f'); + } + } + if (id.intermediates) { + if (id.intermediates.length > 2) { + throw new Error('only two bytes as intermediates are supported'); + } + for (let i = 0; i < id.intermediates.length; ++i) { + const intermediate = id.intermediates.charCodeAt(i); + if (0x20 > intermediate || intermediate > 0x2f) { + throw new Error('intermediate must be in range 0x20 .. 0x2f'); + } + res <<= 8; + res |= intermediate; + } + } + if (id.final.length !== 1) { + throw new Error('final must be a single byte'); + } + const finalCode = id.final.charCodeAt(0); + if (finalRange[0] > finalCode || finalCode > finalRange[1]) { + throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`); + } + res <<= 8; + res |= finalCode; + + return res; + } + + public identToString(ident: number): string { + const res: string[] = []; + while (ident) { + res.push(String.fromCharCode(ident & 0xFF)); + ident >>= 8; + } + return res.reverse().join(''); + } + + public dispose(): void { + this._csiHandlers = Object.create(null); + this._executeHandlers = Object.create(null); + this._escHandlers = Object.create(null); + this._oscParser.dispose(); + this._dcsParser.dispose(); + } + + public setPrintHandler(handler: PrintHandlerType): void { + this._printHandler = handler; + } + public clearPrintHandler(): void { + this._printHandler = this._printHandlerFb; + } + + public registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable { + const ident = this._identifier(id, [0x30, 0x7e]); + if (this._escHandlers[ident] === undefined) { + this._escHandlers[ident] = []; + } + const handlerList = this._escHandlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + public clearEscHandler(id: IFunctionIdentifier): void { + if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])]; + } + public setEscHandlerFallback(handler: EscFallbackHandlerType): void { + this._escHandlerFb = handler; + } + + public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void { + this._executeHandlers[flag.charCodeAt(0)] = handler; + } + public clearExecuteHandler(flag: string): void { + if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)]; + } + public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void { + this._executeHandlerFb = handler; + } + + public registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable { + const ident = this._identifier(id); + if (this._csiHandlers[ident] === undefined) { + this._csiHandlers[ident] = []; + } + const handlerList = this._csiHandlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + public clearCsiHandler(id: IFunctionIdentifier): void { + if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)]; + } + public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void { + this._csiHandlerFb = callback; + } + + public 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)); + } + public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void { + this._dcsParser.setHandlerFallback(handler); + } + + public registerOscHandler(ident: number, handler: IOscHandler): IDisposable { + return this._oscParser.registerHandler(ident, handler); + } + public clearOscHandler(ident: number): void { + this._oscParser.clearHandler(ident); + } + public setOscHandlerFallback(handler: OscFallbackHandlerType): void { + this._oscParser.setHandlerFallback(handler); + } + + public setErrorHandler(callback: (state: IParsingState) => IParsingState): void { + this._errorHandler = callback; + } + public clearErrorHandler(): void { + this._errorHandler = this._errorHandlerFb; + } + + /** + * 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(); + this._dcsParser.reset(); + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingCodepoint = 0; + // abort pending continuation from async handler + // Here the RESET type indicates, that the next parse call will + // ignore any saved stack, instead continues sync with next codepoint from GROUND + if (this._parseStack.state !== ParserStackType.NONE) { + this._parseStack.state = ParserStackType.RESET; + this._parseStack.handlers = []; // also release handlers ref + } + } + + /** + * Async parse support. + */ + protected _preserveStack( + state: ParserStackType, + handlers: ResumableHandlersType, + handlerPos: number, + transition: number, + chunkPos: number + ): void { + this._parseStack.state = state; + this._parseStack.handlers = handlers; + this._parseStack.handlerPos = handlerPos; + this._parseStack.transition = transition; + this._parseStack.chunkPos = chunkPos; + } + + /** + * Parse UTF32 codepoints in `data` up to `length`. + * + * Note: For several actions with high data load the parsing is optimized + * by using local read ahead loops with hardcoded conditions to + * avoid costly table lookups. Make sure that any change of table values + * will be reflected in the loop conditions as well and vice versa. + * Affected states/actions: + * - GROUND:PRINT + * - CSI_PARAM:PARAM + * - DCS_PARAM:PARAM + * - OSC_STRING:OSC_PUT + * - DCS_PASSTHROUGH:DCS_PUT + * + * Note on asynchronous handler support: + * Any handler returning a promise will be treated as asynchronous. + * To keep the in-band blocking working for async handlers, `parse` pauses execution, + * creates a stack save and returns the promise to the caller. + * For proper continuation of the paused state it is important + * to await the promise resolving. On resolve the parse must be repeated + * with the same chunk of data and the resolved value in `promiseResult` + * until no promise is returned. + * + * Important: With only sync handlers defined, parsing is completely synchronous as well. + * As soon as an async handler is involved, synchronous parsing is not possible anymore. + * + * Boilerplate for proper parsing of multiple chunks with async handlers: + * + * ```typescript + * async function parseMultipleChunks(chunks: Uint32Array[]): Promise<void> { + * for (const chunk of chunks) { + * let result: void | Promise<boolean>; + * 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<boolean> { + let code = 0; + let transition = 0; + let start = 0; + let handlerResult: void | boolean | Promise<boolean>; + + // resume from async handler + if (this._parseStack.state) { + // allow sync parser reset even in continuation mode + // Note: can be used to recover parser from improper continuation error below + if (this._parseStack.state === ParserStackType.RESET) { + this._parseStack.state = ParserStackType.NONE; + start = this._parseStack.chunkPos + 1; // continue with next codepoint in GROUND + } else { + if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) { + /** + * Reject further parsing on improper continuation after pausing. + * This is a really bad condition with screwed up execution order and prolly messed up + * terminal state, therefore we exit hard with an exception and reject any further parsing. + * + * Note: With `Terminal.write` usage this exception should never occur, as the top level + * calls are guaranteed to handle async conditions properly. If you ever encounter this + * exception in your terminal integration it indicates, that you injected data chunks to + * `InputHandler.parse` or `EscapeSequenceParser.parse` synchronously without waiting for + * continuation of a running async handler. + * + * It is possible to get rid of this error by calling `reset`. But dont rely on that, + * as the pending async handler still might mess up the terminal later. Instead fix the faulty + * async handling, so this error will not be thrown anymore. + */ + this._parseStack.state = ParserStackType.FAIL; + throw new Error('improper continuation due to previous async handler, giving up parsing'); + } + + // we have to resume the old handler loop if: + // - return value of the promise was `false` + // - handlers are not exhausted yet + const handlers = this._parseStack.handlers; + let handlerPos = this._parseStack.handlerPos - 1; + switch (this._parseStack.state) { + case ParserStackType.CSI: + if (promiseResult === false && handlerPos > -1) { + for (; handlerPos >= 0; handlerPos--) { + handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + } + } + this._parseStack.handlers = []; + break; + case ParserStackType.ESC: + if (promiseResult === false && handlerPos > -1) { + for (; handlerPos >= 0; handlerPos--) { + handlerResult = (handlers as EscHandlerType[])[handlerPos](); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._parseStack.handlerPos = handlerPos; + return handlerResult; + } + } + } + this._parseStack.handlers = []; + break; + case ParserStackType.DCS: + code = data[this._parseStack.chunkPos]; + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { + return handlerResult; + } + if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + case ParserStackType.OSC: + code = data[this._parseStack.chunkPos]; + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult); + if (handlerResult) { + return handlerResult; + } + if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + } + // cleanup before continuing with the main sync loop + this._parseStack.state = ParserStackType.NONE; + start = this._parseStack.chunkPos + 1; + this.precedingCodepoint = 0; + this.currentState = this._parseStack.transition & TableAccess.TRANSITION_STATE_MASK; + } + } + + // continue with main sync loop + + // process input string + for (let i = start; i < length; ++i) { + code = data[i]; + + // normal transition & action lookup + 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 + // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded + for (let j = i + 1; ; ++j) { + if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) { + this._printHandler(data, i, j); + i = j - 1; + break; + } + } + break; + case ParserAction.EXECUTE: + if (this._executeHandlers[code]) this._executeHandlers[code](); + else this._executeHandlerFb(code); + this.precedingCodepoint = 0; + break; + case ParserAction.IGNORE: + break; + case ParserAction.ERROR: + const inject: IParsingState = this._errorHandler( + { + position: i, + code, + currentState: this.currentState, + collect: this._collect, + params: this._params, + abort: false + }); + if (inject.abort) return; + // inject values: currently not implemented + break; + case ParserAction.CSI_DISPATCH: + // Trigger CSI Handler + const handlers = this._csiHandlers[this._collect << 8 | code]; + let j = handlers ? handlers.length - 1 : -1; + for (; j >= 0; j--) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + handlerResult = handlers[j](this._params); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._preserveStack(ParserStackType.CSI, handlers, j, transition, i); + return handlerResult; + } + } + if (j < 0) { + this._csiHandlerFb(this._collect << 8 | code, this._params); + } + this.precedingCodepoint = 0; + break; + case ParserAction.PARAM: + // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a) + do { + switch (code) { + case 0x3b: + this._params.addParam(0); // ZDM + break; + case 0x3a: + this._params.addSubParam(-1); + break; + default: // 0x30 - 0x39 + this._params.addDigit(code - 48); + } + } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c); + i--; + break; + case ParserAction.COLLECT: + this._collect <<= 8; + this._collect |= code; + break; + case ParserAction.ESC_DISPATCH: + const handlersEsc = this._escHandlers[this._collect << 8 | code]; + let jj = handlersEsc ? handlersEsc.length - 1 : -1; + for (; jj >= 0; jj--) { + // true means success and to stop bubbling + // a promise indicates an async handler that needs to finish before progressing + handlerResult = handlersEsc[jj](); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._preserveStack(ParserStackType.ESC, handlersEsc, jj, transition, i); + return handlerResult; + } + } + if (jj < 0) { + this._escHandlerFb(this._collect << 8 | code); + } + this.precedingCodepoint = 0; + break; + case ParserAction.CLEAR: + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + break; + case ParserAction.DCS_HOOK: + 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)) { + this._dcsParser.put(data, i, j); + i = j - 1; + break; + } + } + break; + case ParserAction.DCS_UNHOOK: + handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a); + if (handlerResult) { + this._preserveStack(ParserStackType.DCS, [], 0, transition, i); + return handlerResult; + } + if (code === 0x1b) transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingCodepoint = 0; + break; + case ParserAction.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)) { + this._oscParser.put(data, i, j); + i = j - 1; + break; + } + } + break; + case ParserAction.OSC_END: + handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a); + if (handlerResult) { + this._preserveStack(ParserStackType.OSC, [], 0, transition, i); + return handlerResult; + } + if (code === 0x1b) transition |= ParserState.ESCAPE; + this._params.reset(); + this._params.addParam(0); // ZDM + this._collect = 0; + this.precedingCodepoint = 0; + break; + } + this.currentState = transition & TableAccess.TRANSITION_STATE_MASK; + } + } +} diff --git a/node_modules/xterm/src/common/parser/OscParser.ts b/node_modules/xterm/src/common/parser/OscParser.ts new file mode 100644 index 0000000..32710ae --- /dev/null +++ b/node_modules/xterm/src/common/parser/OscParser.ts @@ -0,0 +1,238 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser, ISubParserStackState } from 'common/parser/Types'; +import { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants'; +import { utf32ToString } from 'common/input/TextDecoder'; +import { IDisposable } from 'common/Types'; + +const EMPTY_HANDLERS: IOscHandler[] = []; + +export class OscParser implements IOscParser { + private _state = OscState.START; + private _active = EMPTY_HANDLERS; + private _id = -1; + private _handlers: IHandlerCollection<IOscHandler> = 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) { + this._handlers[ident] = []; + } + const handlerList = this._handlers[ident]; + handlerList.push(handler); + return { + dispose: () => { + const handlerIndex = handlerList.indexOf(handler); + if (handlerIndex !== -1) { + handlerList.splice(handlerIndex, 1); + } + } + }; + } + public clearHandler(ident: number): void { + if (this._handlers[ident]) delete this._handlers[ident]; + } + public setHandlerFallback(handler: OscFallbackHandlerType): void { + this._handlerFb = handler; + } + + public dispose(): void { + this._handlers = Object.create(null); + this._handlerFb = () => { }; + this._active = EMPTY_HANDLERS; + } + + public reset(): void { + // force cleanup handlers if payload was already sent + if (this._state === OscState.PAYLOAD) { + for (let j = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; j >= 0; --j) { + this._active[j].end(false); + } + } + this._stack.paused = false; + this._active = EMPTY_HANDLERS; + this._id = -1; + this._state = OscState.START; + } + + private _start(): void { + this._active = this._handlers[this._id] || EMPTY_HANDLERS; + if (!this._active.length) { + this._handlerFb(this._id, 'START'); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].start(); + } + } + } + + private _put(data: Uint32Array, start: number, end: number): void { + if (!this._active.length) { + this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end)); + } else { + for (let j = this._active.length - 1; j >= 0; j--) { + this._active[j].put(data, start, end); + } + } + } + + public start(): void { + // always reset leftover handlers + this.reset(); + this._state = OscState.ID; + } + + /** + * Put data to current OSC command. + * Expects the identifier of the OSC command in the form + * OSC id ; payload ST/BEL + * Payload chunks are not further processed and get + * directly passed to the handlers. + */ + public put(data: Uint32Array, start: number, end: number): void { + if (this._state === OscState.ABORT) { + return; + } + if (this._state === OscState.ID) { + while (start < end) { + const code = data[start++]; + if (code === 0x3b) { + this._state = OscState.PAYLOAD; + this._start(); + break; + } + if (code < 0x30 || 0x39 < code) { + this._state = OscState.ABORT; + return; + } + if (this._id === -1) { + this._id = 0; + } + this._id = this._id * 10 + code - 48; + } + } + if (this._state === OscState.PAYLOAD && end - start > 0) { + this._put(data, start, end); + } + } + + /** + * Indicates end of an OSC command. + * Whether the OSC got aborted or finished normally + * is indicated by `success`. + */ + public end(success: boolean, promiseResult: boolean = true): void | Promise<boolean> { + if (this._state === OscState.START) { + return; + } + // do nothing if command was faulty + if (this._state !== OscState.ABORT) { + // if we are still in ID state and get an early end + // means that the command has no payload thus we still have + // to announce START and send END right after + if (this._state === OscState.ID) { + this._start(); + } + + if (!this._active.length) { + this._handlerFb(this._id, 'END', success); + } else { + let handlerResult: boolean | Promise<boolean> = false; + let j = this._active.length - 1; + let fallThrough = false; + if (this._stack.paused) { + j = this._stack.loopPosition - 1; + handlerResult = promiseResult; + fallThrough = this._stack.fallThrough; + this._stack.paused = false; + } + if (!fallThrough && handlerResult === false) { + for (; j >= 0; j--) { + handlerResult = this._active[j].end(success); + if (handlerResult === true) { + break; + } else if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = false; + return handlerResult; + } + } + j--; + } + // cleanup left over handlers + // we always have to call .end for proper cleanup, + // here we use `success` to indicate whether a handler should execute + for (; j >= 0; j--) { + handlerResult = this._active[j].end(false); + if (handlerResult instanceof Promise) { + this._stack.paused = true; + this._stack.loopPosition = j; + this._stack.fallThrough = true; + return handlerResult; + } + } + } + + } + this._active = EMPTY_HANDLERS; + this._id = -1; + this._state = OscState.START; + } +} + +/** + * Convenient class to allow attaching string based handler functions + * as OSC handlers. + */ +export class OscHandler implements IOscHandler { + private _data = ''; + private _hitLimit: boolean = false; + + constructor(private _handler: (data: string) => boolean | Promise<boolean>) { } + + public start(): void { + this._data = ''; + this._hitLimit = false; + } + + public put(data: Uint32Array, start: number, end: number): void { + if (this._hitLimit) { + return; + } + this._data += utf32ToString(data, start, end); + if (this._data.length > PAYLOAD_LIMIT) { + this._data = ''; + this._hitLimit = true; + } + } + + public end(success: boolean): boolean | Promise<boolean> { + let ret: boolean | Promise<boolean> = false; + if (this._hitLimit) { + ret = false; + } else if (success) { + ret = this._handler(this._data); + if (ret instanceof Promise) { + // need to hold data until `ret` got resolved + // dont care for errors, data will be freed anyway on next start + return ret.then(res => { + this._data = ''; + this._hitLimit = false; + return res; + }); + } + } + this._data = ''; + this._hitLimit = false; + return ret; + } +} diff --git a/node_modules/xterm/src/common/parser/Params.ts b/node_modules/xterm/src/common/parser/Params.ts new file mode 100644 index 0000000..7071453 --- /dev/null +++ b/node_modules/xterm/src/common/parser/Params.ts @@ -0,0 +1,229 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IParams, ParamsArray } from 'common/parser/Types'; + +// max value supported for a single param/subparam (clamped to positive int32 range) +const MAX_VALUE = 0x7FFFFFFF; +// max allowed subparams for a single sequence (hardcoded limitation) +const MAX_SUBPARAMS = 256; + +/** + * Params storage class. + * This type is used by the parser to accumulate sequence parameters and sub parameters + * and transmit them to the input handler actions. + * + * NOTES: + * - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy + * - never read beyond `params.length - 1` (likely to contain arbitrary data) + * - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params + * - hardcoded limitations: + * - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that) + * - max. 256 sub params possible + * - negative values are not allowed beside -1 (placeholder for default value) + * + * About ZDM (Zero Default Mode): + * ZDM is not orchestrated by this class. If the parser is in ZDM, + * it should add 0 for empty params, otherwise -1. This does not apply + * to subparams, empty subparams should always be added with -1. + */ +export class Params implements IParams { + // params store and length + public params: Int32Array; + public length: number; + + // sub params store and length + protected _subParams: Int32Array; + protected _subParamsLength: number; + + // sub params offsets from param: param idx --> [start, end] offset + private _subParamsIdx: Uint16Array; + private _rejectDigits: boolean; + private _rejectSubDigits: boolean; + private _digitIsSub: boolean; + + /** + * Create a `Params` type from JS array representation. + */ + public static fromArray(values: ParamsArray): Params { + const params = new Params(); + if (!values.length) { + return params; + } + // skip leading sub params + for (let i = (Array.isArray(values[0])) ? 1 : 0; i < values.length; ++i) { + const value = values[i]; + if (Array.isArray(value)) { + for (let k = 0; k < value.length; ++k) { + params.addSubParam(value[k]); + } + } else { + params.addParam(value); + } + } + return params; + } + + /** + * @param maxLength max length of storable parameters + * @param maxSubParamsLength max length of storable sub parameters + */ + constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) { + if (maxSubParamsLength > MAX_SUBPARAMS) { + throw new Error('maxSubParamsLength must not be greater than 256'); + } + this.params = new Int32Array(maxLength); + this.length = 0; + this._subParams = new Int32Array(maxSubParamsLength); + this._subParamsLength = 0; + this._subParamsIdx = new Uint16Array(maxLength); + this._rejectDigits = false; + this._rejectSubDigits = false; + this._digitIsSub = false; + } + + /** + * Clone object. + */ + public clone(): Params { + const newParams = new Params(this.maxLength, this.maxSubParamsLength); + newParams.params.set(this.params); + newParams.length = this.length; + newParams._subParams.set(this._subParams); + newParams._subParamsLength = this._subParamsLength; + newParams._subParamsIdx.set(this._subParamsIdx); + newParams._rejectDigits = this._rejectDigits; + newParams._rejectSubDigits = this._rejectSubDigits; + newParams._digitIsSub = this._digitIsSub; + return newParams; + } + + /** + * Get a JS array representation of the current parameters and sub parameters. + * The array is structured as follows: + * sequence: "1;2:3:4;5::6" + * array : [1, 2, [3, 4], 5, [-1, 6]] + */ + public toArray(): ParamsArray { + const res: ParamsArray = []; + for (let i = 0; i < this.length; ++i) { + res.push(this.params[i]); + const start = this._subParamsIdx[i] >> 8; + const end = this._subParamsIdx[i] & 0xFF; + if (end - start > 0) { + res.push(Array.prototype.slice.call(this._subParams, start, end)); + } + } + return res; + } + + /** + * Reset to initial empty state. + */ + public reset(): void { + this.length = 0; + this._subParamsLength = 0; + this._rejectDigits = false; + this._rejectSubDigits = false; + this._digitIsSub = false; + } + + /** + * Add a parameter value. + * `Params` only stores up to `maxLength` parameters, any later + * parameter will be ignored. + * Note: VT devices only stored up to 16 values, xterm seems to + * store up to 30. + */ + public addParam(value: number): void { + this._digitIsSub = false; + if (this.length >= this.maxLength) { + this._rejectDigits = true; + return; + } + if (value < -1) { + throw new Error('values lesser than -1 are not allowed'); + } + this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength; + this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value; + } + + /** + * Add a sub parameter value. + * The sub parameter is automatically associated with the last parameter value. + * Thus it is not possible to add a subparameter without any parameter added yet. + * `Params` only stores up to `subParamsLength` sub parameters, any later + * sub parameter will be ignored. + */ + public addSubParam(value: number): void { + this._digitIsSub = true; + if (!this.length) { + return; + } + if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) { + this._rejectSubDigits = true; + return; + } + if (value < -1) { + throw new Error('values lesser than -1 are not allowed'); + } + this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value; + this._subParamsIdx[this.length - 1]++; + } + + /** + * Whether parameter at index `idx` has sub parameters. + */ + public hasSubParams(idx: number): boolean { + return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0); + } + + /** + * Return sub parameters for parameter at index `idx`. + * Note: The values are borrowed, thus you need to copy + * the values if you need to hold them in nonlocal scope. + */ + public getSubParams(idx: number): Int32Array | null { + const start = this._subParamsIdx[idx] >> 8; + const end = this._subParamsIdx[idx] & 0xFF; + if (end - start > 0) { + return this._subParams.subarray(start, end); + } + return null; + } + + /** + * Return all sub parameters as {idx: subparams} mapping. + * Note: The values are not borrowed. + */ + public getSubParamsAll(): {[idx: number]: Int32Array} { + const result: {[idx: number]: Int32Array} = {}; + for (let i = 0; i < this.length; ++i) { + const start = this._subParamsIdx[i] >> 8; + const end = this._subParamsIdx[i] & 0xFF; + if (end - start > 0) { + result[i] = this._subParams.slice(start, end); + } + } + return result; + } + + /** + * Add a single digit value to current parameter. + * This is used by the parser to account digits on a char by char basis. + */ + public addDigit(value: number): void { + let length; + if (this._rejectDigits + || !(length = this._digitIsSub ? this._subParamsLength : this.length) + || (this._digitIsSub && this._rejectSubDigits) + ) { + return; + } + + const store = this._digitIsSub ? this._subParams : this.params; + const cur = store[length - 1]; + store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value; + } +} diff --git a/node_modules/xterm/src/common/parser/Types.d.ts b/node_modules/xterm/src/common/parser/Types.d.ts new file mode 100644 index 0000000..3a621ea --- /dev/null +++ b/node_modules/xterm/src/common/parser/Types.d.ts @@ -0,0 +1,274 @@ +/** + * Copyright (c) 2017 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IDisposable } from 'common/Types'; +import { ParserState } from 'common/parser/Constants'; + + +/** sequence params serialized to js arrays */ +export type ParamsArray = (number | number[])[]; + +/** Params constructor type. */ +export interface IParamsConstructor { + new(maxLength: number, maxSubParamsLength: number): IParams; + + /** create params from ParamsArray */ + fromArray(values: ParamsArray): IParams; +} + +/** Interface of Params storage class. */ +export interface IParams { + /** from ctor */ + maxLength: number; + maxSubParamsLength: number; + + /** param values and its length */ + params: Int32Array; + length: number; + + /** methods */ + clone(): IParams; + toArray(): ParamsArray; + reset(): void; + addParam(value: number): void; + addSubParam(value: number): void; + hasSubParams(idx: number): boolean; + getSubParams(idx: number): Int32Array | null; + getSubParamsAll(): {[idx: number]: Int32Array}; +} + +/** + * Internal state of EscapeSequenceParser. + * Used as argument of the error handler to allow + * introspection at runtime on parse errors. + * Return it with altered values to recover from + * faulty states (not yet supported). + * Set `abort` to `true` to abort the current parsing. + */ +export interface IParsingState { + // position in parse string + position: number; + // actual character code + code: number; + // current parser state + currentState: ParserState; + // collect buffer with intermediate characters + collect: number; + // params buffer + params: IParams; + // should abort (default: false) + abort: boolean; +} + +/** + * Command handler interfaces. + */ + +/** + * CSI handler types. + * Note: `params` is borrowed. + */ +export type CsiHandlerType = (params: IParams) => boolean | Promise<boolean>; +export type CsiFallbackHandlerType = (ident: number, params: IParams) => void; + +/** + * DCS handler types. + */ +export interface IDcsHandler { + /** + * Called when a DCS command starts. + * Prepare needed data structures here. + * Note: `params` is borrowed. + */ + hook(params: IParams): void; + /** + * Incoming payload chunk. + * Note: `params` is borrowed. + */ + put(data: Uint32Array, start: number, end: number): void; + /** + * End of DCS command. `success` indicates whether the + * command finished normally or got aborted, thus final + * execution of the command should depend on `success`. + * To save memory also cleanup data structures here. + */ + unhook(success: boolean): boolean | Promise<boolean>; +} +export type DcsFallbackHandlerType = (ident: number, action: 'HOOK' | 'PUT' | 'UNHOOK', payload?: any) => void; + +/** + * ESC handler types. + */ +export type EscHandlerType = () => boolean | Promise<boolean>; +export type EscFallbackHandlerType = (identifier: number) => void; + +/** + * EXECUTE handler types. + */ +export type ExecuteHandlerType = () => boolean; +export type ExecuteFallbackHandlerType = (ident: number) => void; + +/** + * OSC handler types. + */ +export interface IOscHandler { + /** + * Announces start of this OSC command. + * Prepare needed data structures here. + */ + start(): void; + /** + * Incoming data chunk. + * Note: Data is borrowed. + */ + put(data: Uint32Array, start: number, end: number): void; + /** + * End of OSC command. `success` indicates whether the + * command finished normally or got aborted, thus final + * execution of the command should depend on `success`. + * To save memory also cleanup data structures here. + */ + end(success: boolean): boolean | Promise<boolean>; +} +export type OscFallbackHandlerType = (ident: number, action: 'START' | 'PUT' | 'END', payload?: any) => void; + +/** + * PRINT handler types. + */ +export type PrintHandlerType = (data: Uint32Array, start: number, end: number) => void; +export type PrintFallbackHandlerType = PrintHandlerType; + + +/** +* EscapeSequenceParser interface. +*/ +export interface IEscapeSequenceParser extends IDisposable { + /** + * Preceding codepoint to get REP working correctly. + * This must be set by the print handler as last action. + * It gets reset by the parser for any valid sequence beside REP itself. + */ + precedingCodepoint: number; + + /** + * Reset the parser to its initial state (handlers are kept). + */ + reset(): void; + + /** + * Parse UTF32 codepoints in `data` up to `length`. + * @param data The data to parse. + */ + parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise<boolean>; + + /** + * Get string from numercial function identifier `ident`. + * Useful in fallback handlers which expose the low level + * numcerical function identifier for debugging purposes. + * Note: A full back translation to `IFunctionIdentifier` + * is not implemented. + */ + identToString(ident: number): string; + + setPrintHandler(handler: PrintHandlerType): void; + clearPrintHandler(): void; + + registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable; + clearEscHandler(id: IFunctionIdentifier): void; + setEscHandlerFallback(handler: EscFallbackHandlerType): void; + + setExecuteHandler(flag: string, handler: ExecuteHandlerType): void; + clearExecuteHandler(flag: string): void; + setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void; + + registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable; + clearCsiHandler(id: IFunctionIdentifier): void; + setCsiHandlerFallback(callback: CsiFallbackHandlerType): void; + + registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable; + clearDcsHandler(id: IFunctionIdentifier): void; + setDcsHandlerFallback(handler: DcsFallbackHandlerType): void; + + registerOscHandler(ident: number, handler: IOscHandler): IDisposable; + clearOscHandler(ident: number): void; + setOscHandlerFallback(handler: OscFallbackHandlerType): void; + + setErrorHandler(handler: (state: IParsingState) => IParsingState): void; + clearErrorHandler(): void; +} + +/** + * Subparser interfaces. + * The subparsers are instantiated in `EscapeSequenceParser` and + * called during `EscapeSequenceParser.parse`. + */ +export interface ISubParser<T, U> extends IDisposable { + reset(): void; + registerHandler(ident: number, handler: T): IDisposable; + clearHandler(ident: number): void; + setHandlerFallback(handler: U): void; + put(data: Uint32Array, start: number, end: number): void; +} + +export interface IOscParser extends ISubParser<IOscHandler, OscFallbackHandlerType> { + start(): void; + end(success: boolean, promiseResult?: boolean): void | Promise<boolean>; +} + +export interface IDcsParser extends ISubParser<IDcsHandler, DcsFallbackHandlerType> { + hook(ident: number, params: IParams): void; + unhook(success: boolean, promiseResult?: boolean): void | Promise<boolean>; +} + +/** + * Interface to denote a specific ESC, CSI or DCS handler slot. + * The values are used to create an integer respresentation during handler + * regristation before passed to the subparsers as `ident`. + * The integer translation is made to allow a faster handler access + * in `EscapeSequenceParser.parse`. + */ +export interface IFunctionIdentifier { + prefix?: string; + intermediates?: string; + final: string; +} + +export interface IHandlerCollection<T> { + [key: string]: T[]; +} + +/** + * Types for async parser support. + */ + +// type of saved stack state in parser +export const enum ParserStackType { + NONE = 0, + FAIL, + RESET, + CSI, + ESC, + OSC, + DCS +} + +// aggregate of resumable handler lists +export type ResumableHandlersType = CsiHandlerType[] | EscHandlerType[]; + +// saved stack state of the parser +export interface IParserStackState { + state: ParserStackType; + handlers: ResumableHandlersType; + handlerPos: number; + transition: number; + chunkPos: number; +} + +// saved stack state of subparser (OSC and DCS) +export interface ISubParserStackState { + paused: boolean; + loopPosition: number; + fallThrough: boolean; +} diff --git a/node_modules/xterm/src/common/public/AddonManager.ts b/node_modules/xterm/src/common/public/AddonManager.ts new file mode 100644 index 0000000..06c7812 --- /dev/null +++ b/node_modules/xterm/src/common/public/AddonManager.ts @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ITerminalAddon, IDisposable, Terminal } from 'xterm'; + +export interface ILoadedAddon { + instance: ITerminalAddon; + dispose: () => void; + isDisposed: boolean; +} + +export class AddonManager implements IDisposable { + protected _addons: ILoadedAddon[] = []; + + constructor() { + } + + public dispose(): void { + for (let i = this._addons.length - 1; i >= 0; i--) { + this._addons[i].instance.dispose(); + } + } + + public loadAddon(terminal: Terminal, instance: ITerminalAddon): void { + const loadedAddon: ILoadedAddon = { + instance, + dispose: instance.dispose, + isDisposed: false + }; + this._addons.push(loadedAddon); + instance.dispose = () => this._wrappedAddonDispose(loadedAddon); + instance.activate(terminal as any); + } + + private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void { + if (loadedAddon.isDisposed) { + // Do nothing if already disposed + return; + } + let index = -1; + for (let i = 0; i < this._addons.length; i++) { + if (this._addons[i] === loadedAddon) { + index = i; + break; + } + } + if (index === -1) { + throw new Error('Could not dispose an addon that has not been loaded'); + } + loadedAddon.isDisposed = true; + loadedAddon.dispose.apply(loadedAddon.instance); + this._addons.splice(index, 1); + } +} diff --git a/node_modules/xterm/src/common/public/BufferApiView.ts b/node_modules/xterm/src/common/public/BufferApiView.ts new file mode 100644 index 0000000..ca9ef2d --- /dev/null +++ b/node_modules/xterm/src/common/public/BufferApiView.ts @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi } from 'xterm'; +import { IBuffer } from 'common/buffer/Types'; +import { BufferLineApiView } from 'common/public/BufferLineApiView'; +import { CellData } from 'common/buffer/CellData'; + +export class BufferApiView implements IBufferApi { + constructor( + private _buffer: IBuffer, + public readonly type: 'normal' | 'alternate' + ) { } + + public init(buffer: IBuffer): BufferApiView { + this._buffer = buffer; + return this; + } + + public get cursorY(): number { return this._buffer.y; } + public get cursorX(): number { return this._buffer.x; } + public get viewportY(): number { return this._buffer.ydisp; } + public get baseY(): number { return this._buffer.ybase; } + public get length(): number { return this._buffer.lines.length; } + public getLine(y: number): IBufferLineApi | undefined { + const line = this._buffer.lines.get(y); + if (!line) { + return undefined; + } + return new BufferLineApiView(line); + } + public getNullCell(): IBufferCellApi { return new CellData(); } +} diff --git a/node_modules/xterm/src/common/public/BufferLineApiView.ts b/node_modules/xterm/src/common/public/BufferLineApiView.ts new file mode 100644 index 0000000..6037501 --- /dev/null +++ b/node_modules/xterm/src/common/public/BufferLineApiView.ts @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { CellData } from 'common/buffer/CellData'; +import { IBufferLine, ICellData } from 'common/Types'; +import { IBufferCell as IBufferCellApi, IBufferLine as IBufferLineApi } from 'xterm'; + +export class BufferLineApiView implements IBufferLineApi { + constructor(private _line: IBufferLine) { } + + public get isWrapped(): boolean { return this._line.isWrapped; } + public get length(): number { return this._line.length; } + public getCell(x: number, cell?: IBufferCellApi): IBufferCellApi | undefined { + if (x < 0 || x >= this._line.length) { + return undefined; + } + + if (cell) { + this._line.loadCell(x, cell as ICellData); + return cell; + } + return this._line.loadCell(x, new CellData()); + } + public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string { + return this._line.translateToString(trimRight, startColumn, endColumn); + } +} diff --git a/node_modules/xterm/src/common/public/BufferNamespaceApi.ts b/node_modules/xterm/src/common/public/BufferNamespaceApi.ts new file mode 100644 index 0000000..d86f6bf --- /dev/null +++ b/node_modules/xterm/src/common/public/BufferNamespaceApi.ts @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBuffer as IBufferApi, IBufferNamespace as IBufferNamespaceApi } from 'xterm'; +import { BufferApiView } from 'common/public/BufferApiView'; +import { IEvent, EventEmitter } from 'common/EventEmitter'; +import { ICoreTerminal } from 'common/Types'; + +export class BufferNamespaceApi implements IBufferNamespaceApi { + private _normal: BufferApiView; + private _alternate: BufferApiView; + private _onBufferChange = new EventEmitter<IBufferApi>(); + public get onBufferChange(): IEvent<IBufferApi> { return this._onBufferChange.event; } + + constructor(private _core: ICoreTerminal) { + this._normal = new BufferApiView(this._core.buffers.normal, 'normal'); + this._alternate = new BufferApiView(this._core.buffers.alt, 'alternate'); + this._core.buffers.onBufferActivate(() => this._onBufferChange.fire(this.active)); + } + public get active(): IBufferApi { + if (this._core.buffers.active === this._core.buffers.normal) { return this.normal; } + if (this._core.buffers.active === this._core.buffers.alt) { return this.alternate; } + throw new Error('Active buffer is neither normal nor alternate'); + } + public get normal(): IBufferApi { + return this._normal.init(this._core.buffers.normal); + } + public get alternate(): IBufferApi { + return this._alternate.init(this._core.buffers.alt); + } +} diff --git a/node_modules/xterm/src/common/public/ParserApi.ts b/node_modules/xterm/src/common/public/ParserApi.ts new file mode 100644 index 0000000..67df4be --- /dev/null +++ b/node_modules/xterm/src/common/public/ParserApi.ts @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IParams } from 'common/parser/Types'; +import { IDisposable, IFunctionIdentifier, IParser } from 'xterm'; +import { ICoreTerminal } from 'common/Types'; + +export class ParserApi implements IParser { + constructor(private _core: ICoreTerminal) { } + + public registerCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise<boolean>): IDisposable { + return this._core.registerCsiHandler(id, (params: IParams) => callback(params.toArray())); + } + public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean | Promise<boolean>): IDisposable { + return this.registerCsiHandler(id, callback); + } + public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean | Promise<boolean>): 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 | Promise<boolean>): IDisposable { + return this.registerDcsHandler(id, callback); + } + public registerEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise<boolean>): IDisposable { + return this._core.registerEscHandler(id, handler); + } + public addEscHandler(id: IFunctionIdentifier, handler: () => boolean | Promise<boolean>): IDisposable { + return this.registerEscHandler(id, handler); + } + public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable { + return this._core.registerOscHandler(ident, callback); + } + public addOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable { + return this.registerOscHandler(ident, callback); + } +} diff --git a/node_modules/xterm/src/common/public/UnicodeApi.ts b/node_modules/xterm/src/common/public/UnicodeApi.ts new file mode 100644 index 0000000..8a669a0 --- /dev/null +++ b/node_modules/xterm/src/common/public/UnicodeApi.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2021 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICoreTerminal } from 'common/Types'; +import { IUnicodeHandling, IUnicodeVersionProvider } from 'xterm'; + +export class UnicodeApi implements IUnicodeHandling { + constructor(private _core: ICoreTerminal) { } + + public register(provider: IUnicodeVersionProvider): void { + this._core.unicodeService.register(provider); + } + + public get versions(): string[] { + return this._core.unicodeService.versions; + } + + public get activeVersion(): string { + return this._core.unicodeService.activeVersion; + } + + public set activeVersion(version: string) { + this._core.unicodeService.activeVersion = version; + } +} diff --git a/node_modules/xterm/src/common/services/BufferService.ts b/node_modules/xterm/src/common/services/BufferService.ts new file mode 100644 index 0000000..bba60dd --- /dev/null +++ b/node_modules/xterm/src/common/services/BufferService.ts @@ -0,0 +1,185 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferService, IOptionsService } from 'common/services/Services'; +import { BufferSet } from 'common/buffer/BufferSet'; +import { IBufferSet, IBuffer } from 'common/buffer/Types'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { Disposable } from 'common/Lifecycle'; +import { IAttributeData, IBufferLine, ScrollSource } from 'common/Types'; + +export const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars +export const MINIMUM_ROWS = 1; + +export class BufferService extends Disposable implements IBufferService { + public serviceBrand: any; + + public cols: number; + public rows: number; + public buffers: IBufferSet; + /** Whether the user is scrolling (locks the scroll position) */ + public isUserScrolling: boolean = false; + + private _onResize = new EventEmitter<{ cols: number, rows: number }>(); + public get onResize(): IEvent<{ cols: number, rows: number }> { return this._onResize.event; } + private _onScroll = new EventEmitter<number>(); + public get onScroll(): IEvent<number> { return this._onScroll.event; } + + public get buffer(): IBuffer { return this.buffers.active; } + + /** An IBufferline to clone/copy from for new blank lines */ + private _cachedBlankLine: IBufferLine | undefined; + + constructor( + @IOptionsService private _optionsService: IOptionsService + ) { + super(); + this.cols = Math.max(_optionsService.rawOptions.cols || 0, MINIMUM_COLS); + this.rows = Math.max(_optionsService.rawOptions.rows || 0, MINIMUM_ROWS); + this.buffers = new BufferSet(_optionsService, this); + } + + public dispose(): void { + super.dispose(); + this.buffers.dispose(); + } + + public resize(cols: number, rows: number): void { + this.cols = cols; + this.rows = rows; + this.buffers.resize(cols, rows); + this.buffers.setupTabStops(this.cols); + this._onResize.fire({ cols, rows }); + } + + public reset(): void { + this.buffers.reset(); + this.isUserScrolling = false; + } + + /** + * Scroll the terminal down 1 row, creating a blank line. + * @param isWrapped Whether the new line is wrapped from the previous line. + */ + public scroll(eraseAttr: IAttributeData, isWrapped: boolean = false): void { + const buffer = this.buffer; + + let newLine: IBufferLine | undefined; + newLine = this._cachedBlankLine; + if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) { + newLine = buffer.getBlankLine(eraseAttr, isWrapped); + this._cachedBlankLine = newLine; + } + newLine.isWrapped = isWrapped; + + const topRow = buffer.ybase + buffer.scrollTop; + const bottomRow = buffer.ybase + buffer.scrollBottom; + + if (buffer.scrollTop === 0) { + // Determine whether the buffer is going to be trimmed after insertion. + const willBufferBeTrimmed = buffer.lines.isFull; + + // Insert the line using the fastest method + if (bottomRow === buffer.lines.length - 1) { + if (willBufferBeTrimmed) { + buffer.lines.recycle().copyFrom(newLine); + } else { + buffer.lines.push(newLine.clone()); + } + } else { + buffer.lines.splice(bottomRow + 1, 0, newLine.clone()); + } + + // Only adjust ybase and ydisp when the buffer is not trimmed + if (!willBufferBeTrimmed) { + buffer.ybase++; + // Only scroll the ydisp with ybase if the user has not scrolled up + if (!this.isUserScrolling) { + buffer.ydisp++; + } + } else { + // When the buffer is full and the user has scrolled up, keep the text + // stable unless ydisp is right at the top + if (this.isUserScrolling) { + buffer.ydisp = Math.max(buffer.ydisp - 1, 0); + } + } + } else { + // scrollTop is non-zero which means no line will be going to the + // scrollback, instead we can just shift them in-place. + const scrollRegionHeight = bottomRow - topRow + 1 /* as it's zero-based */; + buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1); + buffer.lines.set(bottomRow, newLine.clone()); + } + + // Move the viewport to the bottom of the buffer unless the user is + // scrolling. + if (!this.isUserScrolling) { + buffer.ydisp = buffer.ybase; + } + + this._onScroll.fire(buffer.ydisp); + } + + /** + * Scroll the display of the terminal + * @param disp The number of lines to scroll down (negative scroll up). + * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used + * to avoid unwanted events being handled by the viewport when the event was triggered from the + * viewport originally. + */ + public scrollLines(disp: number, suppressScrollEvent?: boolean, source?: ScrollSource): void { + const buffer = this.buffer; + if (disp < 0) { + if (buffer.ydisp === 0) { + return; + } + this.isUserScrolling = true; + } else if (disp + buffer.ydisp >= buffer.ybase) { + this.isUserScrolling = false; + } + + const oldYdisp = buffer.ydisp; + buffer.ydisp = Math.max(Math.min(buffer.ydisp + disp, buffer.ybase), 0); + + // No change occurred, don't trigger scroll/refresh + if (oldYdisp === buffer.ydisp) { + return; + } + + if (!suppressScrollEvent) { + this._onScroll.fire(buffer.ydisp); + } + } + + /** + * Scroll the display of the terminal by a number of pages. + * @param pageCount The number of pages to scroll (negative scrolls up). + */ + public scrollPages(pageCount: number): void { + this.scrollLines(pageCount * (this.rows - 1)); + } + + /** + * Scrolls the display of the terminal to the top. + */ + public scrollToTop(): void { + this.scrollLines(-this.buffer.ydisp); + } + + /** + * Scrolls the display of the terminal to the bottom. + */ + public scrollToBottom(): void { + this.scrollLines(this.buffer.ybase - this.buffer.ydisp); + } + + public scrollToLine(line: number): void { + const scrollAmount = line - this.buffer.ydisp; + if (scrollAmount !== 0) { + this.scrollLines(scrollAmount); + } + } +} diff --git a/node_modules/xterm/src/common/services/CharsetService.ts b/node_modules/xterm/src/common/services/CharsetService.ts new file mode 100644 index 0000000..c538106 --- /dev/null +++ b/node_modules/xterm/src/common/services/CharsetService.ts @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICharsetService } from 'common/services/Services'; +import { ICharset } from 'common/Types'; + +export class CharsetService implements ICharsetService { + public serviceBrand: any; + + public charset: ICharset | undefined; + public glevel: number = 0; + + private _charsets: (ICharset | undefined)[] = []; + + public reset(): void { + this.charset = undefined; + this._charsets = []; + this.glevel = 0; + } + + public setgLevel(g: number): void { + this.glevel = g; + this.charset = this._charsets[g]; + } + + public setgCharset(g: number, charset: ICharset | undefined): void { + this._charsets[g] = charset; + if (this.glevel === g) { + this.charset = charset; + } + } +} diff --git a/node_modules/xterm/src/common/services/CoreMouseService.ts b/node_modules/xterm/src/common/services/CoreMouseService.ts new file mode 100644 index 0000000..0b0dc36 --- /dev/null +++ b/node_modules/xterm/src/common/services/CoreMouseService.ts @@ -0,0 +1,309 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IBufferService, ICoreService, ICoreMouseService } from 'common/services/Services'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types'; + +/** + * Supported default protocols. + */ +const DEFAULT_PROTOCOLS: {[key: string]: ICoreMouseProtocol} = { + /** + * NONE + * Events: none + * Modifiers: none + */ + NONE: { + events: CoreMouseEventType.NONE, + restrict: () => false + }, + /** + * X10 + * Events: mousedown + * Modifiers: none + */ + X10: { + events: CoreMouseEventType.DOWN, + restrict: (e: ICoreMouseEvent) => { + // no wheel, no move, no up + if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) { + return false; + } + // no modifiers + e.ctrl = false; + e.alt = false; + e.shift = false; + return true; + } + }, + /** + * VT200 + * Events: mousedown / mouseup / wheel + * Modifiers: all + */ + VT200: { + events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL, + restrict: (e: ICoreMouseEvent) => { + // no move + if (e.action === CoreMouseAction.MOVE) { + return false; + } + return true; + } + }, + /** + * DRAG + * Events: mousedown / mouseup / wheel / mousedrag + * Modifiers: all + */ + DRAG: { + events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG, + restrict: (e: ICoreMouseEvent) => { + // no move without button + if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) { + return false; + } + return true; + } + }, + /** + * ANY + * Events: all mouse related events + * Modifiers: all + */ + ANY: { + events: + CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL + | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE, + restrict: (e: ICoreMouseEvent) => true + } +}; + +const enum Modifiers { + SHIFT = 4, + ALT = 8, + CTRL = 16 +} + +// helper for default encoders to generate the event code. +function eventCode(e: ICoreMouseEvent, isSGR: boolean): number { + let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0); + if (e.button === CoreMouseButton.WHEEL) { + code |= 64; + code |= e.action; + } else { + code |= e.button & 3; + if (e.button & 4) { + code |= 64; + } + if (e.button & 8) { + code |= 128; + } + if (e.action === CoreMouseAction.MOVE) { + code |= CoreMouseAction.MOVE; + } else if (e.action === CoreMouseAction.UP && !isSGR) { + // special case - only SGR can report button on release + // all others have to go with NONE + code |= CoreMouseButton.NONE; + } + } + return code; +} + +const S = String.fromCharCode; + +/** + * Supported default encodings. + */ +const DEFAULT_ENCODINGS: {[key: string]: CoreMouseEncoding} = { + /** + * DEFAULT - CSI M Pb Px Py + * Single byte encoding for coords and event code. + * Can encode values up to 223 (1-based). + */ + DEFAULT: (e: ICoreMouseEvent) => { + const params = [eventCode(e, false) + 32, e.col + 32, e.row + 32]; + // supress mouse report if we exceed addressible range + // Note this is handled differently by emulators + // - xterm: sends 0;0 coords instead + // - vte, konsole: no report + if (params[0] > 255 || params[1] > 255 || params[2] > 255) { + return ''; + } + return `\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`; + }, + /** + * SGR - CSI < Pb ; Px ; Py M|m + * No encoding limitation. + * Can report button on release and works with a well formed sequence. + */ + SGR: (e: ICoreMouseEvent) => { + const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M'; + return `\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`; + } +}; + +/** + * CoreMouseService + * + * Provides mouse tracking reports with different protocols and encodings. + * - protocols: NONE (default), X10, VT200, DRAG, ANY + * - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507) + * + * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`. + * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`. + * Switching a protocol will send a notification event `onProtocolChange` + * with a list of needed events to track. + * + * The service handles the mouse tracking state and decides whether to send + * a tracking report to the backend based on protocol and encoding limitations. + * To send a mouse event call `triggerMouseEvent`. + */ +export class CoreMouseService implements ICoreMouseService { + private _protocols: {[name: string]: ICoreMouseProtocol} = {}; + private _encodings: {[name: string]: CoreMouseEncoding} = {}; + private _activeProtocol: string = ''; + private _activeEncoding: string = ''; + private _onProtocolChange = new EventEmitter<CoreMouseEventType>(); + private _lastEvent: ICoreMouseEvent | null = null; + + constructor( + @IBufferService private readonly _bufferService: IBufferService, + @ICoreService private readonly _coreService: ICoreService + ) { + // register default protocols and encodings + for (const name of Object.keys(DEFAULT_PROTOCOLS)) this.addProtocol(name, DEFAULT_PROTOCOLS[name]); + for (const name of Object.keys(DEFAULT_ENCODINGS)) this.addEncoding(name, DEFAULT_ENCODINGS[name]); + // call reset to set defaults + this.reset(); + } + + public addProtocol(name: string, protocol: ICoreMouseProtocol): void { + this._protocols[name] = protocol; + } + + public addEncoding(name: string, encoding: CoreMouseEncoding): void { + this._encodings[name] = encoding; + } + + public get activeProtocol(): string { + return this._activeProtocol; + } + + public get areMouseEventsActive(): boolean { + return this._protocols[this._activeProtocol].events !== 0; + } + + public set activeProtocol(name: string) { + if (!this._protocols[name]) { + throw new Error(`unknown protocol "${name}"`); + } + this._activeProtocol = name; + this._onProtocolChange.fire(this._protocols[name].events); + } + + public get activeEncoding(): string { + return this._activeEncoding; + } + + public set activeEncoding(name: string) { + if (!this._encodings[name]) { + throw new Error(`unknown encoding "${name}"`); + } + this._activeEncoding = name; + } + + public reset(): void { + this.activeProtocol = 'NONE'; + this.activeEncoding = 'DEFAULT'; + this._lastEvent = null; + } + + /** + * Event to announce changes in mouse tracking. + */ + public get onProtocolChange(): IEvent<CoreMouseEventType> { + return this._onProtocolChange.event; + } + + /** + * Triggers a mouse event to be sent. + * + * Returns true if the event passed all protocol restrictions and a report + * was sent, otherwise false. The return value may be used to decide whether + * the default event action in the bowser component should be omitted. + * + * Note: The method will change values of the given event object + * to fullfill protocol and encoding restrictions. + */ + public triggerMouseEvent(e: ICoreMouseEvent): boolean { + // range check for col/row + if (e.col < 0 || e.col >= this._bufferService.cols + || e.row < 0 || e.row >= this._bufferService.rows) { + return false; + } + + // filter nonsense combinations of button + action + if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) { + return false; + } + if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) { + return false; + } + if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) { + return false; + } + + // report 1-based coords + e.col++; + e.row++; + + // debounce move at grid level + if (e.action === CoreMouseAction.MOVE && this._lastEvent && this._compareEvents(this._lastEvent, e)) { + return false; + } + + // apply protocol restrictions + if (!this._protocols[this._activeProtocol].restrict(e)) { + return false; + } + + // encode report and send + const report = this._encodings[this._activeEncoding](e); + if (report) { + // always send DEFAULT as binary data + if (this._activeEncoding === 'DEFAULT') { + this._coreService.triggerBinaryEvent(report); + } else { + this._coreService.triggerDataEvent(report, true); + } + } + + this._lastEvent = e; + + return true; + } + + public explainEvents(events: CoreMouseEventType): {[event: string]: boolean} { + return { + down: !!(events & CoreMouseEventType.DOWN), + up: !!(events & CoreMouseEventType.UP), + drag: !!(events & CoreMouseEventType.DRAG), + move: !!(events & CoreMouseEventType.MOVE), + wheel: !!(events & CoreMouseEventType.WHEEL) + }; + } + + private _compareEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent): boolean { + if (e1.col !== e2.col) return false; + if (e1.row !== e2.row) return false; + if (e1.button !== e2.button) return false; + if (e1.action !== e2.action) return false; + if (e1.ctrl !== e2.ctrl) return false; + if (e1.alt !== e2.alt) return false; + if (e1.shift !== e2.shift) return false; + return true; + } +} diff --git a/node_modules/xterm/src/common/services/CoreService.ts b/node_modules/xterm/src/common/services/CoreService.ts new file mode 100644 index 0000000..20a3460 --- /dev/null +++ b/node_modules/xterm/src/common/services/CoreService.ts @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ICoreService, ILogService, IOptionsService, IBufferService } from 'common/services/Services'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { IDecPrivateModes, IModes } from 'common/Types'; +import { clone } from 'common/Clone'; +import { Disposable } from 'common/Lifecycle'; + +const DEFAULT_MODES: IModes = Object.freeze({ + insertMode: false +}); + +const DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({ + applicationCursorKeys: false, + applicationKeypad: false, + bracketedPasteMode: false, + origin: false, + reverseWraparound: false, + sendFocus: false, + wraparound: true // defaults: xterm - true, vt100 - false +}); + +export class CoreService extends Disposable implements ICoreService { + public serviceBrand: any; + + public isCursorInitialized: boolean = false; + public isCursorHidden: boolean = false; + public modes: IModes; + public decPrivateModes: IDecPrivateModes; + + // Circular dependency, this must be unset or memory will leak after Terminal.dispose + private _scrollToBottom: (() => void) | undefined; + + private _onData = this.register(new EventEmitter<string>()); + public get onData(): IEvent<string> { return this._onData.event; } + private _onUserInput = this.register(new EventEmitter<void>()); + public get onUserInput(): IEvent<void> { return this._onUserInput.event; } + private _onBinary = this.register(new EventEmitter<string>()); + public get onBinary(): IEvent<string> { return this._onBinary.event; } + + constructor( + // TODO: Move this into a service + scrollToBottom: () => void, + @IBufferService private readonly _bufferService: IBufferService, + @ILogService private readonly _logService: ILogService, + @IOptionsService private readonly _optionsService: IOptionsService + ) { + super(); + this._scrollToBottom = scrollToBottom; + this.register({ dispose: () => this._scrollToBottom = undefined }); + this.modes = clone(DEFAULT_MODES); + this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES); + } + + public reset(): void { + this.modes = clone(DEFAULT_MODES); + this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES); + } + + public triggerDataEvent(data: string, wasUserInput: boolean = false): void { + // Prevents all events to pty process if stdin is disabled + if (this._optionsService.rawOptions.disableStdin) { + return; + } + + // Input is being sent to the terminal, the terminal should focus the prompt. + const buffer = this._bufferService.buffer; + if (buffer.ybase !== buffer.ydisp) { + this._scrollToBottom!(); + } + + // Fire onUserInput so listeners can react as well (eg. clear selection) + if (wasUserInput) { + this._onUserInput.fire(); + } + + // Fire onData API + this._logService.debug(`sending data "${data}"`, () => data.split('').map(e => e.charCodeAt(0))); + this._onData.fire(data); + } + + public triggerBinaryEvent(data: string): void { + if (this._optionsService.rawOptions.disableStdin) { + return; + } + this._logService.debug(`sending binary "${data}"`, () => data.split('').map(e => e.charCodeAt(0))); + this._onBinary.fire(data); + } +} diff --git a/node_modules/xterm/src/common/services/DirtyRowService.ts b/node_modules/xterm/src/common/services/DirtyRowService.ts new file mode 100644 index 0000000..1c43b67 --- /dev/null +++ b/node_modules/xterm/src/common/services/DirtyRowService.ts @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IBufferService, IDirtyRowService } from 'common/services/Services'; + +export class DirtyRowService implements IDirtyRowService { + public serviceBrand: any; + + private _start!: number; + private _end!: number; + + public get start(): number { return this._start; } + public get end(): number { return this._end; } + + constructor( + @IBufferService private readonly _bufferService: IBufferService + ) { + this.clearRange(); + } + + public clearRange(): void { + this._start = this._bufferService.buffer.y; + this._end = this._bufferService.buffer.y; + } + + public markDirty(y: number): void { + if (y < this._start) { + this._start = y; + } else if (y > this._end) { + this._end = y; + } + } + + public markRangeDirty(y1: number, y2: number): void { + if (y1 > y2) { + const temp = y1; + y1 = y2; + y2 = temp; + } + if (y1 < this._start) { + this._start = y1; + } + if (y2 > this._end) { + this._end = y2; + } + } + + public markAllDirty(): void { + this.markRangeDirty(0, this._bufferService.rows - 1); + } +} diff --git a/node_modules/xterm/src/common/services/InstantiationService.ts b/node_modules/xterm/src/common/services/InstantiationService.ts new file mode 100644 index 0000000..8280948 --- /dev/null +++ b/node_modules/xterm/src/common/services/InstantiationService.ts @@ -0,0 +1,83 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + * + * This was heavily inspired from microsoft/vscode's dependency injection system (MIT). + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IInstantiationService, IServiceIdentifier } from 'common/services/Services'; +import { getServiceDependencies } from 'common/services/ServiceRegistry'; + +export class ServiceCollection { + + private _entries = new Map<IServiceIdentifier<any>, any>(); + + constructor(...entries: [IServiceIdentifier<any>, any][]) { + for (const [id, service] of entries) { + this.set(id, service); + } + } + + public set<T>(id: IServiceIdentifier<T>, instance: T): T { + const result = this._entries.get(id); + this._entries.set(id, instance); + return result; + } + + public forEach(callback: (id: IServiceIdentifier<any>, instance: any) => any): void { + this._entries.forEach((value, key) => callback(key, value)); + } + + public has(id: IServiceIdentifier<any>): boolean { + return this._entries.has(id); + } + + public get<T>(id: IServiceIdentifier<T>): T | undefined { + return this._entries.get(id); + } +} + +export class InstantiationService implements IInstantiationService { + public serviceBrand: undefined; + + private readonly _services: ServiceCollection = new ServiceCollection(); + + constructor() { + this._services.set(IInstantiationService, this); + } + + public setService<T>(id: IServiceIdentifier<T>, instance: T): void { + this._services.set(id, instance); + } + + public getService<T>(id: IServiceIdentifier<T>): T | undefined { + return this._services.get(id); + } + + public createInstance<T>(ctor: any, ...args: any[]): T { + const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index); + + const serviceArgs: any[] = []; + for (const dependency of serviceDependencies) { + const service = this._services.get(dependency.id); + if (!service) { + throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`); + } + serviceArgs.push(service); + } + + const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length; + + // check for argument mismatches, adjust static args if needed + if (args.length !== firstServiceArgPos) { + throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`); + } + + // now create the instance + return new ctor(...[...args, ...serviceArgs]); + } +} diff --git a/node_modules/xterm/src/common/services/LogService.ts b/node_modules/xterm/src/common/services/LogService.ts new file mode 100644 index 0000000..d356656 --- /dev/null +++ b/node_modules/xterm/src/common/services/LogService.ts @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { ILogService, IOptionsService, LogLevelEnum } from 'common/services/Services'; + +type LogType = (message?: any, ...optionalParams: any[]) => void; + +interface IConsole { + log: LogType; + error: LogType; + info: LogType; + trace: LogType; + warn: LogType; +} + +// console is available on both node.js and browser contexts but the common +// module doesn't depend on them so we need to explicitly declare it. +declare const console: IConsole; + +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: '; + +export class LogService implements ILogService { + public serviceBrand: any; + + public logLevel: LogLevelEnum = LogLevelEnum.OFF; + + constructor( + @IOptionsService private readonly _optionsService: IOptionsService + ) { + this._updateLogLevel(); + this._optionsService.onOptionChange(key => { + if (key === 'logLevel') { + this._updateLogLevel(); + } + }); + } + + private _updateLogLevel(): void { + this.logLevel = optionsKeyToLogLevel[this._optionsService.rawOptions.logLevel]; + } + + private _evalLazyOptionalParams(optionalParams: any[]): void { + for (let i = 0; i < optionalParams.length; i++) { + if (typeof optionalParams[i] === 'function') { + optionalParams[i] = optionalParams[i](); + } + } + } + + private _log(type: LogType, message: string, optionalParams: any[]): void { + this._evalLazyOptionalParams(optionalParams); + type.call(console, LOG_PREFIX + message, ...optionalParams); + } + + public debug(message: string, ...optionalParams: any[]): void { + if (this.logLevel <= LogLevelEnum.DEBUG) { + this._log(console.log, message, optionalParams); + } + } + + public info(message: string, ...optionalParams: any[]): void { + if (this.logLevel <= LogLevelEnum.INFO) { + this._log(console.info, message, optionalParams); + } + } + + public warn(message: string, ...optionalParams: any[]): void { + if (this.logLevel <= LogLevelEnum.WARN) { + this._log(console.warn, message, optionalParams); + } + } + + public error(message: string, ...optionalParams: any[]): void { + if (this.logLevel <= LogLevelEnum.ERROR) { + this._log(console.error, message, optionalParams); + } + } +} diff --git a/node_modules/xterm/src/common/services/OptionsService.ts b/node_modules/xterm/src/common/services/OptionsService.ts new file mode 100644 index 0000000..43fe998 --- /dev/null +++ b/node_modules/xterm/src/common/services/OptionsService.ts @@ -0,0 +1,177 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IOptionsService, ITerminalOptions, FontWeight } from 'common/services/Services'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { isMac } from 'common/Platform'; + +// Source: https://freesound.org/people/altemark/sounds/45759/ +// This sound is released under the Creative Commons Attribution 3.0 Unported +// (CC BY 3.0) license. It was created by 'altemark'. No modifications have been +// made, apart from the conversion to base64. +export const DEFAULT_BELL_SOUND = 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq'; + +export const DEFAULT_OPTIONS: Readonly<ITerminalOptions> = { + cols: 80, + rows: 24, + cursorBlink: false, + cursorStyle: 'block', + cursorWidth: 1, + customGlyphs: true, + bellSound: DEFAULT_BELL_SOUND, + bellStyle: 'none', + drawBoldTextInBrightColors: true, + fastScrollModifier: 'alt', + fastScrollSensitivity: 5, + fontFamily: 'courier-new, courier, monospace', + fontSize: 15, + fontWeight: 'normal', + fontWeightBold: 'bold', + lineHeight: 1.0, + linkTooltipHoverDuration: 500, + letterSpacing: 0, + logLevel: 'info', + scrollback: 1000, + scrollSensitivity: 1, + screenReaderMode: false, + macOptionIsMeta: false, + macOptionClickForcesSelection: false, + minimumContrastRatio: 1, + disableStdin: false, + allowProposedApi: true, + allowTransparency: false, + tabStopWidth: 8, + theme: {}, + rightClickSelectsWord: isMac, + rendererType: 'canvas', + windowOptions: {}, + windowsMode: false, + wordSeparator: ' ()[]{}\',"`', + altClickMovesCursor: true, + convertEol: false, + termName: 'xterm', + cancelEvents: false +}; + +const FONT_WEIGHT_OPTIONS: Extract<FontWeight, string>[] = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900']; + +export class OptionsService implements IOptionsService { + public serviceBrand: any; + + public readonly rawOptions: ITerminalOptions; + public options: ITerminalOptions; + + private _onOptionChange = new EventEmitter<string>(); + public get onOptionChange(): IEvent<string> { return this._onOptionChange.event; } + + constructor(options: Partial<ITerminalOptions>) { + // set the default value of each option + const defaultOptions = { ...DEFAULT_OPTIONS }; + for (const key in options) { + if (key in defaultOptions) { + try { + const newValue = options[key]; + defaultOptions[key] = this._sanitizeAndValidateOption(key, newValue); + } catch (e) { + console.error(e); + } + } + } + + // set up getters and setters for each option + this.rawOptions = defaultOptions; + this.options = { ... defaultOptions }; + this._setupOptions(); + } + + private _setupOptions(): void { + const getter = (propName: string): any => { + if (!(propName in DEFAULT_OPTIONS)) { + throw new Error(`No option with key "${propName}"`); + } + return this.rawOptions[propName]; + }; + + const setter = (propName: string, value: any): void => { + if (!(propName in DEFAULT_OPTIONS)) { + throw new Error(`No option with key "${propName}"`); + } + + value = this._sanitizeAndValidateOption(propName, value); + // Don't fire an option change event if they didn't change + if (this.rawOptions[propName] !== value) { + this.rawOptions[propName] = value; + this._onOptionChange.fire(propName); + } + }; + + for (const propName in this.rawOptions) { + const desc = { + get: getter.bind(this, propName), + set: setter.bind(this, propName) + }; + Object.defineProperty(this.options, propName, desc); + } + } + + public setOption(key: string, value: any): void { + this.options[key] = value; + } + + private _sanitizeAndValidateOption(key: string, value: any): any { + switch (key) { + case 'bellStyle': + case 'cursorStyle': + case 'rendererType': + case 'wordSeparator': + if (!value) { + value = DEFAULT_OPTIONS[key]; + } + break; + case 'fontWeight': + case 'fontWeightBold': + if (typeof value === 'number' && 1 <= value && value <= 1000) { + // already valid numeric value + break; + } + value = FONT_WEIGHT_OPTIONS.includes(value) ? value : DEFAULT_OPTIONS[key]; + break; + case 'cursorWidth': + value = Math.floor(value); + // Fall through for bounds check + case 'lineHeight': + case 'tabStopWidth': + if (value < 1) { + throw new Error(`${key} cannot be less than 1, value: ${value}`); + } + break; + case 'minimumContrastRatio': + value = Math.max(1, Math.min(21, Math.round(value * 10) / 10)); + break; + case 'scrollback': + value = Math.min(value, 4294967295); + if (value < 0) { + throw new Error(`${key} cannot be less than 0, value: ${value}`); + } + break; + case 'fastScrollSensitivity': + case 'scrollSensitivity': + if (value <= 0) { + throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`); + } + case 'rows': + case 'cols': + if (!value && value !== 0) { + throw new Error(`${key} must be numeric, value: ${value}`); + } + break; + } + return value; + } + + public getOption(key: string): any { + return this.options[key]; + } +} diff --git a/node_modules/xterm/src/common/services/ServiceRegistry.ts b/node_modules/xterm/src/common/services/ServiceRegistry.ts new file mode 100644 index 0000000..6510fb8 --- /dev/null +++ b/node_modules/xterm/src/common/services/ServiceRegistry.ts @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + * + * This was heavily inspired from microsoft/vscode's dependency injection system (MIT). + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IServiceIdentifier } from 'common/services/Services'; + +const DI_TARGET = 'di$target'; +const DI_DEPENDENCIES = 'di$dependencies'; + +export const serviceRegistry: Map<string, IServiceIdentifier<any>> = new Map(); + +export function getServiceDependencies(ctor: any): { id: IServiceIdentifier<any>, index: number, optional: boolean }[] { + return ctor[DI_DEPENDENCIES] || []; +} + +export function createDecorator<T>(id: string): IServiceIdentifier<T> { + if (serviceRegistry.has(id)) { + return serviceRegistry.get(id)!; + } + + const decorator: any = function (target: Function, key: string, index: number): any { + if (arguments.length !== 3) { + throw new Error('@IServiceName-decorator can only be used to decorate a parameter'); + } + + storeServiceDependency(decorator, target, index); + }; + + decorator.toString = () => id; + + serviceRegistry.set(id, decorator); + return decorator; +} + +function storeServiceDependency(id: Function, target: Function, index: number): void { + if ((target as any)[DI_TARGET] === target) { + (target as any)[DI_DEPENDENCIES].push({ id, index }); + } else { + (target as any)[DI_DEPENDENCIES] = [{ id, index }]; + (target as any)[DI_TARGET] = target; + } +} diff --git a/node_modules/xterm/src/common/services/Services.ts b/node_modules/xterm/src/common/services/Services.ts new file mode 100644 index 0000000..90dca98 --- /dev/null +++ b/node_modules/xterm/src/common/services/Services.ts @@ -0,0 +1,300 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ + +import { IEvent } from 'common/EventEmitter'; +import { IBuffer, IBufferSet } from 'common/buffer/Types'; +import { IDecPrivateModes, ICoreMouseEvent, CoreMouseEncoding, ICoreMouseProtocol, CoreMouseEventType, ICharset, IWindowOptions, IModes, IAttributeData, ScrollSource } from 'common/Types'; +import { createDecorator } from 'common/services/ServiceRegistry'; + +export const IBufferService = createDecorator<IBufferService>('BufferService'); +export interface IBufferService { + serviceBrand: undefined; + + readonly cols: number; + readonly rows: number; + readonly buffer: IBuffer; + readonly buffers: IBufferSet; + isUserScrolling: boolean; + onResize: IEvent<{ cols: number, rows: number }>; + onScroll: IEvent<number>; + scroll(eraseAttr: IAttributeData, isWrapped?: boolean): void; + scrollToBottom(): void; + scrollToTop(): void; + scrollToLine(line: number): void; + scrollLines(disp: number, suppressScrollEvent?: boolean, source?: ScrollSource): void; + scrollPages(pageCount: number): void; + resize(cols: number, rows: number): void; + reset(): void; +} + +export const ICoreMouseService = createDecorator<ICoreMouseService>('CoreMouseService'); +export interface ICoreMouseService { + activeProtocol: string; + activeEncoding: string; + areMouseEventsActive: boolean; + addProtocol(name: string, protocol: ICoreMouseProtocol): void; + addEncoding(name: string, encoding: CoreMouseEncoding): void; + reset(): void; + + /** + * Triggers a mouse event to be sent. + * + * Returns true if the event passed all protocol restrictions and a report + * was sent, otherwise false. The return value may be used to decide whether + * the default event action in the bowser component should be omitted. + * + * Note: The method will change values of the given event object + * to fullfill protocol and encoding restrictions. + */ + triggerMouseEvent(event: ICoreMouseEvent): boolean; + + /** + * Event to announce changes in mouse tracking. + */ + onProtocolChange: IEvent<CoreMouseEventType>; + + /** + * Human readable version of mouse events. + */ + explainEvents(events: CoreMouseEventType): { [event: string]: boolean }; +} + +export const ICoreService = createDecorator<ICoreService>('CoreService'); +export interface ICoreService { + serviceBrand: undefined; + + /** + * Initially the cursor will not be visible until the first time the terminal + * is focused. + */ + isCursorInitialized: boolean; + isCursorHidden: boolean; + + readonly modes: IModes; + readonly decPrivateModes: IDecPrivateModes; + + readonly onData: IEvent<string>; + readonly onUserInput: IEvent<void>; + readonly onBinary: IEvent<string>; + + reset(): void; + + /** + * Triggers the onData event in the public API. + * @param data The data that is being emitted. + * @param wasFromUser Whether the data originated from the user (as opposed to + * resulting from parsing incoming data). When true this will also: + * - Scroll to the bottom of the buffer.s + * - Fire the `onUserInput` event (so selection can be cleared). + */ + triggerDataEvent(data: string, wasUserInput?: boolean): void; + + /** + * Triggers the onBinary event in the public API. + * @param data The data that is being emitted. + */ + triggerBinaryEvent(data: string): void; +} + +export const ICharsetService = createDecorator<ICharsetService>('CharsetService'); +export interface ICharsetService { + serviceBrand: undefined; + + charset: ICharset | undefined; + readonly glevel: number; + + reset(): void; + + /** + * Set the G level of the terminal. + * @param g + */ + setgLevel(g: number): void; + + /** + * Set the charset for the given G level of the terminal. + * @param g + * @param charset + */ + setgCharset(g: number, charset: ICharset | undefined): void; +} + +export const IDirtyRowService = createDecorator<IDirtyRowService>('DirtyRowService'); +export interface IDirtyRowService { + serviceBrand: undefined; + + readonly start: number; + readonly end: number; + + clearRange(): void; + markDirty(y: number): void; + markRangeDirty(y1: number, y2: number): void; + markAllDirty(): void; +} + +export interface IServiceIdentifier<T> { + (...args: any[]): void; + type: T; +} + +export interface IBrandedService { + serviceBrand: undefined; +} + +type GetLeadingNonServiceArgs<Args> = + Args extends [...IBrandedService[]] ? [] + : Args extends [infer A1, ...IBrandedService[]] ? [A1] + : Args extends [infer A1, infer A2, ...IBrandedService[]] ? [A1, A2] + : Args extends [infer A1, infer A2, infer A3, ...IBrandedService[]] ? [A1, A2, A3] + : Args extends [infer A1, infer A2, infer A3, infer A4, ...IBrandedService[]] ? [A1, A2, A3, A4] + : Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, ...IBrandedService[]] ? [A1, A2, A3, A4, A5] + : Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, ...IBrandedService[]] ? [A1, A2, A3, A4, A5, A6] + : Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, ...IBrandedService[]] ? [A1, A2, A3, A4, A5, A6, A7] + : Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, infer A8, ...IBrandedService[]] ? [A1, A2, A3, A4, A5, A6, A7, A8] + : never; + +export const IInstantiationService = createDecorator<IInstantiationService>('InstantiationService'); +export interface IInstantiationService { + serviceBrand: undefined; + + setService<T>(id: IServiceIdentifier<T>, instance: T): void; + getService<T>(id: IServiceIdentifier<T>): T | undefined; + createInstance<Ctor extends new (...args: any[]) => any, R extends InstanceType<Ctor>>(t: Ctor, ...args: GetLeadingNonServiceArgs<ConstructorParameters<Ctor>>): R; +} + +export enum LogLevelEnum { + DEBUG = 0, + INFO = 1, + WARN = 2, + ERROR = 3, + OFF = 4 +} + +export const ILogService = createDecorator<ILogService>('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; + error(message: any, ...optionalParams: any[]): void; +} + +export const IOptionsService = createDecorator<IOptionsService>('OptionsService'); +export interface IOptionsService { + serviceBrand: undefined; + + /** + * Read only access to the raw options object, this is an internal-only fast path for accessing + * single options without any validation as we trust TypeScript to enforce correct usage + * internally. + */ + readonly rawOptions: Readonly<ITerminalOptions>; + readonly options: ITerminalOptions; + + readonly onOptionChange: IEvent<string>; + + setOption<T>(key: string, value: T): void; + getOption<T>(key: string): T | undefined; +} + +export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number; +export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off'; + +export type RendererType = 'dom' | 'canvas'; + +export interface ITerminalOptions { + allowProposedApi: boolean; + allowTransparency: boolean; + altClickMovesCursor: boolean; + bellSound: string; + bellStyle: 'none' | 'sound' /* | 'visual' | 'both' */; + cols: number; + convertEol: boolean; + cursorBlink: boolean; + cursorStyle: 'block' | 'underline' | 'bar'; + cursorWidth: number; + customGlyphs: boolean; + disableStdin: boolean; + drawBoldTextInBrightColors: boolean; + fastScrollModifier: 'alt' | 'ctrl' | 'shift' | undefined; + fastScrollSensitivity: number; + fontSize: number; + fontFamily: string; + fontWeight: FontWeight; + fontWeightBold: FontWeight; + letterSpacing: number; + lineHeight: number; + linkTooltipHoverDuration: number; + logLevel: LogLevel; + macOptionIsMeta: boolean; + macOptionClickForcesSelection: boolean; + minimumContrastRatio: number; + rendererType: RendererType; + rightClickSelectsWord: boolean; + rows: number; + screenReaderMode: boolean; + scrollback: number; + scrollSensitivity: number; + tabStopWidth: number; + theme: ITheme; + windowsMode: boolean; + windowOptions: IWindowOptions; + wordSeparator: string; + + [key: string]: any; + cancelEvents: boolean; + termName: string; +} + +export interface ITheme { + foreground?: string; + background?: string; + cursor?: string; + cursorAccent?: string; + selection?: string; + black?: string; + red?: string; + green?: string; + yellow?: string; + blue?: string; + magenta?: string; + cyan?: string; + white?: string; + brightBlack?: string; + brightRed?: string; + brightGreen?: string; + brightYellow?: string; + brightBlue?: string; + brightMagenta?: string; + brightCyan?: string; + brightWhite?: string; +} + +export const IUnicodeService = createDecorator<IUnicodeService>('UnicodeService'); +export interface IUnicodeService { + serviceBrand: undefined; + /** Register an Unicode version provider. */ + register(provider: IUnicodeVersionProvider): void; + /** Registered Unicode versions. */ + readonly versions: string[]; + /** Currently active version. */ + activeVersion: string; + /** Event triggered, when activate version changed. */ + readonly onChange: IEvent<string>; + + /** + * Unicode version dependent + */ + wcwidth(codepoint: number): number; + getStringCellWidth(s: string): number; +} + +export interface IUnicodeVersionProvider { + readonly version: string; + wcwidth(ucs: number): 0 | 1 | 2; +} diff --git a/node_modules/xterm/src/common/services/UnicodeService.ts b/node_modules/xterm/src/common/services/UnicodeService.ts new file mode 100644 index 0000000..e96b757 --- /dev/null +++ b/node_modules/xterm/src/common/services/UnicodeService.ts @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2019 The xterm.js authors. All rights reserved. + * @license MIT + */ +import { IUnicodeService, IUnicodeVersionProvider } from 'common/services/Services'; +import { EventEmitter, IEvent } from 'common/EventEmitter'; +import { UnicodeV6 } from 'common/input/UnicodeV6'; + + +export class UnicodeService implements IUnicodeService { + public serviceBrand: any; + + private _providers: {[key: string]: IUnicodeVersionProvider} = Object.create(null); + private _active: string = ''; + private _activeProvider: IUnicodeVersionProvider; + private _onChange = new EventEmitter<string>(); + public get onChange(): IEvent<string> { return this._onChange.event; } + + constructor() { + const defaultProvider = new UnicodeV6(); + this.register(defaultProvider); + this._active = defaultProvider.version; + this._activeProvider = defaultProvider; + } + + public get versions(): string[] { + return Object.keys(this._providers); + } + + public get activeVersion(): string { + return this._active; + } + + public set activeVersion(version: string) { + if (!this._providers[version]) { + throw new Error(`unknown Unicode version "${version}"`); + } + this._active = version; + this._activeProvider = this._providers[version]; + this._onChange.fire(version); + } + + public register(provider: IUnicodeVersionProvider): void { + this._providers[provider.version] = provider; + } + + /** + * Unicode version dependent interface. + */ + public wcwidth(num: number): number { + return this._activeProvider.wcwidth(num); + } + + public getStringCellWidth(s: string): number { + let result = 0; + const length = s.length; + for (let i = 0; i < length; ++i) { + let code = s.charCodeAt(i); + // surrogate pair first + if (0xD800 <= code && code <= 0xDBFF) { + if (++i >= length) { + // this should not happen with strings retrieved from + // Buffer.translateToString as it converts from UTF-32 + // and therefore always should contain the second part + // for any other string we still have to handle it somehow: + // simply treat the lonely surrogate first as a single char (UCS-2 behavior) + return result + this.wcwidth(code); + } + const second = s.charCodeAt(i); + // convert surrogate pair to high codepoint only for valid second part (UTF-16) + // otherwise treat them independently (UCS-2 behavior) + if (0xDC00 <= second && second <= 0xDFFF) { + code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } else { + result += this.wcwidth(second); + } + } + result += this.wcwidth(code); + } + return result; + } +} |