Merge branch 'master' into issue_3074_fix
This commit is contained in:
@@ -9,6 +9,7 @@
|
||||
"project": [
|
||||
"src/browser/tsconfig.json",
|
||||
"src/common/tsconfig.json",
|
||||
"src/headless/tsconfig.json",
|
||||
"test/api/tsconfig.json",
|
||||
"test/benchmark/tsconfig.json",
|
||||
"addons/xterm-addon-attach/src/tsconfig.json",
|
||||
|
||||
@@ -91,6 +91,10 @@ We also partially support *Internet Explorer 11*, meaning xterm.js should work f
|
||||
|
||||
Xterm.js works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working.
|
||||
|
||||
### Node.js Support
|
||||
|
||||
We also publish [`xterm-headless`](https://www.npmjs.com/package/xterm-headless) which is a stripped down version of xterm.js that runs in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the serialize addon so it can get all state restored upon reconnection.
|
||||
|
||||
## API
|
||||
|
||||
The full API for xterm.js is contained within the [TypeScript declaration file](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts), use the branch/tag picker in GitHub (`w`) to navigate to the correct version of the API.
|
||||
@@ -162,20 +166,23 @@ Xterm.js is used in several world-class applications to provide great terminal e
|
||||
- [**CoCalc**](https://cocalc.com/): Lots of free software pre-installed, to chat, collaborate, develop, program, publish, research, share, teach, in C++, HTML, Julia, Jupyter, LaTeX, Markdown, Python, R, SageMath, Scala, ...
|
||||
- [**Dank Domain**](https://www.DDgame.us/): Open source multiuser medieval game supporting old & new terminal emulation.
|
||||
- [**DockerStacks**](https://docker-stacks.com/): Local LAMP/LEMP development studio
|
||||
- [**Codecademy**](https://codecademy.com/): Uses xterm.js in its courses on Bash.
|
||||
- [**Codecademy**](https://codecademy.com/): Uses xterm.js in its courses on Bash.
|
||||
- [**Laravel Ssh Web Client**](https://github.com/roke22/Laravel-ssh-client): Laravel server inventory with ssh web client to connect at server using xterm.js
|
||||
- [**Repl.it**](https://repl.it): Collaborative browser based IDE with support for 50+ different languages.
|
||||
- [**TeleType**](https://github.com/akshaykmr/TeleType): cli tool that allows you to share your terminal online conveniently. Show off mad cli-fu, help a colleague, teach, or troubleshoot.
|
||||
- [**Intervue**](https://www.intervue.io): Pair programming for interviews. Multiple programming languages are supported, with results displayed by xterm.js.
|
||||
- [**TRASA**](https://trasa.io): Zero trust access to Web, SSH, RDP, and Database services.
|
||||
- [**TRASA**](https://trasa.io): Zero trust access to Web, SSH, RDP, and Database services.
|
||||
- [**Commas**](https://github.com/CyanSalt/commas): Commas is a hackable terminal and command runner.
|
||||
- [**Devtron**](https://github.com/devtron-labs/devtron): Software Delivery Workflow For Kubernetes.
|
||||
- [**Devtron**](https://github.com/devtron-labs/devtron): Software Delivery Workflow For Kubernetes.
|
||||
- [**NxShell**](https://github.com/nxshell/nxshell): An easy to use new terminal for SSH.
|
||||
- [**gifcast**](https://dstein64.github.io/gifcast/): Converts an asciinema cast to an animated GIF.
|
||||
- [**WizardWebssh**](https://gitlab.com/mikeramsey/wizardwebssh): A terminal with Pyqt5 Widget for embedding, which can be used as an ssh client to connect to your ssh servers. It is written in Python, based on tornado, paramiko, and xterm.js.
|
||||
- [**Wizard Assistant**](https://wizardassistant.com/): Wizard Assistant comes with advanced automation tools, preloaded common and special time-saving commands, and a built-in SSH terminal. Now you can remotely administer, troubleshoot, and analyze any system with ease.
|
||||
- [**Wizard Assistant**](https://wizardassistant.com/): Wizard Assistant comes with advanced automation tools, preloaded common and special time-saving commands, and a built-in SSH terminal. Now you can remotely administer, troubleshoot, and analyze any system with ease.
|
||||
- [**ucli**](https://github.com/tsadarsh/ucli): Command Line for everyone :family_man_woman_girl_boy: at [www.ucli.tech](https://www.ucli.tech).
|
||||
- [**Tess**](https://github.com/SquitchYT/Tess/): Simple Terminal Fully Customizable for Everyone.
|
||||
- [**HashiCorp Nomad**](https://www.nomadproject.io/): A container orchestrator with the ability to connect to remote tasks via a web interface using websockets and xterm.js.
|
||||
- [**TermPair**](https://github.com/cs01/termpair): View and control terminals from your browser with end-to-end encryption
|
||||
- [**gdbgui**](https://github.com/cs01/gdbgui): Browser-based frontend to gdb (gnu debugger)
|
||||
- [And much more...](https://github.com/xtermjs/xterm.js/network/dependents)
|
||||
|
||||
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Note: Please add any new contributions to the end of the list only.
|
||||
|
||||
@@ -23,7 +23,7 @@ export interface ISearchResult {
|
||||
row: number;
|
||||
}
|
||||
|
||||
const NON_WORD_CHARACTERS = ' ~!@#$%^&*()+`-=[]{}|\;:"\',./<>?';
|
||||
const NON_WORD_CHARACTERS = ' ~!@#$%^&*()+`-=[]{}|\\;:"\',./<>?';
|
||||
const LINES_CACHE_TIME_TO_LIVE = 15 * 1000; // 15 secs
|
||||
|
||||
export class SearchAddon implements ITerminalAddon {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
},
|
||||
"main": "lib/xterm-addon-serialize.js",
|
||||
"types": "typings/xterm-addon-serialize.d.ts",
|
||||
"repository": "https://github.com/xtermjs/xterm.js",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "../../node_modules/.bin/tsc -p .",
|
||||
|
||||
@@ -7,13 +7,17 @@
|
||||
|
||||
import { Terminal, ITerminalAddon, IBuffer, IBufferCell } from 'xterm';
|
||||
|
||||
|
||||
function constrain(value: number, low: number, high: number): number {
|
||||
return Math.max(low, Math.min(value, high));
|
||||
}
|
||||
|
||||
// TODO: Refine this template class later
|
||||
abstract class BaseSerializeHandler {
|
||||
constructor(private _buffer: IBuffer) { }
|
||||
constructor(
|
||||
protected readonly _buffer: IBuffer
|
||||
) {
|
||||
}
|
||||
|
||||
public serialize(startRow: number, endRow: number): string {
|
||||
// we need two of them to flip between old and new cell
|
||||
@@ -71,8 +75,6 @@ function equalFlags(cell1: IBufferCell, cell2: IBufferCell): boolean {
|
||||
&& cell1.isDim() === cell2.isDim();
|
||||
}
|
||||
|
||||
|
||||
|
||||
class StringSerializeHandler extends BaseSerializeHandler {
|
||||
private _rowIndex: number = 0;
|
||||
private _allRows: string[] = new Array<string>();
|
||||
@@ -83,7 +85,7 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
// we can see a full colored cell and a null cell that only have background the same style
|
||||
// but the information isn't preserved by null cell itself
|
||||
// so wee need to record it when required.
|
||||
private _cursorStyle: IBufferCell = this._buffer1.getNullCell();
|
||||
private _cursorStyle: IBufferCell = this._buffer.getNullCell();
|
||||
|
||||
// where exact the cursor styles comes from
|
||||
// because we can't copy the cell directly
|
||||
@@ -92,7 +94,7 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
private _cursorStyleCol: number = 0;
|
||||
|
||||
// this is a null cell for reference for checking whether background is empty or not
|
||||
private _backgroundCell: IBufferCell = this._buffer1.getNullCell();
|
||||
private _backgroundCell: IBufferCell = this._buffer.getNullCell();
|
||||
|
||||
private _firstRow: number = 0;
|
||||
private _lastCursorRow: number = 0;
|
||||
@@ -100,8 +102,11 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
private _lastContentCursorRow: number = 0;
|
||||
private _lastContentCursorCol: number = 0;
|
||||
|
||||
constructor(private _buffer1: IBuffer, private _terminal: Terminal) {
|
||||
super(_buffer1);
|
||||
constructor(
|
||||
buffer: IBuffer,
|
||||
private readonly _terminal: Terminal
|
||||
) {
|
||||
super(buffer);
|
||||
}
|
||||
|
||||
protected _beforeSerialize(rows: number, start: number, end: number): void {
|
||||
@@ -111,14 +116,14 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
this._firstRow = start;
|
||||
}
|
||||
|
||||
private _thisRowLastChar: IBufferCell = this._buffer1.getNullCell();
|
||||
private _thisRowLastSecondChar: IBufferCell = this._buffer1.getNullCell();
|
||||
private _nextRowFirstChar: IBufferCell = this._buffer1.getNullCell();
|
||||
private _thisRowLastChar: IBufferCell = this._buffer.getNullCell();
|
||||
private _thisRowLastSecondChar: IBufferCell = this._buffer.getNullCell();
|
||||
private _nextRowFirstChar: IBufferCell = this._buffer.getNullCell();
|
||||
protected _rowEnd(row: number, isLastRow: boolean): void {
|
||||
// if there is colorful empty cell at line end, whe must pad it back, or the the color block will missing
|
||||
if (this._nullCellCount > 0 && !equalBg(this._cursorStyle, this._backgroundCell)) {
|
||||
// use clear right to set background.
|
||||
this._currentRow += `\x1b[${this._nullCellCount}X`;
|
||||
this._currentRow += `\u001b[${this._nullCellCount}X`;
|
||||
}
|
||||
|
||||
let rowSeparator = '';
|
||||
@@ -127,13 +132,13 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
if (!isLastRow) {
|
||||
// Enable BCE
|
||||
if (row - this._firstRow >= this._terminal.rows) {
|
||||
this._buffer1.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol, this._backgroundCell);
|
||||
this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol, this._backgroundCell);
|
||||
}
|
||||
|
||||
// Fetch current line
|
||||
const currentLine = this._buffer1.getLine(row)!;
|
||||
const currentLine = this._buffer.getLine(row)!;
|
||||
// Fetch next line
|
||||
const nextLine = this._buffer1.getLine(row + 1)!;
|
||||
const nextLine = this._buffer.getLine(row + 1)!;
|
||||
|
||||
if (!nextLine.isWrapped) {
|
||||
// just insert the line break
|
||||
@@ -187,15 +192,15 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
// insert enough character to force the wrap
|
||||
rowSeparator = '-'.repeat(this._nullCellCount + 1);
|
||||
// move back and erase next line head
|
||||
rowSeparator += '\x1b[1D\x1b[1X';
|
||||
rowSeparator += '\u001b[1D\u001b[1X';
|
||||
|
||||
if (this._nullCellCount > 0) {
|
||||
// do these because we filled the last several null slot, which we shouldn't
|
||||
rowSeparator += '\x1b[A';
|
||||
rowSeparator += `\x1b[${currentLine.length - this._nullCellCount}C`;
|
||||
rowSeparator += `\x1b[${this._nullCellCount}X`;
|
||||
rowSeparator += `\x1b[${currentLine.length - this._nullCellCount}D`;
|
||||
rowSeparator += '\x1b[B';
|
||||
rowSeparator += '\u001b[A';
|
||||
rowSeparator += `\u001b[${currentLine.length - this._nullCellCount}C`;
|
||||
rowSeparator += `\u001b[${this._nullCellCount}X`;
|
||||
rowSeparator += `\u001b[${currentLine.length - this._nullCellCount}D`;
|
||||
rowSeparator += '\u001b[B';
|
||||
}
|
||||
|
||||
// This is content and need the be serialized even it is invisible.
|
||||
@@ -285,20 +290,20 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
if (this._nullCellCount > 0) {
|
||||
// use clear right to set background.
|
||||
if (!equalBg(this._cursorStyle, this._backgroundCell)) {
|
||||
this._currentRow += `\x1b[${this._nullCellCount}X`;
|
||||
this._currentRow += `\u001b[${this._nullCellCount}X`;
|
||||
}
|
||||
// use move right to move cursor.
|
||||
this._currentRow += `\x1b[${this._nullCellCount}C`;
|
||||
this._currentRow += `\u001b[${this._nullCellCount}C`;
|
||||
this._nullCellCount = 0;
|
||||
}
|
||||
|
||||
this._lastContentCursorRow = this._lastCursorRow = row;
|
||||
this._lastContentCursorCol = this._lastCursorCol = col;
|
||||
|
||||
this._currentRow += `\x1b[${sgrSeq.join(';')}m`;
|
||||
this._currentRow += `\u001b[${sgrSeq.join(';')}m`;
|
||||
|
||||
// update the last cursor style
|
||||
const line = this._buffer1.getLine(row);
|
||||
const line = this._buffer.getLine(row);
|
||||
if (line !== undefined) {
|
||||
line.getCell(col, this._cursorStyle);
|
||||
this._cursorStyleRow = row;
|
||||
@@ -317,10 +322,10 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
// because style change is handled by previous stage
|
||||
// use move right when background is empty, use clear right when there is background.
|
||||
if (equalBg(this._cursorStyle, this._backgroundCell)) {
|
||||
this._currentRow += `\x1b[${this._nullCellCount}C`;
|
||||
this._currentRow += `\u001b[${this._nullCellCount}C`;
|
||||
} else {
|
||||
this._currentRow += `\x1b[${this._nullCellCount}X`;
|
||||
this._currentRow += `\x1b[${this._nullCellCount}C`;
|
||||
this._currentRow += `\u001b[${this._nullCellCount}X`;
|
||||
this._currentRow += `\u001b[${this._nullCellCount}C`;
|
||||
}
|
||||
this._nullCellCount = 0;
|
||||
}
|
||||
@@ -338,7 +343,7 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
|
||||
// the fixup is only required for data without scrollback
|
||||
// because it will always be placed at last line otherwise
|
||||
if (this._buffer1.length - this._firstRow <= this._terminal.rows) {
|
||||
if (this._buffer.length - this._firstRow <= this._terminal.rows) {
|
||||
rowEnd = this._lastContentCursorRow + 1 - this._firstRow;
|
||||
this._lastCursorCol = this._lastContentCursorCol;
|
||||
this._lastCursorRow = this._lastContentCursorRow;
|
||||
@@ -354,8 +359,8 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
}
|
||||
|
||||
// restore the cursor
|
||||
const realCursorRow = this._buffer1.baseY + this._buffer1.cursorY;
|
||||
const realCursorCol = this._buffer1.cursorX;
|
||||
const realCursorRow = this._buffer.baseY + this._buffer.cursorY;
|
||||
const realCursorCol = this._buffer.cursorX;
|
||||
|
||||
const cursorMoved = (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol);
|
||||
|
||||
@@ -379,7 +384,6 @@ class StringSerializeHandler extends BaseSerializeHandler {
|
||||
moveRight(realCursorCol - this._lastCursorCol);
|
||||
}
|
||||
|
||||
|
||||
return content;
|
||||
}
|
||||
}
|
||||
@@ -393,14 +397,40 @@ export class SerializeAddon implements ITerminalAddon {
|
||||
this._terminal = terminal;
|
||||
}
|
||||
|
||||
private _getString(buffer: IBuffer, scrollback?: number): string {
|
||||
private _serializeBuffer(terminal: Terminal, buffer: IBuffer, scrollback?: number): string {
|
||||
const maxRows = buffer.length;
|
||||
const handler = new StringSerializeHandler(buffer, this._terminal!);
|
||||
const handler = new StringSerializeHandler(buffer, terminal);
|
||||
const correctRows = (scrollback === undefined) ? maxRows : constrain(scrollback + terminal.rows, 0, maxRows);
|
||||
return handler.serialize(maxRows - correctRows, maxRows);
|
||||
}
|
||||
|
||||
const correctRows = (scrollback === undefined) ? maxRows : constrain(scrollback + this!._terminal!.rows, 0, maxRows);
|
||||
const result = handler.serialize(maxRows - correctRows, maxRows);
|
||||
private _serializeModes(terminal: Terminal): string {
|
||||
let content = '';
|
||||
const modes = terminal.modes;
|
||||
|
||||
return result;
|
||||
// Default: false
|
||||
if (modes.applicationCursorKeysMode) content += '\x1b[?1h';
|
||||
if (modes.applicationKeypadMode) content += '\x1b[?66h';
|
||||
if (modes.bracketedPasteMode) content += '\x1b[?2004h';
|
||||
if (modes.insertMode) content += '\x1b[4h';
|
||||
if (modes.originMode) content += '\x1b[?6h';
|
||||
if (modes.reverseWraparoundMode) content += '\x1b[?45h';
|
||||
if (modes.sendFocusMode) content += '\x1b[?1004h';
|
||||
|
||||
// Default: true
|
||||
if (modes.wraparoundMode === false) content += '\x1b[?7l';
|
||||
|
||||
// Default: 'none'
|
||||
if (modes.mouseTrackingMode !== 'none') {
|
||||
switch (modes.mouseTrackingMode) {
|
||||
case 'x10': content += '\x1b[?9h'; break;
|
||||
case 'vt200': content += '\x1b[?1000h'; break;
|
||||
case 'drag': content += '\x1b[?1002h'; break;
|
||||
case 'any': content += '\x1b[?1003h'; break;
|
||||
}
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
public serialize(scrollback?: number): string {
|
||||
@@ -409,17 +439,19 @@ export class SerializeAddon implements ITerminalAddon {
|
||||
throw new Error('Cannot use addon until it has been loaded');
|
||||
}
|
||||
|
||||
if (this._terminal.buffer.active.type === 'normal') {
|
||||
return this._getString(this._terminal.buffer.active, scrollback);
|
||||
// Normal buffer
|
||||
let content = this._serializeBuffer(this._terminal, this._terminal.buffer.normal, scrollback);
|
||||
|
||||
// Alternate buffer
|
||||
if (this._terminal.buffer.active.type === 'alternate') {
|
||||
const alternativeScreenContent = this._serializeBuffer(this._terminal, this._terminal.buffer.alternate, undefined);
|
||||
content += `\u001b[?1049h\u001b[H${alternativeScreenContent}`;
|
||||
}
|
||||
|
||||
const normalScreenContent = this._getString(this._terminal.buffer.normal, scrollback);
|
||||
// alt screen don't have scrollback
|
||||
const alternativeScreenContent = this._getString(this._terminal.buffer.alternate, undefined);
|
||||
// Modes
|
||||
content += this._serializeModes(this._terminal);
|
||||
|
||||
return normalScreenContent
|
||||
+ '\u001b[?1049h\u001b[H'
|
||||
+ alternativeScreenContent;
|
||||
return content;
|
||||
}
|
||||
|
||||
public dispose(): void { }
|
||||
|
||||
@@ -30,6 +30,12 @@ const testNormalScreenEqual = async (page: any, str: string): Promise<void> => {
|
||||
assert.equal(JSON.stringify(originalBuffer), JSON.stringify(newBuffer));
|
||||
};
|
||||
|
||||
async function testSerializeEquals(writeContent: string, expectedSerialized: string): Promise<void> {
|
||||
await writeRawSync(page, writeContent);
|
||||
const result = await page.evaluate(`serializeAddon.serialize();`) as string;
|
||||
assert.strictEqual(result, expectedSerialized);
|
||||
}
|
||||
|
||||
describe('SerializeAddon', () => {
|
||||
before(async function(): Promise<any> {
|
||||
const browserType = getBrowserType();
|
||||
@@ -89,8 +95,6 @@ describe('SerializeAddon', () => {
|
||||
});
|
||||
|
||||
it('empty content', async function(): Promise<any> {
|
||||
const rows = 10;
|
||||
const cols = 10;
|
||||
assert.equal(await page.evaluate(`serializeAddon.serialize();`), '');
|
||||
});
|
||||
|
||||
@@ -177,17 +181,17 @@ describe('SerializeAddon', () => {
|
||||
const cols = 10;
|
||||
const line = '+'.repeat(cols);
|
||||
const lines: string[] = [
|
||||
mkSGR(FG_P16_GREEN) + line, // Workaround: If we clear all flags a the end, serialize will use \x1b[0m to clear instead of the sepcific disable sequence
|
||||
mkSGR(INVERSE) + line,
|
||||
mkSGR(BOLD) + line,
|
||||
mkSGR(UNDERLINED) + line,
|
||||
mkSGR(BLINK) + line,
|
||||
mkSGR(INVISIBLE) + line,
|
||||
mkSGR(NO_INVERSE) + line,
|
||||
mkSGR(NO_BOLD) + line,
|
||||
mkSGR(NO_UNDERLINED) + line,
|
||||
mkSGR(NO_BLINK) + line,
|
||||
mkSGR(NO_INVISIBLE) + line
|
||||
sgr(FG_P16_GREEN) + line, // Workaround: If we clear all flags a the end, serialize will use \x1b[0m to clear instead of the sepcific disable sequence
|
||||
sgr(INVERSE) + line,
|
||||
sgr(BOLD) + line,
|
||||
sgr(UNDERLINED) + line,
|
||||
sgr(BLINK) + line,
|
||||
sgr(INVISIBLE) + line,
|
||||
sgr(NO_INVERSE) + line,
|
||||
sgr(NO_BOLD) + line,
|
||||
sgr(NO_UNDERLINED) + line,
|
||||
sgr(NO_BLINK) + line,
|
||||
sgr(NO_INVISIBLE) + line
|
||||
];
|
||||
const rows = lines.length;
|
||||
await writeSync(page, lines.join('\\r\\n'));
|
||||
@@ -209,16 +213,16 @@ describe('SerializeAddon', () => {
|
||||
const cols = 10;
|
||||
const line = '+'.repeat(cols);
|
||||
const lines: string[] = [
|
||||
mkSGR(FG_P16_RED) + line, // fg Red,
|
||||
mkSGR(UNDERLINED) + line, // fg Red, Underlined
|
||||
mkSGR(FG_P16_GREEN) + line, // fg Green, Underlined
|
||||
mkSGR(INVERSE) + line, // fg Green, Underlined, Inverse
|
||||
mkSGR(NO_INVERSE) + line, // fg Green, Underlined
|
||||
mkSGR(INVERSE) + line, // fg Green, Underlined, Inverse
|
||||
mkSGR(BG_P16_YELLOW) + line, // fg Green, bg Yellow, Underlined, Inverse
|
||||
mkSGR(FG_RESET) + line, // bg Yellow, Underlined, Inverse
|
||||
mkSGR(BG_RESET) + line, // Underlined, Inverse
|
||||
mkSGR(NORMAL) + line // Back to normal
|
||||
sgr(FG_P16_RED) + line, // fg Red,
|
||||
sgr(UNDERLINED) + line, // fg Red, Underlined
|
||||
sgr(FG_P16_GREEN) + line, // fg Green, Underlined
|
||||
sgr(INVERSE) + line, // fg Green, Underlined, Inverse
|
||||
sgr(NO_INVERSE) + line, // fg Green, Underlined
|
||||
sgr(INVERSE) + line, // fg Green, Underlined, Inverse
|
||||
sgr(BG_P16_YELLOW) + line, // fg Green, bg Yellow, Underlined, Inverse
|
||||
sgr(FG_RESET) + line, // bg Yellow, Underlined, Inverse
|
||||
sgr(BG_RESET) + line, // Underlined, Inverse
|
||||
sgr(NORMAL) + line // Back to normal
|
||||
];
|
||||
await writeSync(page, lines.join('\\r\\n'));
|
||||
assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
|
||||
@@ -228,19 +232,19 @@ describe('SerializeAddon', () => {
|
||||
const cols = 10;
|
||||
const line = '+'.repeat(cols);
|
||||
const lines: string[] = [
|
||||
mkSGR(FG_P16_RED) + line, // fg Red
|
||||
mkSGR(FG_P16_GREEN, BG_P16_YELLOW) + line, // fg Green, bg Yellow
|
||||
mkSGR(UNDERLINED, ITALIC) + line, // fg Green, bg Yellow, Underlined, Italic
|
||||
mkSGR(NO_UNDERLINED, NO_ITALIC) + line, // fg Green, bg Yellow
|
||||
mkSGR(FG_RESET, ITALIC) + line, // bg Yellow, Italic
|
||||
mkSGR(BG_RESET) + line, // Italic
|
||||
mkSGR(NORMAL) + line, // Back to normal
|
||||
mkSGR(FG_P16_RED) + line, // fg Red
|
||||
mkSGR(FG_P16_GREEN, BG_P16_YELLOW) + line, // fg Green, bg Yellow
|
||||
mkSGR(UNDERLINED, ITALIC) + line, // fg Green, bg Yellow, Underlined, Italic
|
||||
mkSGR(NO_UNDERLINED, NO_ITALIC) + line, // fg Green, bg Yellow
|
||||
mkSGR(FG_RESET, ITALIC) + line, // bg Yellow, Italic
|
||||
mkSGR(BG_RESET) + line // Italic
|
||||
sgr(FG_P16_RED) + line, // fg Red
|
||||
sgr(FG_P16_GREEN, BG_P16_YELLOW) + line, // fg Green, bg Yellow
|
||||
sgr(UNDERLINED, ITALIC) + line, // fg Green, bg Yellow, Underlined, Italic
|
||||
sgr(NO_UNDERLINED, NO_ITALIC) + line, // fg Green, bg Yellow
|
||||
sgr(FG_RESET, ITALIC) + line, // bg Yellow, Italic
|
||||
sgr(BG_RESET) + line, // Italic
|
||||
sgr(NORMAL) + line, // Back to normal
|
||||
sgr(FG_P16_RED) + line, // fg Red
|
||||
sgr(FG_P16_GREEN, BG_P16_YELLOW) + line, // fg Green, bg Yellow
|
||||
sgr(UNDERLINED, ITALIC) + line, // fg Green, bg Yellow, Underlined, Italic
|
||||
sgr(NO_UNDERLINED, NO_ITALIC) + line, // fg Green, bg Yellow
|
||||
sgr(FG_RESET, ITALIC) + line, // bg Yellow, Italic
|
||||
sgr(BG_RESET) + line // Italic
|
||||
];
|
||||
await writeSync(page, lines.join('\\r\\n'));
|
||||
assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
|
||||
@@ -250,16 +254,16 @@ describe('SerializeAddon', () => {
|
||||
const cols = 10;
|
||||
const line = '+'.repeat(cols);
|
||||
const lines: string[] = [
|
||||
mkSGR(FG_P256_RED) + line, // fg Red 256,
|
||||
mkSGR(UNDERLINED) + line, // fg Red 256, Underlined
|
||||
mkSGR(FG_P256_GREEN) + line, // fg Green 256, Underlined
|
||||
mkSGR(INVERSE) + line, // fg Green 256, Underlined, Inverse
|
||||
mkSGR(NO_INVERSE) + line, // fg Green 256, Underlined
|
||||
mkSGR(INVERSE) + line, // fg Green 256, Underlined, Inverse
|
||||
mkSGR(BG_P256_YELLOW) + line, // fg Green 256, bg Yellow 256, Underlined, Inverse
|
||||
mkSGR(FG_RESET) + line, // bg Yellow 256, Underlined, Inverse
|
||||
mkSGR(BG_RESET) + line, // Underlined, Inverse
|
||||
mkSGR(NORMAL) + line // Back to normal
|
||||
sgr(FG_P256_RED) + line, // fg Red 256,
|
||||
sgr(UNDERLINED) + line, // fg Red 256, Underlined
|
||||
sgr(FG_P256_GREEN) + line, // fg Green 256, Underlined
|
||||
sgr(INVERSE) + line, // fg Green 256, Underlined, Inverse
|
||||
sgr(NO_INVERSE) + line, // fg Green 256, Underlined
|
||||
sgr(INVERSE) + line, // fg Green 256, Underlined, Inverse
|
||||
sgr(BG_P256_YELLOW) + line, // fg Green 256, bg Yellow 256, Underlined, Inverse
|
||||
sgr(FG_RESET) + line, // bg Yellow 256, Underlined, Inverse
|
||||
sgr(BG_RESET) + line, // Underlined, Inverse
|
||||
sgr(NORMAL) + line // Back to normal
|
||||
];
|
||||
await writeSync(page, lines.join('\\r\\n'));
|
||||
assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
|
||||
@@ -269,19 +273,19 @@ describe('SerializeAddon', () => {
|
||||
const cols = 10;
|
||||
const line = '+'.repeat(cols);
|
||||
const lines: string[] = [
|
||||
mkSGR(FG_P256_RED) + line, // fg Red 256
|
||||
mkSGR(FG_P256_GREEN, BG_P256_YELLOW) + line, // fg Green 256, bg Yellow 256
|
||||
mkSGR(UNDERLINED, ITALIC) + line, // fg Green 256, bg Yellow 256, Underlined, Italic
|
||||
mkSGR(NO_UNDERLINED, NO_ITALIC) + line, // fg Green 256, bg Yellow 256
|
||||
mkSGR(FG_RESET, ITALIC) + line, // bg Yellow 256, Italic
|
||||
mkSGR(BG_RESET) + line, // Italic
|
||||
mkSGR(NORMAL) + line, // Back to normal
|
||||
mkSGR(FG_P256_RED) + line, // fg Red 256
|
||||
mkSGR(FG_P256_GREEN, BG_P256_YELLOW) + line, // fg Green 256, bg Yellow 256
|
||||
mkSGR(UNDERLINED, ITALIC) + line, // fg Green 256, bg Yellow 256, Underlined, Italic
|
||||
mkSGR(NO_UNDERLINED, NO_ITALIC) + line, // fg Green 256, bg Yellow 256
|
||||
mkSGR(FG_RESET, ITALIC) + line, // bg Yellow 256, Italic
|
||||
mkSGR(BG_RESET) + line // Italic
|
||||
sgr(FG_P256_RED) + line, // fg Red 256
|
||||
sgr(FG_P256_GREEN, BG_P256_YELLOW) + line, // fg Green 256, bg Yellow 256
|
||||
sgr(UNDERLINED, ITALIC) + line, // fg Green 256, bg Yellow 256, Underlined, Italic
|
||||
sgr(NO_UNDERLINED, NO_ITALIC) + line, // fg Green 256, bg Yellow 256
|
||||
sgr(FG_RESET, ITALIC) + line, // bg Yellow 256, Italic
|
||||
sgr(BG_RESET) + line, // Italic
|
||||
sgr(NORMAL) + line, // Back to normal
|
||||
sgr(FG_P256_RED) + line, // fg Red 256
|
||||
sgr(FG_P256_GREEN, BG_P256_YELLOW) + line, // fg Green 256, bg Yellow 256
|
||||
sgr(UNDERLINED, ITALIC) + line, // fg Green 256, bg Yellow 256, Underlined, Italic
|
||||
sgr(NO_UNDERLINED, NO_ITALIC) + line, // fg Green 256, bg Yellow 256
|
||||
sgr(FG_RESET, ITALIC) + line, // bg Yellow 256, Italic
|
||||
sgr(BG_RESET) + line // Italic
|
||||
];
|
||||
await writeSync(page, lines.join('\\r\\n'));
|
||||
assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
|
||||
@@ -291,16 +295,16 @@ describe('SerializeAddon', () => {
|
||||
const cols = 10;
|
||||
const line = '+'.repeat(cols);
|
||||
const lines: string[] = [
|
||||
mkSGR(FG_RGB_RED) + line, // fg Red RGB,
|
||||
mkSGR(UNDERLINED) + line, // fg Red RGB, Underlined
|
||||
mkSGR(FG_RGB_GREEN) + line, // fg Green RGB, Underlined
|
||||
mkSGR(INVERSE) + line, // fg Green RGB, Underlined, Inverse
|
||||
mkSGR(NO_INVERSE) + line, // fg Green RGB, Underlined
|
||||
mkSGR(INVERSE) + line, // fg Green RGB, Underlined, Inverse
|
||||
mkSGR(BG_RGB_YELLOW) + line, // fg Green RGB, bg Yellow RGB, Underlined, Inverse
|
||||
mkSGR(FG_RESET) + line, // bg Yellow RGB, Underlined, Inverse
|
||||
mkSGR(BG_RESET) + line, // Underlined, Inverse
|
||||
mkSGR(NORMAL) + line // Back to normal
|
||||
sgr(FG_RGB_RED) + line, // fg Red RGB,
|
||||
sgr(UNDERLINED) + line, // fg Red RGB, Underlined
|
||||
sgr(FG_RGB_GREEN) + line, // fg Green RGB, Underlined
|
||||
sgr(INVERSE) + line, // fg Green RGB, Underlined, Inverse
|
||||
sgr(NO_INVERSE) + line, // fg Green RGB, Underlined
|
||||
sgr(INVERSE) + line, // fg Green RGB, Underlined, Inverse
|
||||
sgr(BG_RGB_YELLOW) + line, // fg Green RGB, bg Yellow RGB, Underlined, Inverse
|
||||
sgr(FG_RESET) + line, // bg Yellow RGB, Underlined, Inverse
|
||||
sgr(BG_RESET) + line, // Underlined, Inverse
|
||||
sgr(NORMAL) + line // Back to normal
|
||||
];
|
||||
await writeSync(page, lines.join('\\r\\n'));
|
||||
assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
|
||||
@@ -310,19 +314,19 @@ describe('SerializeAddon', () => {
|
||||
const cols = 10;
|
||||
const line = '+'.repeat(cols);
|
||||
const lines: string[] = [
|
||||
mkSGR(FG_RGB_RED) + line, // fg Red RGB
|
||||
mkSGR(FG_RGB_GREEN, BG_RGB_YELLOW) + line, // fg Green RGB, bg Yellow RGB
|
||||
mkSGR(UNDERLINED, ITALIC) + line, // fg Green RGB, bg Yellow RGB, Underlined, Italic
|
||||
mkSGR(NO_UNDERLINED, NO_ITALIC) + line, // fg Green RGB, bg Yellow RGB
|
||||
mkSGR(FG_RESET, ITALIC) + line, // bg Yellow RGB, Italic
|
||||
mkSGR(BG_RESET) + line, // Italic
|
||||
mkSGR(NORMAL) + line, // Back to normal
|
||||
mkSGR(FG_RGB_RED) + line, // fg Red RGB
|
||||
mkSGR(FG_RGB_GREEN, BG_RGB_YELLOW) + line, // fg Green RGB, bg Yellow RGB
|
||||
mkSGR(UNDERLINED, ITALIC) + line, // fg Green RGB, bg Yellow RGB, Underlined, Italic
|
||||
mkSGR(NO_UNDERLINED, NO_ITALIC) + line, // fg Green RGB, bg Yellow RGB
|
||||
mkSGR(FG_RESET, ITALIC) + line, // bg Yellow RGB, Italic
|
||||
mkSGR(BG_RESET) + line // Italic
|
||||
sgr(FG_RGB_RED) + line, // fg Red RGB
|
||||
sgr(FG_RGB_GREEN, BG_RGB_YELLOW) + line, // fg Green RGB, bg Yellow RGB
|
||||
sgr(UNDERLINED, ITALIC) + line, // fg Green RGB, bg Yellow RGB, Underlined, Italic
|
||||
sgr(NO_UNDERLINED, NO_ITALIC) + line, // fg Green RGB, bg Yellow RGB
|
||||
sgr(FG_RESET, ITALIC) + line, // bg Yellow RGB, Italic
|
||||
sgr(BG_RESET) + line, // Italic
|
||||
sgr(NORMAL) + line, // Back to normal
|
||||
sgr(FG_RGB_RED) + line, // fg Red RGB
|
||||
sgr(FG_RGB_GREEN, BG_RGB_YELLOW) + line, // fg Green RGB, bg Yellow RGB
|
||||
sgr(UNDERLINED, ITALIC) + line, // fg Green RGB, bg Yellow RGB, Underlined, Italic
|
||||
sgr(NO_UNDERLINED, NO_ITALIC) + line, // fg Green RGB, bg Yellow RGB
|
||||
sgr(FG_RESET, ITALIC) + line, // bg Yellow RGB, Italic
|
||||
sgr(BG_RESET) + line // Italic
|
||||
];
|
||||
await writeSync(page, lines.join('\\r\\n'));
|
||||
assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
|
||||
@@ -481,6 +485,52 @@ describe('SerializeAddon', () => {
|
||||
|
||||
await testNormalScreenEqual(page, lines.join(''));
|
||||
});
|
||||
|
||||
describe('handle modes', () => {
|
||||
it('applicationCursorKeysMode', async () => {
|
||||
await testSerializeEquals('test\u001b[?1h', 'test\u001b[?1h');
|
||||
await testSerializeEquals('\u001b[?1l', 'test');
|
||||
});
|
||||
it('applicationKeypadMode', async () => {
|
||||
await testSerializeEquals('test\u001b[?66h', 'test\u001b[?66h');
|
||||
await testSerializeEquals('\u001b[?66l', 'test');
|
||||
});
|
||||
it('bracketedPasteMode', async () => {
|
||||
await testSerializeEquals('test\u001b[?2004h', 'test\u001b[?2004h');
|
||||
await testSerializeEquals('\u001b[?2004l', 'test');
|
||||
});
|
||||
it('insertMode', async () => {
|
||||
await testSerializeEquals('test\u001b[4h', 'test\u001b[4h');
|
||||
await testSerializeEquals('\u001b[4l', 'test');
|
||||
});
|
||||
it('mouseTrackingMode', async () => {
|
||||
await testSerializeEquals('test\u001b[?9h', 'test\u001b[?9h');
|
||||
await testSerializeEquals('\u001b[?9l', 'test');
|
||||
await testSerializeEquals('\u001b[?1000h', 'test\u001b[?1000h');
|
||||
await testSerializeEquals('\u001b[?1000l', 'test');
|
||||
await testSerializeEquals('\u001b[?1002h', 'test\u001b[?1002h');
|
||||
await testSerializeEquals('\u001b[?1002l', 'test');
|
||||
await testSerializeEquals('\u001b[?1003h', 'test\u001b[?1003h');
|
||||
await testSerializeEquals('\u001b[?1003l', 'test');
|
||||
});
|
||||
it('originMode', async () => {
|
||||
// origin mode moves cursor to (0,0)
|
||||
await testSerializeEquals('test\u001b[?6h', 'test\u001b[4D\u001b[?6h');
|
||||
await testSerializeEquals('\u001b[?6l', 'test\u001b[4D');
|
||||
});
|
||||
it('reverseWraparoundMode', async () => {
|
||||
await testSerializeEquals('test\u001b[?45h', 'test\u001b[?45h');
|
||||
await testSerializeEquals('\u001b[?45l', 'test');
|
||||
});
|
||||
it('sendFocusMode', async () => {
|
||||
await testSerializeEquals('test\u001b[?1004h', 'test\u001b[?1004h');
|
||||
await testSerializeEquals('\u001b[?1004l', 'test');
|
||||
});
|
||||
it('wraparoundMode', async () => {
|
||||
await testSerializeEquals('test\u001b[?7l', 'test\u001b[?7l');
|
||||
await testSerializeEquals('\u001b[?7h', 'test');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function newArray<T>(initial: T | ((index: number) => T), count: number): T[] {
|
||||
@@ -503,7 +553,7 @@ function digitsString(length: number, from: number = 0, sgr: string = ''): strin
|
||||
return s;
|
||||
}
|
||||
|
||||
function mkSGR(...seq: string[]): string {
|
||||
function sgr(...seq: string[]): string {
|
||||
return `\x1b[${seq.join(';')}m`;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
|
||||
import { Terminal, ITerminalAddon } from 'xterm';
|
||||
|
||||
declare module 'xterm-addon-serialize' {
|
||||
@@ -21,12 +20,13 @@ declare module 'xterm-addon-serialize' {
|
||||
public activate(terminal: Terminal): void;
|
||||
|
||||
/**
|
||||
* Serializes terminal rows into a string that can be written back to the terminal
|
||||
* to restore the state. The cursor will also be positioned to the correct cell.
|
||||
* When restoring a terminal it is best to do before `Terminal.open` is called
|
||||
* to avoid wasting CPU cycles rendering incomplete frames.
|
||||
* @param scrollback The number of rows in scrollback buffer to serialize, starting from the bottom of the
|
||||
* scrollback buffer. This defaults to the all available rows in the scrollback buffer.
|
||||
* Serializes terminal rows into a string that can be written back to the terminal to restore
|
||||
* the state. The cursor will also be positioned to the correct cell. When restoring a terminal
|
||||
* it is best to do before `Terminal.open` is called to avoid wasting CPU cycles rendering
|
||||
* incomplete frames.
|
||||
* @param scrollback The number of rows in scrollback buffer to serialize, starting from the
|
||||
* bottom of the scrollback buffer. This defaults to the all available rows in the scrollback
|
||||
* buffer.
|
||||
*/
|
||||
public serialize(scrollback?: number): string;
|
||||
|
||||
|
||||
@@ -25,7 +25,8 @@ module.exports = {
|
||||
filename: mainFile,
|
||||
path: path.resolve('./lib'),
|
||||
library: addonName,
|
||||
libraryTarget: 'umd'
|
||||
libraryTarget: 'umd',
|
||||
globalObject: 'this'
|
||||
},
|
||||
mode: 'production'
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { Terminal, ITerminalAddon } from 'xterm';
|
||||
import { UnicodeV11 } from './UnicodeV11';
|
||||
|
||||
|
||||
export class Unicode11Addon implements ITerminalAddon {
|
||||
public activate(terminal: Terminal): void {
|
||||
terminal.unicode.register(new UnicodeV11());
|
||||
|
||||
@@ -32,7 +32,8 @@ module.exports = {
|
||||
filename: mainFile,
|
||||
path: path.resolve('./lib'),
|
||||
library: addonName,
|
||||
libraryTarget: 'umd'
|
||||
libraryTarget: 'umd',
|
||||
globalObject: 'this'
|
||||
},
|
||||
mode: 'production'
|
||||
};
|
||||
|
||||
@@ -60,7 +60,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
||||
|
||||
this._renderLayers = [
|
||||
new LinkRenderLayer(this._core.screenElement!, 2, this._colors, this._core),
|
||||
new CursorRenderLayer(this._core.screenElement!, 3, this._colors, this._onRequestRedraw)
|
||||
new CursorRenderLayer(this._core.screenElement!, 3, this._colors, this._core, this._onRequestRedraw)
|
||||
];
|
||||
this.dimensions = {
|
||||
scaledCharWidth: 0,
|
||||
@@ -230,7 +230,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
|
||||
return;
|
||||
}
|
||||
|
||||
const atlas = acquireCharAtlas(this._terminal, this._colors, this.dimensions.scaledCharWidth, this.dimensions.scaledCharHeight);
|
||||
const atlas = acquireCharAtlas(this._terminal, this._colors, this.dimensions.scaledCellWidth, this.dimensions.scaledCellHeight, this.dimensions.scaledCharWidth, this.dimensions.scaledCharHeight);
|
||||
if (!('getRasterizedGlyph' in atlas)) {
|
||||
throw new Error('The webgl renderer only works with the webgl char atlas');
|
||||
}
|
||||
|
||||
@@ -28,10 +28,12 @@ const charAtlasCache: ICharAtlasCacheEntry[] = [];
|
||||
export function acquireCharAtlas(
|
||||
terminal: Terminal,
|
||||
colors: IColorSet,
|
||||
scaledCellWidth: number,
|
||||
scaledCellHeight: number,
|
||||
scaledCharWidth: number,
|
||||
scaledCharHeight: number
|
||||
): WebglCharAtlas {
|
||||
const newConfig = generateConfig(scaledCharWidth, scaledCharHeight, terminal, colors);
|
||||
const newConfig = generateConfig(scaledCellWidth, scaledCellHeight, scaledCharWidth, scaledCharHeight, terminal, colors);
|
||||
|
||||
// Check to see if the terminal already owns this config
|
||||
for (let i = 0; i < charAtlasCache.length; i++) {
|
||||
|
||||
@@ -13,7 +13,7 @@ const NULL_COLOR: IColor = {
|
||||
rgba: 0
|
||||
};
|
||||
|
||||
export function generateConfig(scaledCharWidth: number, scaledCharHeight: number, terminal: Terminal, colors: IColorSet): ICharAtlasConfig {
|
||||
export function generateConfig(scaledCellWidth: number, scaledCellHeight: number, scaledCharWidth: number, scaledCharHeight: number, terminal: Terminal, colors: IColorSet): ICharAtlasConfig {
|
||||
// null out some fields that don't matter
|
||||
const clonedColors: IColorSet = {
|
||||
foreground: colors.foreground,
|
||||
@@ -28,7 +28,12 @@ export function generateConfig(scaledCharWidth: number, scaledCharHeight: number
|
||||
contrastCache: colors.contrastCache
|
||||
};
|
||||
return {
|
||||
customGlyphs: terminal.getOption('customGlyphs'),
|
||||
devicePixelRatio: window.devicePixelRatio,
|
||||
letterSpacing: terminal.getOption('letterSpacing'),
|
||||
lineHeight: terminal.getOption('lineHeight'),
|
||||
scaledCellWidth,
|
||||
scaledCellHeight,
|
||||
scaledCharWidth,
|
||||
scaledCharHeight,
|
||||
fontFamily: terminal.getOption('fontFamily'),
|
||||
@@ -49,6 +54,9 @@ export function configEquals(a: ICharAtlasConfig, b: ICharAtlasConfig): boolean
|
||||
}
|
||||
}
|
||||
return a.devicePixelRatio === b.devicePixelRatio &&
|
||||
a.customGlyphs === b.customGlyphs &&
|
||||
a.lineHeight === b.lineHeight &&
|
||||
a.letterSpacing === b.letterSpacing &&
|
||||
a.fontFamily === b.fontFamily &&
|
||||
a.fontSize === b.fontSize &&
|
||||
a.fontWeight === b.fontWeight &&
|
||||
|
||||
@@ -17,11 +17,16 @@ export interface IGlyphIdentifier {
|
||||
}
|
||||
|
||||
export interface ICharAtlasConfig {
|
||||
customGlyphs: boolean;
|
||||
devicePixelRatio: number;
|
||||
letterSpacing: number;
|
||||
lineHeight: number;
|
||||
fontSize: number;
|
||||
fontFamily: string;
|
||||
fontWeight: FontWeight;
|
||||
fontWeightBold: FontWeight;
|
||||
scaledCellWidth: number;
|
||||
scaledCellHeight: number;
|
||||
scaledCharWidth: number;
|
||||
scaledCharHeight: number;
|
||||
allowTransparency: boolean;
|
||||
|
||||
@@ -12,6 +12,7 @@ import { IColor } from 'browser/Types';
|
||||
import { IDisposable } from 'xterm';
|
||||
import { AttributeData } from 'common/buffer/AttributeData';
|
||||
import { channels, rgba } from 'browser/Color';
|
||||
import { tryDrawCustomChar } from 'browser/renderer/CustomGlyphs';
|
||||
|
||||
// In practice we're probably never going to exhaust a texture this large. For debugging purposes,
|
||||
// however, it can be useful to set this to a really tiny value, to verify that LRU eviction works.
|
||||
@@ -83,8 +84,8 @@ export class WebglCharAtlas implements IDisposable {
|
||||
this._cacheCtx = throwIfFalsy(this.cacheCanvas.getContext('2d', { alpha: true }));
|
||||
|
||||
this._tmpCanvas = document.createElement('canvas');
|
||||
this._tmpCanvas.width = this._config.scaledCharWidth * 4 + TMP_CANVAS_GLYPH_PADDING * 2;
|
||||
this._tmpCanvas.height = this._config.scaledCharHeight + TMP_CANVAS_GLYPH_PADDING * 2;
|
||||
this._tmpCanvas.width = this._config.scaledCellWidth * 4 + TMP_CANVAS_GLYPH_PADDING * 2;
|
||||
this._tmpCanvas.height = this._config.scaledCellHeight + TMP_CANVAS_GLYPH_PADDING * 2;
|
||||
this._tmpCtx = throwIfFalsy(this._tmpCanvas.getContext('2d', { alpha: this._config.allowTransparency }));
|
||||
}
|
||||
|
||||
@@ -390,8 +391,32 @@ export class WebglCharAtlas implements IDisposable {
|
||||
// For powerline glyphs left/top padding is excluded (https://github.com/microsoft/vscode/issues/120129)
|
||||
const padding = isPowerlineGlyph ? 0 : TMP_CANVAS_GLYPH_PADDING;
|
||||
|
||||
// Draw custom characters if applicable
|
||||
let drawSuccess = false;
|
||||
if (this._config.customGlyphs !== false) {
|
||||
drawSuccess = tryDrawCustomChar(this._tmpCtx, chars, padding, padding, this._config.scaledCellWidth, this._config.scaledCellHeight);
|
||||
}
|
||||
|
||||
// Draw the character
|
||||
this._tmpCtx.fillText(chars, padding, padding + this._config.scaledCharHeight);
|
||||
if (!drawSuccess) {
|
||||
this._tmpCtx.fillText(chars, padding, padding + this._config.scaledCharHeight);
|
||||
}
|
||||
|
||||
// If this charcater is underscore and beyond the cell bounds, shift it up until it is visible,
|
||||
// try for a maximum of 5 pixels.
|
||||
if (chars === '_' && !this._config.allowTransparency) {
|
||||
let isBeyondCellBounds = clearColor(this._tmpCtx.getImageData(padding, padding, this._config.scaledCellWidth, this._config.scaledCellHeight), backgroundColor);
|
||||
if (isBeyondCellBounds) {
|
||||
for (let offset = 1; offset <= 5; offset++) {
|
||||
this._tmpCtx.clearRect(0, 0, this._tmpCanvas.width, this._tmpCanvas.height);
|
||||
this._tmpCtx.fillText(chars, padding, padding + this._config.scaledCharHeight - offset);
|
||||
isBeyondCellBounds = clearColor(this._tmpCtx.getImageData(padding, padding, this._config.scaledCellWidth, this._config.scaledCellHeight), backgroundColor);
|
||||
if (!isBeyondCellBounds) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Draw underline and strikethrough
|
||||
if (underline || strikethrough) {
|
||||
@@ -434,7 +459,7 @@ export class WebglCharAtlas implements IDisposable {
|
||||
return NULL_RASTERIZED_GLYPH;
|
||||
}
|
||||
|
||||
const rasterizedGlyph = this._findGlyphBoundingBox(imageData, this._workBoundingBox, allowedWidth, isPowerlineGlyph);
|
||||
const rasterizedGlyph = this._findGlyphBoundingBox(imageData, this._workBoundingBox, allowedWidth, isPowerlineGlyph, drawSuccess);
|
||||
const clippedImageData = this._clipImageData(imageData, this._workBoundingBox);
|
||||
|
||||
// Check if there is enough room in the current row and go to next if needed
|
||||
@@ -467,7 +492,7 @@ export class WebglCharAtlas implements IDisposable {
|
||||
* @param imageData The image data to read.
|
||||
* @param boundingBox An IBoundingBox to put the clipped bounding box values.
|
||||
*/
|
||||
private _findGlyphBoundingBox(imageData: ImageData, boundingBox: IBoundingBox, allowedWidth: number, restrictedGlyph: boolean): IRasterizedGlyph {
|
||||
private _findGlyphBoundingBox(imageData: ImageData, boundingBox: IBoundingBox, allowedWidth: number, restrictedGlyph: boolean, customGlyph: boolean): IRasterizedGlyph {
|
||||
boundingBox.top = 0;
|
||||
const height = restrictedGlyph ? this._config.scaledCharHeight : this._tmpCanvas.height;
|
||||
const width = restrictedGlyph ? this._config.scaledCharWidth : allowedWidth;
|
||||
@@ -542,8 +567,8 @@ export class WebglCharAtlas implements IDisposable {
|
||||
y: (boundingBox.bottom - boundingBox.top + 1) / TEXTURE_HEIGHT
|
||||
},
|
||||
offset: {
|
||||
x: -boundingBox.left + (restrictedGlyph ? 0 : TMP_CANVAS_GLYPH_PADDING),
|
||||
y: -boundingBox.top + (restrictedGlyph ? 0 : TMP_CANVAS_GLYPH_PADDING)
|
||||
x: -boundingBox.left + (restrictedGlyph ? 0 : TMP_CANVAS_GLYPH_PADDING) + (customGlyph ? Math.floor(this._config.letterSpacing / 2) : 0),
|
||||
y: -boundingBox.top + (restrictedGlyph ? 0 : TMP_CANVAS_GLYPH_PADDING) + (customGlyph ? this._config.lineHeight === 1 ? 0 : Math.round((this._config.scaledCellHeight - this._config.scaledCharHeight) / 2) : 0)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ export abstract class BaseRenderLayer implements IRenderLayer {
|
||||
if (this._scaledCharWidth <= 0 && this._scaledCharHeight <= 0) {
|
||||
return;
|
||||
}
|
||||
this._charAtlas = acquireCharAtlas(terminal, colorSet, this._scaledCharWidth, this._scaledCharHeight);
|
||||
this._charAtlas = acquireCharAtlas(terminal, colorSet, this._scaledCellWidth, this._scaledCellHeight, this._scaledCharWidth, this._scaledCharHeight);
|
||||
this._charAtlas.warmUp();
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Terminal } from 'xterm';
|
||||
import { BaseRenderLayer } from './BaseRenderLayer';
|
||||
import { ICellData } from 'common/Types';
|
||||
import { CellData } from 'common/buffer/CellData';
|
||||
import { IColorSet } from 'browser/Types';
|
||||
import { IColorSet, ITerminal } from 'browser/Types';
|
||||
import { IRenderDimensions, IRequestRedrawEvent } from 'browser/renderer/Types';
|
||||
import { IEventEmitter } from 'common/EventEmitter';
|
||||
|
||||
@@ -34,6 +34,7 @@ export class CursorRenderLayer extends BaseRenderLayer {
|
||||
container: HTMLElement,
|
||||
zIndex: number,
|
||||
colors: IColorSet,
|
||||
private readonly _terminal: ITerminal,
|
||||
private _onRequestRefreshRowsEvent: IEventEmitter<IRequestRedrawEvent>
|
||||
) {
|
||||
super(container, 'cursor', zIndex, true, colors);
|
||||
@@ -120,7 +121,7 @@ export class CursorRenderLayer extends BaseRenderLayer {
|
||||
private _render(terminal: Terminal, triggeredByAnimationFrame: boolean): void {
|
||||
// Don't draw the cursor if it's hidden
|
||||
// TODO: Need to expose API for this
|
||||
if (!(terminal as any)._core._coreService.isCursorInitialized || (terminal as any)._core._coreService.isCursorHidden) {
|
||||
if (!this._terminal.coreService.isCursorInitialized || this._terminal.coreService.isCursorHidden) {
|
||||
this._clearCursor();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
import { ITerminalOptions } from '../../../src/common/Types';
|
||||
import { ITheme } from 'xterm';
|
||||
import { assert } from 'chai';
|
||||
import { openTerminal, pollFor, writeSync, getBrowserType } from '../../../out-test/api/TestUtils';
|
||||
import { Browser, Page } from 'playwright';
|
||||
import { ITheme } from 'xterm';
|
||||
import { getBrowserType, openTerminal, pollFor, writeSync } from '../../../out-test/api/TestUtils';
|
||||
import { ITerminalOptions } from '../../../src/common/Types';
|
||||
|
||||
const APP = 'http://127.0.0.1:3001/test';
|
||||
|
||||
@@ -890,6 +890,20 @@ async function getCellColor(col: number, row: number): Promise<number[]> {
|
||||
return await page.evaluate(`Array.from(window.result)`);
|
||||
}
|
||||
|
||||
async function getCellPixels(col: number, row: number): Promise<number[]> {
|
||||
await page.evaluate(`
|
||||
window.gl = window.term._core._renderService._renderer._gl;
|
||||
window.result = new Uint8Array(window.d.scaledCellWidth * window.d.scaledCellHeight * 4);
|
||||
window.d = window.term._core._renderService.dimensions;
|
||||
window.gl.readPixels(
|
||||
Math.floor(${col - 1} * window.d.scaledCellWidth),
|
||||
Math.floor(window.gl.drawingBufferHeight - ${row} * window.d.scaledCellHeight),
|
||||
window.d.scaledCellWidth, window.d.scaledCellHeight, window.gl.RGBA, window.gl.UNSIGNED_BYTE, window.result
|
||||
);
|
||||
`);
|
||||
return await page.evaluate(`Array.from(window.result)`);
|
||||
}
|
||||
|
||||
async function setupBrowser(options: ITerminalOptions = { rendererType: 'dom' }): Promise<void> {
|
||||
const browserType = getBrowserType();
|
||||
browser = await browserType.launch({
|
||||
|
||||
@@ -164,5 +164,9 @@ jobs:
|
||||
displayName: Cache node modules
|
||||
- script: yarn --frozen-lockfile
|
||||
displayName: 'Install dependencies and build'
|
||||
- script: |
|
||||
yarn package-headless
|
||||
node ./bin/package_headless.js
|
||||
displayName: 'Package xterm-headless'
|
||||
- script: NPM_AUTH_TOKEN="$(NPM_AUTH_TOKEN)" node ./bin/publish.js
|
||||
displayName: 'Package and publish to npm'
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Copyright (c) 2021 The xterm.js authors. All rights reserved.
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
const { exec } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const { join } = require('path');
|
||||
|
||||
const repoRoot = join(__dirname, '..');
|
||||
const headlessRoot = join(repoRoot, 'headless');
|
||||
|
||||
console.log('> headless/package.json');
|
||||
const xtermPackageJson = require('../package.json');
|
||||
const xtermHeadlessPackageJson = {
|
||||
...xtermPackageJson,
|
||||
name: 'xterm-headless',
|
||||
description: 'A headless terminal component that runs in Node.js',
|
||||
main: 'lib-headless/xterm-headless.js',
|
||||
types: 'typings/xterm-headless.d.ts',
|
||||
};
|
||||
delete xtermHeadlessPackageJson['scripts'];
|
||||
delete xtermHeadlessPackageJson['devDependencies'];
|
||||
delete xtermHeadlessPackageJson['style'];
|
||||
fs.writeFileSync(join(headlessRoot, 'package.json'), JSON.stringify(xtermHeadlessPackageJson, null, 1));
|
||||
console.log(fs.readFileSync(join(headlessRoot, 'package.json')).toString());
|
||||
|
||||
console.log('> headless/typings/');
|
||||
mkdirF(join(headlessRoot, 'typings'));
|
||||
fs.copyFileSync(
|
||||
join(repoRoot, 'typings/xterm-headless.d.ts'),
|
||||
join(headlessRoot, 'typings/xterm-headless.d.ts')
|
||||
);
|
||||
|
||||
console.log('> headless/logo-full.png');
|
||||
fs.copyFileSync(
|
||||
join(repoRoot, 'logo-full.png'),
|
||||
join(headlessRoot, 'logo-full.png')
|
||||
);
|
||||
|
||||
function mkdirF(p) {
|
||||
if (!fs.existsSync(p)) {
|
||||
fs.mkdirSync(p);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('> Publish dry run');
|
||||
exec('npm publish --dry-run', { cwd: headlessRoot }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log(`error: ${error.message}`);
|
||||
return;
|
||||
}
|
||||
if (stderr) {
|
||||
console.error(`stderr:\n${stderr}`);
|
||||
}
|
||||
console.log(`stdout:\n${stdout}`);
|
||||
});
|
||||
@@ -22,6 +22,7 @@ const changedFiles = getChangedFilesInCommit('HEAD');
|
||||
let isStableRelease = false;
|
||||
if (changedFiles.some(e => e.search(/^addons\//) === -1)) {
|
||||
isStableRelease = checkAndPublishPackage(path.resolve(__dirname, '..'));
|
||||
checkAndPublishPackage(path.resolve(__dirname, '../headless'));
|
||||
}
|
||||
|
||||
// Publish addons if any files were changed inside of the addon
|
||||
|
||||
@@ -147,6 +147,7 @@ if (document.location.pathname === '/test') {
|
||||
createTerminal();
|
||||
document.getElementById('dispose').addEventListener('click', disposeRecreateButtonHandler);
|
||||
document.getElementById('serialize').addEventListener('click', serializeButtonHandler);
|
||||
document.getElementById('custom-glyph').addEventListener('click', writeCustomGlyphHandler);
|
||||
}
|
||||
|
||||
function createTerminal(): void {
|
||||
@@ -434,3 +435,49 @@ function serializeButtonHandler(): void {
|
||||
term.write(output);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function writeCustomGlyphHandler() {
|
||||
term.write('\n\r');
|
||||
term.write('\n\r');
|
||||
term.write('Box styles: ┎┰┒┍┯┑╓╥╖╒╤╕ ┏┳┓┌┲┓┌┬┐┏┱┐\n\r');
|
||||
term.write('┌─┬─┐ ┏━┳━┓ ╔═╦═╗ ┠╂┨┝┿┥╟╫╢╞╪╡ ┡╇┩├╊┫┢╈┪┣╉┤\n\r');
|
||||
term.write('│ │ │ ┃ ┃ ┃ ║ ║ ║ ┖┸┚┕┷┙╙╨╜╘╧╛ └┴┘└┺┛┗┻┛┗┹┘\n\r');
|
||||
term.write('├─┼─┤ ┣━╋━┫ ╠═╬═╣ ┏┱┐┌┲┓┌┬┐┌┬┐ ┏┳┓┌┮┓┌┬┐┏┭┐\n\r');
|
||||
term.write('│ │ │ ┃ ┃ ┃ ║ ║ ║ ┡╃┤├╄┩├╆┪┢╅┤ ┞╀┦├┾┫┟╁┧┣┽┤\n\r');
|
||||
term.write('└─┴─┘ ┗━┻━┛ ╚═╩═╝ └┴┘└┴┘└┺┛┗┹┘ └┴┘└┶┛┗┻┛┗┵┘\n\r');
|
||||
term.write('\n\r');
|
||||
term.write('Other:\n\r');
|
||||
term.write('╭─╮ ╲ ╱ ╷╻╎╏┆┇┊┋ ╺╾╴ ╌╌╌ ┄┄┄ ┈┈┈\n\r');
|
||||
term.write('│ │ ╳ ╽╿╎╏┆┇┊┋ ╶╼╸ ╍╍╍ ┅┅┅ ┉┉┉\n\r');
|
||||
term.write('╰─╯ ╱ ╲ ╹╵╎╏┆┇┊┋\n\r');
|
||||
term.write('\n\r');
|
||||
term.write('All box drawing characters:\n\r');
|
||||
term.write('─ ━ │ ┃ ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ ┌ ┍ ┎ ┏\n\r');
|
||||
term.write('┐ ┑ ┒ ┓ └ ┕ ┖ ┗ ┘ ┙ ┚ ┛ ├ ┝ ┞ ┟\n\r');
|
||||
term.write('┠ ┡ ┢ ┣ ┤ ┥ ┦ ┧ ┨ ┩ ┪ ┫ ┬ ┭ ┮ ┯\n\r');
|
||||
term.write('┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻ ┼ ┽ ┾ ┿\n\r');
|
||||
term.write('╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╌ ╍ ╎ ╏\n\r');
|
||||
term.write('═ ║ ╒ ╓ ╔ ╕ ╖ ╗ ╘ ╙ ╚ ╛ ╜ ╝ ╞ ╟\n\r');
|
||||
term.write('╠ ╡ ╢ ╣ ╤ ╥ ╦ ╧ ╨ ╩ ╪ ╫ ╬ ╭ ╮ ╯\n\r');
|
||||
term.write('╰ ╱ ╲ ╳ ╴ ╵ ╶ ╷ ╸ ╹ ╺ ╻ ╼ ╽ ╾ ╿\n\r');
|
||||
term.write('Box drawing alignment tests:\x1b[31m █\n\r');
|
||||
term.write(' ▉\n\r');
|
||||
term.write(' ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳\n\r');
|
||||
term.write(' ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳\n\r');
|
||||
term.write(' ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳\n\r');
|
||||
term.write(' ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳\n\r');
|
||||
term.write(' ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎\n\r');
|
||||
term.write(' ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏\n\r');
|
||||
term.write(' ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█\n\r');
|
||||
term.write('Box drawing alignment tests:\x1b[32m █\n\r');
|
||||
term.write(' ▉\n\r');
|
||||
term.write(' ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳\n\r');
|
||||
term.write(' ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳\n\r');
|
||||
term.write(' ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳\n\r');
|
||||
term.write(' ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳\n\r');
|
||||
term.write(' ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎\n\r');
|
||||
term.write(' ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏\n\r');
|
||||
term.write(' ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█\n\r');
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
</div>
|
||||
<hr/>
|
||||
<button id="dispose" title="This is used to testing memory leaks">Dispose terminal</button>
|
||||
<button id="custom-glyph" title="Write custom box drawing and block element characters to the terminal">Test custom glyphs</button>
|
||||
<script src="dist/client-bundle.js" defer ></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
lib-headless/
|
||||
typings/
|
||||
logo-full.png
|
||||
./package.json
|
||||
@@ -0,0 +1,6 @@
|
||||
# Include
|
||||
!typings/*.d.ts
|
||||
!lib-headless/
|
||||
|
||||
# Exclude
|
||||
test/
|
||||
@@ -0,0 +1,31 @@
|
||||
# [](https://xtermjs.org)
|
||||
|
||||
⚠ This package is experimental
|
||||
|
||||
`xterm-headless` is a headless terminal that can be run in node.js. This is useful in combination with the frontend [`xterm`](https://www.npmjs.com/package/xterm) for example to keep track of a terminal's state on a remote server where the process is hosted.
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, you need to install the module, we ship exclusively through npm, so you need that installed and then add xterm.js as a dependency by running:
|
||||
|
||||
```sh
|
||||
npm install xterm-headless
|
||||
```
|
||||
|
||||
Then import as you would a regular node package. The recommended way to load `xterm-headless` is with TypeScript and the ES6 module syntax:
|
||||
|
||||
```javascript
|
||||
import { Terminal } from 'xterm-headless';
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
The full API for `xterm-headless` is contained within the [TypeScript declaration file](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm-headless.d.ts), use the branch/tag picker in GitHub (`w`) to navigate to the correct version of the API.
|
||||
|
||||
Note that some APIs are marked *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.
|
||||
|
||||
### Addons
|
||||
|
||||
Addons in `xterm-headless` work the [same as in `xterm`](https://github.com/xtermjs/xterm.js/blob/master/README.md#addons) with the one caveat being that the addon needs to be packaged for node.js and not use any DOM APIs.
|
||||
|
||||
Currently no official addons are packaged on npm.
|
||||
@@ -10,6 +10,8 @@
|
||||
"scripts": {
|
||||
"prepackage": "npm run build",
|
||||
"package": "webpack",
|
||||
"package-headless": "webpack --config ./webpack.config.headless.js",
|
||||
"postpackage-headless": "node ./bin/package_headless.js",
|
||||
"start": "node demo/start",
|
||||
"start-debug": "node --inspect-brk demo/start",
|
||||
"lint": "eslint -c .eslintrc.json --max-warnings 0 --ext .ts src/ addons/",
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
*/
|
||||
|
||||
import * as Strings from 'browser/LocalizableStrings';
|
||||
import { ITerminal } from 'browser/Types';
|
||||
import { ITerminal, IRenderDebouncer } from 'browser/Types';
|
||||
import { IBuffer } from 'common/buffer/Types';
|
||||
import { isMac } from 'common/Platform';
|
||||
import { RenderDebouncer } from 'browser/RenderDebouncer';
|
||||
import { TimeBasedDebouncer } from 'browser/TimeBasedDebouncer';
|
||||
import { addDisposableDomListener } from 'browser/Lifecycle';
|
||||
import { Disposable } from 'common/Lifecycle';
|
||||
import { ScreenDprMonitor } from 'browser/ScreenDprMonitor';
|
||||
@@ -28,7 +28,7 @@ export class AccessibilityManager extends Disposable {
|
||||
private _liveRegion: HTMLElement;
|
||||
private _liveRegionLineCount: number = 0;
|
||||
|
||||
private _renderRowsDebouncer: RenderDebouncer;
|
||||
private _renderRowsDebouncer: IRenderDebouncer;
|
||||
private _screenDprMonitor: ScreenDprMonitor;
|
||||
|
||||
private _topBoundaryFocusListener: (e: FocusEvent) => void;
|
||||
@@ -72,7 +72,7 @@ export class AccessibilityManager extends Disposable {
|
||||
this._refreshRowsDimensions();
|
||||
this._accessibilityTreeRoot.appendChild(this._rowContainer);
|
||||
|
||||
this._renderRowsDebouncer = new RenderDebouncer(this._renderRows.bind(this));
|
||||
this._renderRowsDebouncer = new TimeBasedDebouncer(this._renderRows.bind(this));
|
||||
this._refreshRows();
|
||||
|
||||
this._liveRegion = document.createElement('div');
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
import { IDisposable } from 'common/Types';
|
||||
import { IRenderDebouncer } from 'browser/Types';
|
||||
|
||||
/**
|
||||
* Debounces calls to render terminal rows using animation frames.
|
||||
*/
|
||||
export class RenderDebouncer implements IDisposable {
|
||||
export class RenderDebouncer implements IRenderDebouncer {
|
||||
private _rowStart: number | undefined;
|
||||
private _rowEnd: number | undefined;
|
||||
private _rowCount: number | undefined;
|
||||
|
||||
+80
-28
@@ -94,6 +94,20 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
*/
|
||||
private _keyDownHandled: boolean = false;
|
||||
|
||||
/**
|
||||
* Records whether the keypress event has already been handled and triggered a data event, if so
|
||||
* the input event should not trigger a data event but should still print to the textarea so
|
||||
* screen readers will announce it.
|
||||
*/
|
||||
private _keyPressHandled: boolean = false;
|
||||
|
||||
/**
|
||||
* Records whether there has been a keydown event for a dead key without a corresponding keydown
|
||||
* event for the composed/alternative character. If we cancel the keydown event for the dead key,
|
||||
* no events will be emitted for the final character.
|
||||
*/
|
||||
private _unprocessedDeadKey: boolean = false;
|
||||
|
||||
public linkifier: ILinkifier;
|
||||
public linkifier2: ILinkifier2;
|
||||
public viewport: IViewport | undefined;
|
||||
@@ -113,8 +127,8 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }
|
||||
private _onTitleChange = new EventEmitter<string>();
|
||||
public get onTitleChange(): IEvent<string> { return this._onTitleChange.event; }
|
||||
private _onBell = new EventEmitter<void>();
|
||||
public get onBell (): IEvent<void> { return this._onBell.event; }
|
||||
private _onBell = new EventEmitter<void>();
|
||||
public get onBell(): IEvent<void> { return this._onBell.event; }
|
||||
|
||||
private _onFocus = new EventEmitter<void>();
|
||||
public get onFocus(): IEvent<void> { return this._onFocus.event; }
|
||||
@@ -224,6 +238,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
// The DOM renderer needs a row refresh to update the cursor styles
|
||||
this.refresh(this.buffer.y, this.buffer.y);
|
||||
break;
|
||||
case 'customGlyphs':
|
||||
case 'drawBoldTextInBrightColors':
|
||||
case 'letterSpacing':
|
||||
case 'lineHeight':
|
||||
@@ -267,8 +282,8 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
* Binds the desired focus behavior on a given terminal object.
|
||||
*/
|
||||
private _onTextAreaFocus(ev: KeyboardEvent): void {
|
||||
if (this._coreService.decPrivateModes.sendFocus) {
|
||||
this._coreService.triggerDataEvent(C0.ESC + '[I');
|
||||
if (this.coreService.decPrivateModes.sendFocus) {
|
||||
this.coreService.triggerDataEvent(C0.ESC + '[I');
|
||||
}
|
||||
this.updateCursorStyle(ev);
|
||||
this.element!.classList.add('focus');
|
||||
@@ -292,8 +307,8 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
// screen readers reading it out.
|
||||
this.textarea!.value = '';
|
||||
this.refresh(this.buffer.y, this.buffer.y);
|
||||
if (this._coreService.decPrivateModes.sendFocus) {
|
||||
this._coreService.triggerDataEvent(C0.ESC + '[O');
|
||||
if (this.coreService.decPrivateModes.sendFocus) {
|
||||
this.coreService.triggerDataEvent(C0.ESC + '[O');
|
||||
}
|
||||
this.element!.classList.remove('focus');
|
||||
this._onBlur.fire();
|
||||
@@ -340,7 +355,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
}
|
||||
copyHandler(event, this._selectionService!);
|
||||
}));
|
||||
const pasteHandlerWrapper = (event: ClipboardEvent): void => handlePasteEvent(event, this.textarea!, this._coreService);
|
||||
const pasteHandlerWrapper = (event: ClipboardEvent): void => handlePasteEvent(event, this.textarea!, this.coreService);
|
||||
this.register(addDisposableDomListener(this.textarea!, 'paste', pasteHandlerWrapper));
|
||||
this.register(addDisposableDomListener(this.element!, 'paste', pasteHandlerWrapper));
|
||||
|
||||
@@ -382,6 +397,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
this.register(addDisposableDomListener(this.textarea!, 'compositionstart', () => this._compositionHelper!.compositionstart()));
|
||||
this.register(addDisposableDomListener(this.textarea!, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper!.compositionupdate(e)));
|
||||
this.register(addDisposableDomListener(this.textarea!, 'compositionend', () => this._compositionHelper!.compositionend()));
|
||||
this.register(addDisposableDomListener(this.textarea!, 'input', (ev: InputEvent) => this._inputEvent(ev), true));
|
||||
this.register(this.onRender(() => this._compositionHelper!.updateCompositionElements()));
|
||||
this.register(this.onRender(e => this._queueLinkification(e.start, e.end)));
|
||||
}
|
||||
@@ -408,7 +424,6 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
this.element.classList.add('terminal');
|
||||
this.element.classList.add('xterm');
|
||||
this.element.setAttribute('tabindex', '0');
|
||||
this.element.setAttribute('role', 'document');
|
||||
parent.appendChild(this.element);
|
||||
|
||||
// Performance: Use a document fragment to build the terminal
|
||||
@@ -526,7 +541,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
this.register(addDisposableDomListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService!.onMouseDown(e)));
|
||||
|
||||
// apply mouse event classes set by escape codes before terminal was attached
|
||||
if (this._coreMouseService.areMouseEventsActive) {
|
||||
if (this.coreMouseService.areMouseEventsActive) {
|
||||
this._selectionService.disable();
|
||||
this.element.classList.add('enable-mouse-events');
|
||||
} else {
|
||||
@@ -644,7 +659,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
return false;
|
||||
}
|
||||
|
||||
return self._coreMouseService.triggerMouseEvent({
|
||||
return self.coreMouseService.triggerMouseEvent({
|
||||
col: pos.x - 33, // FIXME: why -33 here?
|
||||
row: pos.y - 33,
|
||||
button: but,
|
||||
@@ -699,11 +714,11 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
}
|
||||
}
|
||||
};
|
||||
this.register(this._coreMouseService.onProtocolChange(events => {
|
||||
this.register(this.coreMouseService.onProtocolChange(events => {
|
||||
// apply global changes on events
|
||||
if (events) {
|
||||
if (this.optionsService.options.logLevel === 'debug') {
|
||||
this._logService.debug('Binding to mouse events:', this._coreMouseService.explainEvents(events));
|
||||
this._logService.debug('Binding to mouse events:', this.coreMouseService.explainEvents(events));
|
||||
}
|
||||
this.element!.classList.add('enable-mouse-events');
|
||||
this._selectionService!.disable();
|
||||
@@ -746,7 +761,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
}
|
||||
}));
|
||||
// force initial onProtocolChange so we dont miss early mouse requests
|
||||
this._coreMouseService.activeProtocol = this._coreMouseService.activeProtocol;
|
||||
this.coreMouseService.activeProtocol = this.coreMouseService.activeProtocol;
|
||||
|
||||
/**
|
||||
* "Always on" event listeners.
|
||||
@@ -758,7 +773,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
// Don't send the mouse button to the pty if mouse events are disabled or
|
||||
// if the selection manager is having selection forced (ie. a modifier is
|
||||
// held).
|
||||
if (!this._coreMouseService.areMouseEventsActive || this._selectionService!.shouldForceSelection(ev)) {
|
||||
if (!this.coreMouseService.areMouseEventsActive || this._selectionService!.shouldForceSelection(ev)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -791,12 +806,12 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
}
|
||||
|
||||
// Construct and send sequences
|
||||
const sequence = C0.ESC + (this._coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B');
|
||||
const sequence = C0.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B');
|
||||
let data = '';
|
||||
for (let i = 0; i < Math.abs(amount); i++) {
|
||||
data += sequence;
|
||||
}
|
||||
this._coreService.triggerDataEvent(data, true);
|
||||
this.coreService.triggerDataEvent(data, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -812,13 +827,13 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
}, { passive: false }));
|
||||
|
||||
this.register(addDisposableDomListener(el, 'touchstart', (ev: TouchEvent) => {
|
||||
if (this._coreMouseService.areMouseEventsActive) return;
|
||||
if (this.coreMouseService.areMouseEventsActive) return;
|
||||
this.viewport!.onTouchStart(ev);
|
||||
return this.cancel(ev);
|
||||
}, { passive: true }));
|
||||
|
||||
this.register(addDisposableDomListener(el, 'touchmove', (ev: TouchEvent) => {
|
||||
if (this._coreMouseService.areMouseEventsActive) return;
|
||||
if (this.coreMouseService.areMouseEventsActive) return;
|
||||
if (!this.viewport!.onTouchMove(ev)) {
|
||||
return this.cancel(ev);
|
||||
}
|
||||
@@ -860,8 +875,8 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
* Display the cursor element
|
||||
*/
|
||||
private _showCursor(): void {
|
||||
if (!this._coreService.isCursorInitialized) {
|
||||
this._coreService.isCursorInitialized = true;
|
||||
if (!this.coreService.isCursorInitialized) {
|
||||
this.coreService.isCursorInitialized = true;
|
||||
this.refresh(this.buffer.y, this.buffer.y);
|
||||
}
|
||||
}
|
||||
@@ -872,7 +887,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
}
|
||||
|
||||
public paste(data: string): void {
|
||||
paste(data, this.textarea!, this._coreService);
|
||||
paste(data, this.textarea!, this.coreService);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1025,7 +1040,11 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = evaluateKeyboardEvent(event, this._coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);
|
||||
if (event.key === 'Dead' || event.key === 'AltGraph') {
|
||||
this._unprocessedDeadKey = true;
|
||||
}
|
||||
|
||||
const result = evaluateKeyboardEvent(event, this.coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);
|
||||
|
||||
this.updateCursorStyle(event);
|
||||
|
||||
@@ -1052,6 +1071,11 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this._unprocessedDeadKey) {
|
||||
this._unprocessedDeadKey = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers
|
||||
// will announce deleted characters. This will not work 100% of the time but it should cover
|
||||
// most scenarios.
|
||||
@@ -1061,7 +1085,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
|
||||
this._onKey.fire({ key: result.key, domEvent: event });
|
||||
this._showCursor();
|
||||
this._coreService.triggerDataEvent(result.key, true);
|
||||
this.coreService.triggerDataEvent(result.key, true);
|
||||
|
||||
// Cancel events when not in screen reader mode so events don't get bubbled up and handled by
|
||||
// other listeners. When screen reader mode is enabled, this could cause issues if the event
|
||||
@@ -1074,10 +1098,11 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
this._keyDownHandled = true;
|
||||
}
|
||||
|
||||
private _isThirdLevelShift(browser: IBrowser, ev: IKeyboardEvent): boolean {
|
||||
private _isThirdLevelShift(browser: IBrowser, ev: KeyboardEvent): boolean {
|
||||
const thirdLevelKey =
|
||||
(browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
|
||||
(browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
|
||||
(browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey) ||
|
||||
(browser.isWindows && ev.getModifierState('AltGraph'));
|
||||
|
||||
if (ev.type === 'keypress') {
|
||||
return thirdLevelKey;
|
||||
@@ -1097,6 +1122,7 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
}
|
||||
|
||||
this.updateCursorStyle(ev);
|
||||
this._keyPressHandled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1108,6 +1134,8 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
protected _keyPress(ev: KeyboardEvent): boolean {
|
||||
let key;
|
||||
|
||||
this._keyPressHandled = false;
|
||||
|
||||
if (this._keyDownHandled) {
|
||||
return false;
|
||||
}
|
||||
@@ -1138,11 +1166,35 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
|
||||
this._onKey.fire({ key, domEvent: ev });
|
||||
this._showCursor();
|
||||
this._coreService.triggerDataEvent(key, true);
|
||||
this.coreService.triggerDataEvent(key, true);
|
||||
|
||||
this._keyPressHandled = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an input event.
|
||||
* Key Resources:
|
||||
* - https://developer.mozilla.org/en-US/docs/Web/API/InputEvent
|
||||
* @param ev The input event to be handled.
|
||||
*/
|
||||
protected _inputEvent(ev: InputEvent): boolean {
|
||||
if (ev.data && ev.inputType === 'insertText') {
|
||||
if (this._keyPressHandled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const text = ev.data;
|
||||
this.coreService.triggerDataEvent(text, true);
|
||||
|
||||
this.cancel(ev);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ring the bell.
|
||||
* Note: We could do sweet things with webaudio here
|
||||
@@ -1247,12 +1299,12 @@ export class Terminal extends CoreTerminal implements ITerminal {
|
||||
case WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:
|
||||
const canvasWidth = this._renderService.dimensions.scaledCanvasWidth.toFixed(0);
|
||||
const canvasHeight = this._renderService.dimensions.scaledCanvasHeight.toFixed(0);
|
||||
this._coreService.triggerDataEvent(`${C0.ESC}[4;${canvasHeight};${canvasWidth}t`);
|
||||
this.coreService.triggerDataEvent(`${C0.ESC}[4;${canvasHeight};${canvasWidth}t`);
|
||||
break;
|
||||
case WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:
|
||||
const cellWidth = this._renderService.dimensions.scaledCellWidth.toFixed(0);
|
||||
const cellHeight = this._renderService.dimensions.scaledCellHeight.toFixed(0);
|
||||
this._coreService.triggerDataEvent(`${C0.ESC}[6;${cellHeight};${cellWidth}t`);
|
||||
this.coreService.triggerDataEvent(`${C0.ESC}[6;${cellHeight};${cellWidth}t`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import { IBufferLine, ICellData, IAttributeData, ICircularList, XtermListener, I
|
||||
import { Buffer } from 'common/buffer/Buffer';
|
||||
import * as Browser from 'common/Platform';
|
||||
import { Terminal } from 'browser/Terminal';
|
||||
import { IUnicodeService, IOptionsService } from 'common/services/Services';
|
||||
import { IUnicodeService, IOptionsService, ICoreService, ICoreMouseService } from 'common/services/Services';
|
||||
import { IFunctionIdentifier, IParams } from 'common/parser/Types';
|
||||
import { AttributeData } from 'common/buffer/AttributeData';
|
||||
|
||||
@@ -43,6 +43,8 @@ export class MockTerminal implements ITerminal {
|
||||
public onRender!: IEvent<{ start: number, end: number }>;
|
||||
public onResize!: IEvent<{ cols: number, rows: number }>;
|
||||
public markers!: IMarker[];
|
||||
public coreMouseService!: ICoreMouseService;
|
||||
public coreService!: ICoreService;
|
||||
public optionsService!: IOptionsService;
|
||||
public unicodeService!: IUnicodeService;
|
||||
public addMarker(cursorYOffset: number): IMarker {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
const RENDER_DEBOUNCE_THRESHOLD_MS = 1000; // 1 Second
|
||||
|
||||
import { IRenderDebouncer } from 'browser/Types';
|
||||
|
||||
/**
|
||||
* Debounces calls to update screen readers to update at most once configurable interval of time.
|
||||
*/
|
||||
export class TimeBasedDebouncer implements IRenderDebouncer {
|
||||
private _rowStart: number | undefined;
|
||||
private _rowEnd: number | undefined;
|
||||
private _rowCount: number | undefined;
|
||||
|
||||
// The last moment that the Terminal was refreshed at
|
||||
private _lastRefreshMs = 0;
|
||||
// Whether a trailing refresh should be triggered due to a refresh request that was throttled
|
||||
private _additionalRefreshRequested = false;
|
||||
|
||||
private _refreshTimeoutID: number | undefined;
|
||||
|
||||
constructor(
|
||||
private _renderCallback: (start: number, end: number) => void,
|
||||
private readonly _debounceThresholdMS = RENDER_DEBOUNCE_THRESHOLD_MS
|
||||
) {
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
if (this._refreshTimeoutID) {
|
||||
clearTimeout(this._refreshTimeoutID);
|
||||
}
|
||||
}
|
||||
|
||||
public refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void {
|
||||
this._rowCount = rowCount;
|
||||
// Get the min/max row start/end for the arg values
|
||||
rowStart = rowStart !== undefined ? rowStart : 0;
|
||||
rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;
|
||||
// Set the properties to the updated values
|
||||
this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;
|
||||
this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;
|
||||
|
||||
// Only refresh if the time since last refresh is above a threshold, otherwise wait for
|
||||
// enough time to pass before refreshing again.
|
||||
const refreshRequestTime: number = Date.now();
|
||||
if (refreshRequestTime - this._lastRefreshMs >= this._debounceThresholdMS) {
|
||||
// Enough time has lapsed since the last refresh; refresh immediately
|
||||
this._lastRefreshMs = refreshRequestTime;
|
||||
this._innerRefresh();
|
||||
} else if (!this._additionalRefreshRequested) {
|
||||
// This is the first additional request throttled; set up trailing refresh
|
||||
const elapsed = refreshRequestTime - this._lastRefreshMs;
|
||||
const waitPeriodBeforeTrailingRefresh = this._debounceThresholdMS - elapsed;
|
||||
this._additionalRefreshRequested = true;
|
||||
|
||||
this._refreshTimeoutID = window.setTimeout(() => {
|
||||
this._lastRefreshMs = Date.now();
|
||||
this._innerRefresh();
|
||||
this._additionalRefreshRequested = false;
|
||||
this._refreshTimeoutID = undefined; // No longer need to clear the timeout
|
||||
}, waitPeriodBeforeTrailingRefresh);
|
||||
}
|
||||
}
|
||||
|
||||
private _innerRefresh(): void {
|
||||
// Make sure values are set
|
||||
if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clamp values
|
||||
const start = Math.max(this._rowStart, 0);
|
||||
const end = Math.min(this._rowEnd, this._rowCount - 1);
|
||||
|
||||
// Reset debouncer (this happens before render callback as the render could trigger it again)
|
||||
this._rowStart = undefined;
|
||||
this._rowEnd = undefined;
|
||||
|
||||
// Run render callback
|
||||
this._renderCallback(start, end);
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+4
@@ -309,3 +309,7 @@ export interface ICharacterJoiner {
|
||||
id: number;
|
||||
handler: CharacterJoinerHandler;
|
||||
}
|
||||
|
||||
export interface IRenderDebouncer extends IDisposable {
|
||||
refresh(rowStart: number | undefined, rowEnd: number | undefined, rowCount: number): void;
|
||||
}
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
import { Terminal as ITerminalApi, ITerminalOptions, IMarker, IDisposable, ILinkMatcherOptions, ITheme, ILocalizableStrings, ITerminalAddon, ISelectionPosition, IBufferNamespace as IBufferNamespaceApi, IParser, ILinkProvider, IUnicodeHandling, FontWeight } from 'xterm';
|
||||
import { Terminal as ITerminalApi, ITerminalOptions, IMarker, IDisposable, ILinkMatcherOptions, ITheme, ILocalizableStrings, ITerminalAddon, ISelectionPosition, IBufferNamespace as IBufferNamespaceApi, IParser, ILinkProvider, IUnicodeHandling, FontWeight, IModes } from 'xterm';
|
||||
import { ITerminal } from 'browser/Types';
|
||||
import { Terminal as TerminalCore } from '../Terminal';
|
||||
import * as Strings from '../LocalizableStrings';
|
||||
import { Terminal as TerminalCore } from 'browser/Terminal';
|
||||
import * as Strings from 'browser/LocalizableStrings';
|
||||
import { IEvent } from 'common/EventEmitter';
|
||||
import { ParserApi } from 'common/public/ParserApi';
|
||||
import { UnicodeApi } from 'common/public/UnicodeApi';
|
||||
import { AddonManager } from './AddonManager';
|
||||
import { AddonManager } from 'common/public/AddonManager';
|
||||
import { BufferNamespaceApi } from 'common/public/BufferNamespaceApi';
|
||||
|
||||
export class Terminal implements ITerminalApi {
|
||||
@@ -30,17 +30,17 @@ export class Terminal implements ITerminalApi {
|
||||
}
|
||||
}
|
||||
|
||||
public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }
|
||||
public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }
|
||||
public get onSelectionChange(): IEvent<void> { return this._core.onSelectionChange; }
|
||||
public get onData(): IEvent<string> { return this._core.onData; }
|
||||
public get onBinary(): IEvent<string> { return this._core.onBinary; }
|
||||
public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }
|
||||
public get onBell(): IEvent<void> { return this._core.onBell; }
|
||||
public get onScroll(): IEvent<number> { return this._core.onScroll; }
|
||||
public get onBinary(): IEvent<string> { return this._core.onBinary; }
|
||||
public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }
|
||||
public get onData(): IEvent<string> { return this._core.onData; }
|
||||
public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }
|
||||
public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }
|
||||
public get onRender(): IEvent<{ start: number, end: number }> { return this._core.onRender; }
|
||||
public get onResize(): IEvent<{ cols: number, rows: number }> { return this._core.onResize; }
|
||||
public get onScroll(): IEvent<number> { return this._core.onScroll; }
|
||||
public get onSelectionChange(): IEvent<void> { return this._core.onSelectionChange; }
|
||||
public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }
|
||||
|
||||
public get element(): HTMLElement | undefined { return this._core.element; }
|
||||
public get parser(): IParser {
|
||||
@@ -68,6 +68,27 @@ export class Terminal implements ITerminalApi {
|
||||
this._checkProposedApi();
|
||||
return this._core.markers;
|
||||
}
|
||||
public get modes(): IModes {
|
||||
const m = this._core.coreService.decPrivateModes;
|
||||
let mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any' = 'none';
|
||||
switch (this._core.coreMouseService.activeProtocol) {
|
||||
case 'X10': mouseTrackingMode = 'x10'; break;
|
||||
case 'VT200': mouseTrackingMode = 'vt200'; break;
|
||||
case 'DRAG': mouseTrackingMode = 'drag'; break;
|
||||
case 'ANY': mouseTrackingMode = 'any'; break;
|
||||
}
|
||||
return {
|
||||
applicationCursorKeysMode: m.applicationCursorKeys,
|
||||
applicationKeypadMode: m.applicationKeypad,
|
||||
bracketedPasteMode: m.bracketedPasteMode,
|
||||
insertMode: this._core.coreService.modes.insertMode,
|
||||
mouseTrackingMode: mouseTrackingMode,
|
||||
originMode: m.origin,
|
||||
reverseWraparoundMode: m.reverseWraparound,
|
||||
sendFocusMode: m.sendFocus,
|
||||
wraparoundMode: m.wraparound
|
||||
};
|
||||
}
|
||||
public blur(): void {
|
||||
this._core.blur();
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import { IBufferService, IOptionsService } from 'common/services/Services';
|
||||
import { throwIfFalsy } from 'browser/renderer/RendererUtils';
|
||||
import { channels, color, rgba } from 'browser/Color';
|
||||
import { removeElementFromParent } from 'browser/Dom';
|
||||
import { tryDrawCustomChar } from 'browser/renderer/CustomGlyphs';
|
||||
|
||||
export abstract class BaseRenderLayer implements IRenderLayer {
|
||||
private _canvas: HTMLCanvasElement;
|
||||
@@ -259,10 +260,20 @@ export abstract class BaseRenderLayer implements IRenderLayer {
|
||||
this._ctx.font = this._getFont(false, false);
|
||||
this._ctx.textBaseline = 'ideographic';
|
||||
this._clipRow(y);
|
||||
this._ctx.fillText(
|
||||
cell.getChars(),
|
||||
x * this._scaledCellWidth + this._scaledCharLeft,
|
||||
y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight);
|
||||
|
||||
// Draw custom characters if applicable
|
||||
let drawSuccess = false;
|
||||
if (this._optionsService.options.customGlyphs !== false) {
|
||||
drawSuccess = tryDrawCustomChar(this._ctx, cell.getChars(), x * this._scaledCellWidth, y * this._scaledCellHeight, this._scaledCellWidth, this._scaledCellHeight);
|
||||
}
|
||||
|
||||
// Draw the character
|
||||
if (!drawSuccess) {
|
||||
this._ctx.fillText(
|
||||
cell.getChars(),
|
||||
x * this._scaledCellWidth + this._scaledCharLeft,
|
||||
y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -373,14 +384,25 @@ export abstract class BaseRenderLayer implements IRenderLayer {
|
||||
if (cell.isDim()) {
|
||||
this._ctx.globalAlpha = DIM_OPACITY;
|
||||
}
|
||||
|
||||
// Draw custom characters if applicable
|
||||
let drawSuccess = false;
|
||||
if (this._optionsService.options.customGlyphs !== false) {
|
||||
drawSuccess = tryDrawCustomChar(this._ctx, cell.getChars(), x * this._scaledCellWidth, y * this._scaledCellHeight, this._scaledCellWidth, this._scaledCellHeight);
|
||||
}
|
||||
|
||||
// Draw the character
|
||||
this._ctx.fillText(
|
||||
cell.getChars(),
|
||||
x * this._scaledCellWidth + this._scaledCharLeft,
|
||||
y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight);
|
||||
if (!drawSuccess) {
|
||||
this._ctx.fillText(
|
||||
cell.getChars(),
|
||||
x * this._scaledCellWidth + this._scaledCharLeft,
|
||||
y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight);
|
||||
}
|
||||
|
||||
this._ctx.restore();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Clips a row to ensure no pixels will be drawn outside the cells in the row.
|
||||
* @param y The row to clip.
|
||||
|
||||
@@ -58,6 +58,14 @@ export class CursorRenderLayer extends BaseRenderLayer {
|
||||
// TODO: Consider initial options? Maybe onOptionsChanged should be called at the end of open?
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
if (this._cursorBlinkStateManager) {
|
||||
this._cursorBlinkStateManager.dispose();
|
||||
this._cursorBlinkStateManager = undefined;
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
public resize(dim: IRenderDimensions): void {
|
||||
super.resize(dim);
|
||||
// Resizing the canvas discards the contents of the canvas so clear state
|
||||
|
||||
@@ -0,0 +1,563 @@
|
||||
/**
|
||||
* Copyright (c) 2021 The xterm.js authors. All rights reserved.
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
import { throwIfFalsy } from 'browser/renderer/RendererUtils';
|
||||
|
||||
interface IBlockVector {
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
export const blockElementDefinitions: { [index: string]: IBlockVector[] | undefined } = {
|
||||
// Block elements (0x2580-0x2590)
|
||||
'▀': [{ x: 0, y: 0, w: 8, h: 4 }], // UPPER HALF BLOCK
|
||||
'▁': [{ x: 0, y: 7, w: 8, h: 1 }], // LOWER ONE EIGHTH BLOCK
|
||||
'▂': [{ x: 0, y: 6, w: 8, h: 2 }], // LOWER ONE QUARTER BLOCK
|
||||
'▃': [{ x: 0, y: 5, w: 8, h: 3 }], // LOWER THREE EIGHTHS BLOCK
|
||||
'▄': [{ x: 0, y: 4, w: 8, h: 4 }], // LOWER HALF BLOCK
|
||||
'▅': [{ x: 0, y: 3, w: 8, h: 5 }], // LOWER FIVE EIGHTHS BLOCK
|
||||
'▆': [{ x: 0, y: 2, w: 8, h: 6 }], // LOWER THREE QUARTERS BLOCK
|
||||
'▇': [{ x: 0, y: 1, w: 8, h: 7 }], // LOWER SEVEN EIGHTHS BLOCK
|
||||
'█': [{ x: 0, y: 0, w: 8, h: 8 }], // FULL BLOCK
|
||||
'▉': [{ x: 0, y: 0, w: 7, h: 8 }], // LEFT SEVEN EIGHTHS BLOCK
|
||||
'▊': [{ x: 0, y: 0, w: 6, h: 8 }], // LEFT THREE QUARTERS BLOCK
|
||||
'▋': [{ x: 0, y: 0, w: 5, h: 8 }], // LEFT FIVE EIGHTHS BLOCK
|
||||
'▌': [{ x: 0, y: 0, w: 4, h: 8 }], // LEFT HALF BLOCK
|
||||
'▍': [{ x: 0, y: 0, w: 3, h: 8 }], // LEFT THREE EIGHTHS BLOCK
|
||||
'▎': [{ x: 0, y: 0, w: 2, h: 8 }], // LEFT ONE QUARTER BLOCK
|
||||
'▏': [{ x: 0, y: 0, w: 1, h: 8 }], // LEFT ONE EIGHTH BLOCK
|
||||
'▐': [{ x: 4, y: 0, w: 4, h: 8 }], // RIGHT HALF BLOCK
|
||||
|
||||
// Block elements (0x2594-0x2595)
|
||||
'▔': [{ x: 0, y: 0, w: 9, h: 1 }], // UPPER ONE EIGHTH BLOCK
|
||||
'▕': [{ x: 7, y: 0, w: 1, h: 8 }], // RIGHT ONE EIGHTH BLOCK
|
||||
|
||||
// Terminal graphic characters (0x2596-0x259F)
|
||||
'▖': [{ x: 0, y: 4, w: 4, h: 4 }], // QUADRANT LOWER LEFT
|
||||
'▗': [{ x: 4, y: 4, w: 4, h: 4 }], // QUADRANT LOWER RIGHT
|
||||
'▘': [{ x: 0, y: 0, w: 4, h: 4 }], // QUADRANT UPPER LEFT
|
||||
'▙': [{ x: 0, y: 0, w: 4, h: 8 }, { x: 0, y: 4, w: 8, h: 4 }], // QUADRANT UPPER LEFT AND LOWER LEFT AND LOWER RIGHT
|
||||
'▚': [{ x: 0, y: 0, w: 4, h: 4 }, { x: 4, y: 4, w: 4, h: 4 }], // QUADRANT UPPER LEFT AND LOWER RIGHT
|
||||
'▛': [{ x: 0, y: 0, w: 4, h: 8 }, { x: 0, y: 0, w: 4, h: 8 }], // QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER LEFT
|
||||
'▜': [{ x: 0, y: 0, w: 8, h: 4 }, { x: 4, y: 0, w: 4, h: 8 }], // QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER RIGHT
|
||||
'▝': [{ x: 4, y: 0, w: 4, h: 4 }], // QUADRANT UPPER RIGHT
|
||||
'▞': [{ x: 4, y: 0, w: 4, h: 4 }, { x: 0, y: 4, w: 4, h: 4 }], // QUADRANT UPPER RIGHT AND LOWER LEFT
|
||||
'▟': [{ x: 4, y: 0, w: 4, h: 8 }, { x: 0, y: 4, w: 8, h: 4 }], // QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT
|
||||
|
||||
// VERTICAL ONE EIGHTH BLOCK-2 through VERTICAL ONE EIGHTH BLOCK-7
|
||||
'\u{1FB70}': [{ x: 1, y: 0, w: 1, h: 8 }],
|
||||
'\u{1FB71}': [{ x: 2, y: 0, w: 1, h: 8 }],
|
||||
'\u{1FB72}': [{ x: 3, y: 0, w: 1, h: 8 }],
|
||||
'\u{1FB73}': [{ x: 4, y: 0, w: 1, h: 8 }],
|
||||
'\u{1FB74}': [{ x: 5, y: 0, w: 1, h: 8 }],
|
||||
'\u{1FB75}': [{ x: 6, y: 0, w: 1, h: 8 }],
|
||||
|
||||
// HORIZONTAL ONE EIGHTH BLOCK-2 through HORIZONTAL ONE EIGHTH BLOCK-7
|
||||
'\u{1FB76}': [{ x: 0, y: 1, w: 8, h: 1 }],
|
||||
'\u{1FB77}': [{ x: 0, y: 2, w: 8, h: 1 }],
|
||||
'\u{1FB78}': [{ x: 0, y: 3, w: 8, h: 1 }],
|
||||
'\u{1FB79}': [{ x: 0, y: 4, w: 8, h: 1 }],
|
||||
'\u{1FB7A}': [{ x: 0, y: 5, w: 8, h: 1 }],
|
||||
'\u{1FB7B}': [{ x: 0, y: 6, w: 8, h: 1 }],
|
||||
|
||||
// LEFT AND LOWER ONE EIGHTH BLOCK
|
||||
'\u{1FB7C}': [{ x: 0, y: 0, w: 1, h: 8 }, { x: 0, y: 7, w: 8, h: 1 }],
|
||||
// LEFT AND UPPER ONE EIGHTH BLOCK
|
||||
'\u{1FB7D}': [{ x: 0, y: 0, w: 1, h: 8 }, { x: 0, y: 0, w: 8, h: 1 }],
|
||||
// RIGHT AND UPPER ONE EIGHTH BLOCK
|
||||
'\u{1FB7E}': [{ x: 7, y: 0, w: 1, h: 8 }, { x: 0, y: 0, w: 8, h: 1 }],
|
||||
// RIGHT AND LOWER ONE EIGHTH BLOCK
|
||||
'\u{1FB7F}': [{ x: 7, y: 0, w: 1, h: 8 }, { x: 0, y: 7, w: 8, h: 1 }],
|
||||
// UPPER AND LOWER ONE EIGHTH BLOCK
|
||||
'\u{1FB80}': [{ x: 0, y: 0, w: 8, h: 1 }, { x: 0, y: 7, w: 8, h: 1 }],
|
||||
// HORIZONTAL ONE EIGHTH BLOCK-1358
|
||||
'\u{1FB81}': [{ x: 0, y: 0, w: 8, h: 1 }, { x: 0, y: 2, w: 8, h: 1 }, { x: 0, y: 4, w: 8, h: 1 }, { x: 0, y: 7, w: 8, h: 1 }],
|
||||
|
||||
// UPPER ONE QUARTER BLOCK
|
||||
'\u{1FB82}': [{ x: 0, y: 0, w: 8, h: 2 }],
|
||||
// UPPER THREE EIGHTHS BLOCK
|
||||
'\u{1FB83}': [{ x: 0, y: 0, w: 8, h: 3 }],
|
||||
// UPPER FIVE EIGHTHS BLOCK
|
||||
'\u{1FB84}': [{ x: 0, y: 0, w: 8, h: 5 }],
|
||||
// UPPER THREE QUARTERS BLOCK
|
||||
'\u{1FB85}': [{ x: 0, y: 0, w: 8, h: 6 }],
|
||||
// UPPER SEVEN EIGHTHS BLOCK
|
||||
'\u{1FB86}': [{ x: 0, y: 0, w: 8, h: 7 }],
|
||||
|
||||
// RIGHT ONE QUARTER BLOCK
|
||||
'\u{1FB87}': [{ x: 6, y: 0, w: 2, h: 8 }],
|
||||
// RIGHT THREE EIGHTHS B0OCK
|
||||
'\u{1FB88}': [{ x: 5, y: 0, w: 3, h: 8 }],
|
||||
// RIGHT FIVE EIGHTHS BL0CK
|
||||
'\u{1FB89}': [{ x: 3, y: 0, w: 5, h: 8 }],
|
||||
// RIGHT THREE QUARTERS 0LOCK
|
||||
'\u{1FB8A}': [{ x: 2, y: 0, w: 6, h: 8 }],
|
||||
// RIGHT SEVEN EIGHTHS B0OCK
|
||||
'\u{1FB8B}': [{ x: 1, y: 0, w: 7, h: 8 }],
|
||||
|
||||
// CHECKER BOARD FILL
|
||||
'\u{1FB95}': [
|
||||
{ x: 0, y: 0, w: 2, h: 2 }, { x: 4, y: 0, w: 2, h: 2 },
|
||||
{ x: 2, y: 2, w: 2, h: 2 }, { x: 6, y: 2, w: 2, h: 2 },
|
||||
{ x: 0, y: 4, w: 2, h: 2 }, { x: 4, y: 4, w: 2, h: 2 },
|
||||
{ x: 2, y: 6, w: 2, h: 2 }, { x: 6, y: 6, w: 2, h: 2 }
|
||||
],
|
||||
// INVERSE CHECKER BOARD FILL
|
||||
'\u{1FB96}': [
|
||||
{ x: 2, y: 0, w: 2, h: 2 }, { x: 6, y: 0, w: 2, h: 2 },
|
||||
{ x: 0, y: 2, w: 2, h: 2 }, { x: 4, y: 2, w: 2, h: 2 },
|
||||
{ x: 2, y: 4, w: 2, h: 2 }, { x: 6, y: 4, w: 2, h: 2 },
|
||||
{ x: 0, y: 6, w: 2, h: 2 }, { x: 4, y: 6, w: 2, h: 2 }
|
||||
],
|
||||
// HEAVY HORIZONTAL FILL (upper middle and lower one quarter block)
|
||||
'\u{1FB97}': [{ x: 0, y: 2, w: 8, h: 2 }, { x: 0, y: 6, w: 8, h: 2 }]
|
||||
};
|
||||
|
||||
type PatternDefinition = number[][];
|
||||
|
||||
/**
|
||||
* Defines the repeating pattern used by special characters, the pattern is made up of a 2d array of
|
||||
* pixel values to be filled (1) or not filled (0).
|
||||
*/
|
||||
const patternCharacterDefinitions: { [key: string]: PatternDefinition | undefined } = {
|
||||
// Shade characters (0x2591-0x2593)
|
||||
'░': [ // LIGHT SHADE (25%)
|
||||
[1, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 1, 0],
|
||||
[0, 0, 0, 0]
|
||||
],
|
||||
'▒': [ // MEDIUM SHADE (50%)
|
||||
[1, 0],
|
||||
[0, 0],
|
||||
[0, 1],
|
||||
[0, 0]
|
||||
],
|
||||
'▓': [ // DARK SHADE (75%)
|
||||
[0, 1],
|
||||
[1, 1],
|
||||
[1, 0],
|
||||
[1, 1]
|
||||
]
|
||||
};
|
||||
|
||||
const enum Shapes {
|
||||
/** │ */ TOP_TO_BOTTOM = 'M.5,0 L.5,1',
|
||||
/** ─ */ LEFT_TO_RIGHT = 'M0,.5 L1,.5',
|
||||
|
||||
/** └ */ TOP_TO_RIGHT = 'M.5,0 L.5,.5 L1,.5',
|
||||
/** ┘ */ TOP_TO_LEFT = 'M.5,0 L.5,.5 L0,.5',
|
||||
/** ┐ */ LEFT_TO_BOTTOM = 'M0,.5 L.5,.5 L.5,1',
|
||||
/** ┌ */ RIGHT_TO_BOTTOM = 'M0.5,1 L.5,.5 L1,.5',
|
||||
|
||||
/** ╵ */ MIDDLE_TO_TOP = 'M.5,.5 L.5,0',
|
||||
/** ╴ */ MIDDLE_TO_LEFT = 'M.5,.5 L0,.5',
|
||||
/** ╶ */ MIDDLE_TO_RIGHT = 'M.5,.5 L1,.5',
|
||||
/** ╷ */ MIDDLE_TO_BOTTOM = 'M.5,.5 L.5,1',
|
||||
|
||||
/** ┴ */ T_TOP = 'M0,.5 L1,.5 M.5,.5 L.5,0',
|
||||
/** ┤ */ T_LEFT = 'M.5,0 L.5,1 M.5,.5 L0,.5',
|
||||
/** ├ */ T_RIGHT = 'M.5,0 L.5,1 M.5,.5 L1,.5',
|
||||
/** ┬ */ T_BOTTOM = 'M0,.5 L1,.5 M.5,.5 L.5,1',
|
||||
|
||||
/** ┼ */ CROSS = 'M0,.5 L1,.5 M.5,0 L.5,1',
|
||||
|
||||
/** ╌ */ TWO_DASHES_HORIZONTAL = 'M.1,.5 L.4,.5 M.6,.5 L.9,.5', // .2 empty, .3 filled
|
||||
/** ┄ */ THREE_DASHES_HORIZONTAL = 'M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5', // .1333 empty, .2 filled
|
||||
/** ┉ */ FOUR_DASHES_HORIZONTAL = 'M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5', // .1 empty, .15 filled
|
||||
/** ╎ */ TWO_DASHES_VERTICAL = 'M.5,.1 L.5,.4 M.5,.6 L.5,.9',
|
||||
/** ┆ */ THREE_DASHES_VERTICAL = 'M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333',
|
||||
/** ┊ */ FOUR_DASHES_VERTICAL = 'M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95',
|
||||
}
|
||||
|
||||
const enum Style {
|
||||
NORMAL = 1,
|
||||
BOLD = 3
|
||||
}
|
||||
|
||||
/**
|
||||
* This contains the definitions of all box drawing characters in the format of SVG paths (ie. the
|
||||
* svg d attribute).
|
||||
*/
|
||||
export const boxDrawingDefinitions: { [character: string]: { [fontWeight: number]: string | ((xp: number, yp: number) => string) } | undefined } = {
|
||||
// Uniform normal and bold
|
||||
'─': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT },
|
||||
'━': { [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
|
||||
'│': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM },
|
||||
'┃': { [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
|
||||
'┌': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM },
|
||||
'┏': { [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
|
||||
'┐': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM },
|
||||
'┓': { [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
|
||||
'└': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT },
|
||||
'┗': { [Style.BOLD]: Shapes.TOP_TO_RIGHT },
|
||||
'┘': { [Style.NORMAL]: Shapes.TOP_TO_LEFT },
|
||||
'┛': { [Style.BOLD]: Shapes.TOP_TO_LEFT },
|
||||
'├': { [Style.NORMAL]: Shapes.T_RIGHT },
|
||||
'┣': { [Style.BOLD]: Shapes.T_RIGHT },
|
||||
'┤': { [Style.NORMAL]: Shapes.T_LEFT },
|
||||
'┫': { [Style.BOLD]: Shapes.T_LEFT },
|
||||
'┬': { [Style.NORMAL]: Shapes.T_BOTTOM },
|
||||
'┳': { [Style.BOLD]: Shapes.T_BOTTOM },
|
||||
'┴': { [Style.NORMAL]: Shapes.T_TOP },
|
||||
'┻': { [Style.BOLD]: Shapes.T_TOP },
|
||||
'┼': { [Style.NORMAL]: Shapes.CROSS },
|
||||
'╋': { [Style.BOLD]: Shapes.CROSS },
|
||||
'╴': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT },
|
||||
'╸': { [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'╵': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP },
|
||||
'╹': { [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'╶': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'╺': { [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'╷': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'╻': { [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
|
||||
// Double border
|
||||
'═': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp}` },
|
||||
'║': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1` },
|
||||
'╒': { [Style.NORMAL]: (xp, yp) => `M.5,1 L.5,${.5 - yp} L1,${.5 - yp} M.5,${.5 + yp} L1,${.5 + yp}` },
|
||||
'╓': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},1 L${.5 - xp},.5 L1,.5 M${.5 + xp},.5 L${.5 + xp},1` },
|
||||
'╔': { [Style.NORMAL]: (xp, yp) => `M1,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1` },
|
||||
'╕': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L.5,${.5 - yp} L.5,1 M0,${.5 + yp} L.5,${.5 + yp}` },
|
||||
'╖': { [Style.NORMAL]: (xp, yp) => `M${.5 + xp},1 L${.5 + xp},.5 L0,.5 M${.5 - xp},.5 L${.5 - xp},1` },
|
||||
'╗': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M0,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},1` },
|
||||
'╘': { [Style.NORMAL]: (xp, yp) => `M.5,0 L.5,${.5 + yp} L1,${.5 + yp} M.5,${.5 - yp} L1,${.5 - yp}` },
|
||||
'╙': { [Style.NORMAL]: (xp, yp) => `M1,.5 L${.5 - xp},.5 L${.5 - xp},0 M${.5 + xp},.5 L${.5 + xp},0` },
|
||||
'╚': { [Style.NORMAL]: (xp, yp) => `M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0 M1,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},0` },
|
||||
'╛': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L.5,${.5 + yp} L.5,0 M0,${.5 - yp} L.5,${.5 - yp}` },
|
||||
'╜': { [Style.NORMAL]: (xp, yp) => `M0,.5 L${.5 + xp},.5 L${.5 + xp},0 M${.5 - xp},.5 L${.5 - xp},0` },
|
||||
'╝': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0 M0,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},0` },
|
||||
'╞': { [Style.NORMAL]: (xp, yp) => `${Shapes.TOP_TO_BOTTOM} M.5,${.5 - yp} L1,${.5 - yp} M.5,${.5 + yp} L1,${.5 + yp}` },
|
||||
'╟': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1 M${.5 + xp},.5 L1,.5` },
|
||||
'╠': { [Style.NORMAL]: (xp, yp) => `M${.5 - xp},0 L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1 M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0` },
|
||||
'╡': { [Style.NORMAL]: (xp, yp) => `${Shapes.TOP_TO_BOTTOM} M0,${.5 - yp} L.5,${.5 - yp} M0,${.5 + yp} L.5,${.5 + yp}` },
|
||||
'╢': { [Style.NORMAL]: (xp, yp) => `M0,.5 L${.5 - xp},.5 M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1` },
|
||||
'╣': { [Style.NORMAL]: (xp, yp) => `M${.5 + xp},0 L${.5 + xp},1 M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0` },
|
||||
'╤': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp} M.5,${.5 + yp} L.5,1` },
|
||||
'╥': { [Style.NORMAL]: (xp, yp) => `${Shapes.LEFT_TO_RIGHT} M${.5 - xp},.5 L${.5 - xp},1 M${.5 + xp},.5 L${.5 + xp},1` },
|
||||
'╦': { [Style.NORMAL]: (xp, yp) => `M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1` },
|
||||
'╧': { [Style.NORMAL]: (xp, yp) => `M.5,0 L.5,${.5 - yp} M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp}` },
|
||||
'╨': { [Style.NORMAL]: (xp, yp) => `${Shapes.LEFT_TO_RIGHT} M${.5 - xp},.5 L${.5 - xp},0 M${.5 + xp},.5 L${.5 + xp},0` },
|
||||
'╩': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L1,${.5 + yp} M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0 M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0` },
|
||||
'╪': { [Style.NORMAL]: (xp, yp) => `${Shapes.TOP_TO_BOTTOM} M0,${.5 - yp} L1,${.5 - yp} M0,${.5 + yp} L1,${.5 + yp}` },
|
||||
'╫': { [Style.NORMAL]: (xp, yp) => `${Shapes.LEFT_TO_RIGHT} M${.5 - xp},0 L${.5 - xp},1 M${.5 + xp},0 L${.5 + xp},1` },
|
||||
'╬': { [Style.NORMAL]: (xp, yp) => `M0,${.5 + yp} L${.5 - xp},${.5 + yp} L${.5 - xp},1 M1,${.5 + yp} L${.5 + xp},${.5 + yp} L${.5 + xp},1 M0,${.5 - yp} L${.5 - xp},${.5 - yp} L${.5 - xp},0 M1,${.5 - yp} L${.5 + xp},${.5 - yp} L${.5 + xp},0` },
|
||||
|
||||
// Diagonal
|
||||
'╱': { [Style.NORMAL]: 'M1,0 L0,1' },
|
||||
'╲': { [Style.NORMAL]: 'M0,0 L1,1' },
|
||||
'╳': { [Style.NORMAL]: 'M1,0 L0,1 M0,0 L1,1' },
|
||||
|
||||
// Mixed weight
|
||||
'╼': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'╽': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'╾': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'╿': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'┍': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'┎': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'┑': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'┒': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'┕': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'┖': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'┙': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'┚': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'┝': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'┞': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'┟': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'┠': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
|
||||
'┡': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_RIGHT },
|
||||
'┢': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
|
||||
'┥': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'┦': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'┧': { [Style.NORMAL]: Shapes.TOP_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'┨': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
|
||||
'┩': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_LEFT },
|
||||
'┪': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
|
||||
'┭': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'┮': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'┯': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
|
||||
'┰': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'┱': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
|
||||
'┲': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
|
||||
'┵': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'┶': { [Style.NORMAL]: Shapes.TOP_TO_LEFT, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'┷': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
|
||||
'┸': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'┹': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: Shapes.TOP_TO_LEFT },
|
||||
'┺': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: Shapes.TOP_TO_RIGHT },
|
||||
'┽': { [Style.NORMAL]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_RIGHT}`, [Style.BOLD]: Shapes.MIDDLE_TO_LEFT },
|
||||
'┾': { [Style.NORMAL]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_LEFT}`, [Style.BOLD]: Shapes.MIDDLE_TO_RIGHT },
|
||||
'┿': { [Style.NORMAL]: Shapes.TOP_TO_BOTTOM, [Style.BOLD]: Shapes.LEFT_TO_RIGHT },
|
||||
'╀': { [Style.NORMAL]: `${Shapes.LEFT_TO_RIGHT} ${Shapes.MIDDLE_TO_BOTTOM}`, [Style.BOLD]: Shapes.MIDDLE_TO_TOP },
|
||||
'╁': { [Style.NORMAL]: `${Shapes.MIDDLE_TO_TOP} ${Shapes.LEFT_TO_RIGHT}`, [Style.BOLD]: Shapes.MIDDLE_TO_BOTTOM },
|
||||
'╂': { [Style.NORMAL]: Shapes.LEFT_TO_RIGHT, [Style.BOLD]: Shapes.TOP_TO_BOTTOM },
|
||||
'╃': { [Style.NORMAL]: Shapes.RIGHT_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_LEFT },
|
||||
'╄': { [Style.NORMAL]: Shapes.LEFT_TO_BOTTOM, [Style.BOLD]: Shapes.TOP_TO_RIGHT },
|
||||
'╅': { [Style.NORMAL]: Shapes.TOP_TO_RIGHT, [Style.BOLD]: Shapes.LEFT_TO_BOTTOM },
|
||||
'╆': { [Style.NORMAL]: Shapes.TOP_TO_LEFT, [Style.BOLD]: Shapes.RIGHT_TO_BOTTOM },
|
||||
'╇': { [Style.NORMAL]: Shapes.MIDDLE_TO_BOTTOM, [Style.BOLD]: `${Shapes.MIDDLE_TO_TOP} ${Shapes.LEFT_TO_RIGHT}` },
|
||||
'╈': { [Style.NORMAL]: Shapes.MIDDLE_TO_TOP, [Style.BOLD]: `${Shapes.LEFT_TO_RIGHT} ${Shapes.MIDDLE_TO_BOTTOM}` },
|
||||
'╉': { [Style.NORMAL]: Shapes.MIDDLE_TO_RIGHT, [Style.BOLD]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_LEFT}` },
|
||||
'╊': { [Style.NORMAL]: Shapes.MIDDLE_TO_LEFT, [Style.BOLD]: `${Shapes.TOP_TO_BOTTOM} ${Shapes.MIDDLE_TO_RIGHT}` },
|
||||
|
||||
// Dashed
|
||||
'╌': { [Style.NORMAL]: Shapes.TWO_DASHES_HORIZONTAL },
|
||||
'╍': { [Style.BOLD]: Shapes.TWO_DASHES_HORIZONTAL },
|
||||
'┄': { [Style.NORMAL]: Shapes.THREE_DASHES_HORIZONTAL },
|
||||
'┅': { [Style.BOLD]: Shapes.THREE_DASHES_HORIZONTAL },
|
||||
'┈': { [Style.NORMAL]: Shapes.FOUR_DASHES_HORIZONTAL },
|
||||
'┉': { [Style.BOLD]: Shapes.FOUR_DASHES_HORIZONTAL },
|
||||
'╎': { [Style.NORMAL]: Shapes.TWO_DASHES_VERTICAL },
|
||||
'╏': { [Style.BOLD]: Shapes.TWO_DASHES_VERTICAL },
|
||||
'┆': { [Style.NORMAL]: Shapes.THREE_DASHES_VERTICAL },
|
||||
'┇': { [Style.BOLD]: Shapes.THREE_DASHES_VERTICAL },
|
||||
'┊': { [Style.NORMAL]: Shapes.FOUR_DASHES_VERTICAL },
|
||||
'┋': { [Style.BOLD]: Shapes.FOUR_DASHES_VERTICAL },
|
||||
|
||||
// Curved
|
||||
'╭': { [Style.NORMAL]: 'C.5,1,.5,.5,1,.5' },
|
||||
'╮': { [Style.NORMAL]: 'C.5,1,.5,.5,0,.5' },
|
||||
'╯': { [Style.NORMAL]: 'C.5,0,.5,.5,0,.5' },
|
||||
'╰': { [Style.NORMAL]: 'C.5,0,.5,.5,1,.5' }
|
||||
};
|
||||
|
||||
/**
|
||||
* Try drawing a custom block element or box drawing character, returning whether it was
|
||||
* successfully drawn.
|
||||
*/
|
||||
export function tryDrawCustomChar(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
c: string,
|
||||
xOffset: number,
|
||||
yOffset: number,
|
||||
scaledCellWidth: number,
|
||||
scaledCellHeight: number
|
||||
): boolean {
|
||||
const blockElementDefinition = blockElementDefinitions[c];
|
||||
if (blockElementDefinition) {
|
||||
drawBlockElementChar(ctx, blockElementDefinition, xOffset, yOffset, scaledCellWidth, scaledCellHeight);
|
||||
return true;
|
||||
}
|
||||
|
||||
const patternDefinition = patternCharacterDefinitions[c];
|
||||
if (patternDefinition) {
|
||||
drawPatternChar(ctx, patternDefinition, xOffset, yOffset, scaledCellWidth, scaledCellHeight);
|
||||
return true;
|
||||
}
|
||||
|
||||
const boxDrawingDefinition = boxDrawingDefinitions[c];
|
||||
if (boxDrawingDefinition) {
|
||||
drawBoxDrawingChar(ctx, boxDrawingDefinition, xOffset, yOffset, scaledCellWidth, scaledCellHeight);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function drawBlockElementChar(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
charDefinition: IBlockVector[],
|
||||
xOffset: number,
|
||||
yOffset: number,
|
||||
scaledCellWidth: number,
|
||||
scaledCellHeight: number
|
||||
): void {
|
||||
for (let i = 0; i < charDefinition.length; i++) {
|
||||
const box = charDefinition[i];
|
||||
const xEighth = scaledCellWidth / 8;
|
||||
const yEighth = scaledCellHeight / 8;
|
||||
ctx.fillRect(
|
||||
xOffset + box.x * xEighth,
|
||||
yOffset + box.y * yEighth,
|
||||
box.w * xEighth,
|
||||
box.h * yEighth
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const cachedPatterns: Map<PatternDefinition, Map</* fillStyle */string, CanvasPattern>> = new Map();
|
||||
|
||||
function drawPatternChar(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
charDefinition: number[][],
|
||||
xOffset: number,
|
||||
yOffset: number,
|
||||
scaledCellWidth: number,
|
||||
scaledCellHeight: number
|
||||
): void {
|
||||
let patternSet = cachedPatterns.get(charDefinition);
|
||||
if (!patternSet) {
|
||||
patternSet = new Map();
|
||||
cachedPatterns.set(charDefinition, patternSet);
|
||||
}
|
||||
const fillStyle = ctx.fillStyle;
|
||||
if (typeof fillStyle !== 'string') {
|
||||
throw new Error(`Unexpected fillStyle type "${fillStyle}"`);
|
||||
}
|
||||
let pattern = patternSet.get(fillStyle);
|
||||
if (!pattern) {
|
||||
const width = charDefinition[0].length;
|
||||
const height = charDefinition.length;
|
||||
const tmpCanvas = document.createElement('canvas');
|
||||
tmpCanvas.width = width;
|
||||
tmpCanvas.height = height;
|
||||
const tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d'));
|
||||
const imageData = new ImageData(width, height);
|
||||
|
||||
// Extract rgba from fillStyle
|
||||
let r: number;
|
||||
let g: number;
|
||||
let b: number;
|
||||
let a: number;
|
||||
if (fillStyle.startsWith('#')) {
|
||||
r = parseInt(fillStyle.substr(1, 2), 16);
|
||||
g = parseInt(fillStyle.substr(3, 2), 16);
|
||||
b = parseInt(fillStyle.substr(5, 2), 16);
|
||||
a = fillStyle.length > 7 && parseInt(fillStyle.substr(7, 2), 16) || 1;
|
||||
} else if (fillStyle.startsWith('rgba')) {
|
||||
([r, g, b, a] = fillStyle.substring(5, fillStyle.length - 1).split(',').map(e => parseFloat(e)));
|
||||
} else {
|
||||
throw new Error(`Unexpected fillStyle color format "${fillStyle}" when drawing pattern glyph`);
|
||||
}
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
imageData.data[(y * width + x) * 4 ] = r;
|
||||
imageData.data[(y * width + x) * 4 + 1] = g;
|
||||
imageData.data[(y * width + x) * 4 + 2] = b;
|
||||
imageData.data[(y * width + x) * 4 + 3] = charDefinition[y][x] * (a * 255);
|
||||
}
|
||||
}
|
||||
tmpCtx.putImageData(imageData, 0, 0);
|
||||
pattern = throwIfFalsy(ctx.createPattern(tmpCanvas, null));
|
||||
patternSet.set(fillStyle, pattern);
|
||||
}
|
||||
ctx.fillStyle = pattern;
|
||||
ctx.fillRect(xOffset, yOffset, scaledCellWidth, scaledCellHeight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the following box drawing characters by mapping a subset of SVG d attribute instructions to
|
||||
* canvas draw calls.
|
||||
*
|
||||
* Box styles: ┎┰┒┍┯┑╓╥╖╒╤╕ ┏┳┓┌┲┓┌┬┐┏┱┐
|
||||
* ┌─┬─┐ ┏━┳━┓ ╔═╦═╗ ┠╂┨┝┿┥╟╫╢╞╪╡ ┡╇┩├╊┫┢╈┪┣╉┤
|
||||
* │ │ │ ┃ ┃ ┃ ║ ║ ║ ┖┸┚┕┷┙╙╨╜╘╧╛ └┴┘└┺┛┗┻┛┗┹┘
|
||||
* ├─┼─┤ ┣━╋━┫ ╠═╬═╣ ┏┱┐┌┲┓┌┬┐┌┬┐ ┏┳┓┌┮┓┌┬┐┏┭┐
|
||||
* │ │ │ ┃ ┃ ┃ ║ ║ ║ ┡╃┤├╄┩├╆┪┢╅┤ ┞╀┦├┾┫┟╁┧┣┽┤
|
||||
* └─┴─┘ ┗━┻━┛ ╚═╩═╝ └┴┘└┴┘└┺┛┗┹┘ └┴┘└┶┛┗┻┛┗┵┘
|
||||
*
|
||||
* Other:
|
||||
* ╭─╮ ╲ ╱ ╷╻╎╏┆┇┊┋ ╺╾╴ ╌╌╌ ┄┄┄ ┈┈┈
|
||||
* │ │ ╳ ╽╿╎╏┆┇┊┋ ╶╼╸ ╍╍╍ ┅┅┅ ┉┉┉
|
||||
* ╰─╯ ╱ ╲ ╹╵╎╏┆┇┊┋
|
||||
*
|
||||
* All box drawing characters:
|
||||
* ─ ━ │ ┃ ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ ┌ ┍ ┎ ┏
|
||||
* ┐ ┑ ┒ ┓ └ ┕ ┖ ┗ ┘ ┙ ┚ ┛ ├ ┝ ┞ ┟
|
||||
* ┠ ┡ ┢ ┣ ┤ ┥ ┦ ┧ ┨ ┩ ┪ ┫ ┬ ┭ ┮ ┯
|
||||
* ┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻ ┼ ┽ ┾ ┿
|
||||
* ╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╌ ╍ ╎ ╏
|
||||
* ═ ║ ╒ ╓ ╔ ╕ ╖ ╗ ╘ ╙ ╚ ╛ ╜ ╝ ╞ ╟
|
||||
* ╠ ╡ ╢ ╣ ╤ ╥ ╦ ╧ ╨ ╩ ╪ ╫ ╬ ╭ ╮ ╯
|
||||
* ╰ ╱ ╲ ╳ ╴ ╵ ╶ ╷ ╸ ╹ ╺ ╻ ╼ ╽ ╾ ╿
|
||||
*
|
||||
* ---
|
||||
*
|
||||
* Box drawing alignment tests: █
|
||||
* ▉
|
||||
* ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳
|
||||
* ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳
|
||||
* ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳
|
||||
* ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳
|
||||
* ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎
|
||||
* ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏
|
||||
* ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█
|
||||
*
|
||||
* Source: https://www.w3.org/2001/06/utf-8-test/UTF-8-demo.html
|
||||
*/
|
||||
function drawBoxDrawingChar(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
charDefinition: { [fontWeight: number]: string | ((xp: number, yp: number) => string) },
|
||||
xOffset: number,
|
||||
yOffset: number,
|
||||
scaledCellWidth: number,
|
||||
scaledCellHeight: number
|
||||
): void {
|
||||
ctx.strokeStyle = ctx.fillStyle;
|
||||
for (const [fontWeight, instructions] of Object.entries(charDefinition)) {
|
||||
ctx.beginPath();
|
||||
ctx.lineWidth = window.devicePixelRatio * Number.parseInt(fontWeight);
|
||||
let actualInstructions: string;
|
||||
if (typeof instructions === 'function') {
|
||||
const xp = .15;
|
||||
const yp = .15 / scaledCellHeight * scaledCellWidth;
|
||||
actualInstructions = instructions(xp, yp);
|
||||
} else {
|
||||
actualInstructions = instructions;
|
||||
}
|
||||
for (const instruction of actualInstructions.split(' ')) {
|
||||
const type = instruction[0];
|
||||
const f = svgToCanvasInstructionMap[type];
|
||||
if (!f) {
|
||||
console.error(`Could not find drawing instructions for "${type}"`);
|
||||
continue;
|
||||
}
|
||||
const args: string[] = instruction.substring(1).split(',');
|
||||
if (!args[0] || !args[1]) {
|
||||
continue;
|
||||
}
|
||||
f(ctx, translateArgs(args, scaledCellWidth, scaledCellHeight, xOffset, yOffset));
|
||||
}
|
||||
ctx.stroke();
|
||||
ctx.closePath();
|
||||
}
|
||||
}
|
||||
|
||||
function clamp(value: number, max: number, min: number = 0): number {
|
||||
return Math.max(Math.min(value, max), min);
|
||||
}
|
||||
|
||||
const svgToCanvasInstructionMap: { [index: string]: any } = {
|
||||
'C': (ctx: CanvasRenderingContext2D, args: number[]) => ctx.bezierCurveTo(args[0], args[1], args[2], args[3], args[4], args[5]),
|
||||
'L': (ctx: CanvasRenderingContext2D, args: number[]) => ctx.lineTo(args[0], args[1]),
|
||||
'M': (ctx: CanvasRenderingContext2D, args: number[]) => ctx.moveTo(args[0], args[1])
|
||||
};
|
||||
|
||||
function translateArgs(args: string[], cellWidth: number, cellHeight: number, xOffset: number, yOffset: number): number[] {
|
||||
const result = args.map(e => parseFloat(e) || parseInt(e));
|
||||
|
||||
if (result.length < 2) {
|
||||
throw new Error('Too few arguments for instruction');
|
||||
}
|
||||
|
||||
for (let x = 0; x < result.length; x += 2) {
|
||||
// Translate from 0-1 to 0-cellWidth
|
||||
result[x] *= cellWidth;
|
||||
// Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
|
||||
// line at 100% devicePixelRatio
|
||||
if (result[x] !== 0) {
|
||||
result[x] = clamp(Math.round(result[x] + 0.5) - 0.5, cellWidth, 0);
|
||||
}
|
||||
// Apply the cell's offset (ie. x*cellWidth)
|
||||
result[x] += xOffset;
|
||||
}
|
||||
|
||||
for (let y = 1; y < result.length; y += 2) {
|
||||
// Translate from 0-1 to 0-cellHeight
|
||||
result[y] *= cellHeight;
|
||||
// Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
|
||||
// line at 100% devicePixelRatio
|
||||
if (result[y] !== 0) {
|
||||
result[y] = clamp(Math.round(result[y] + 0.5) - 0.5, cellHeight, 0);
|
||||
}
|
||||
// Apply the cell's offset (ie. x*cellHeight)
|
||||
result[y] += yOffset;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -266,11 +266,10 @@ export class DynamicCharAtlas extends BaseCharAtlas {
|
||||
}
|
||||
// Draw the character
|
||||
this._tmpCtx.fillText(glyph.chars, 0, this._config.scaledCharHeight);
|
||||
this._tmpCtx.restore();
|
||||
|
||||
// clear the background from the character to avoid issues with drawing over the previous
|
||||
// character if it extends past it's bounds
|
||||
const imageData = this._tmpCtx.getImageData(
|
||||
let imageData = this._tmpCtx.getImageData(
|
||||
0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight
|
||||
);
|
||||
let isEmpty = false;
|
||||
@@ -278,6 +277,27 @@ export class DynamicCharAtlas extends BaseCharAtlas {
|
||||
isEmpty = clearColor(imageData, backgroundColor);
|
||||
}
|
||||
|
||||
// If this charcater is underscore and empty, shift it up until it is visible, try for a maximum
|
||||
// of 5 pixels.
|
||||
if (isEmpty && glyph.chars === '_' && !this._config.allowTransparency) {
|
||||
for (let offset = 1; offset <= 5; offset++) {
|
||||
// Draw the character
|
||||
this._tmpCtx.fillText(glyph.chars, 0, this._config.scaledCharHeight - offset);
|
||||
|
||||
// clear the background from the character to avoid issues with drawing over the previous
|
||||
// character if it extends past it's bounds
|
||||
imageData = this._tmpCtx.getImageData(
|
||||
0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight
|
||||
);
|
||||
isEmpty = clearColor(imageData, backgroundColor);
|
||||
if (!isEmpty) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._tmpCtx.restore();
|
||||
|
||||
// copy the data from imageData to _cacheCanvas
|
||||
const x = this._toCoordinateX(index);
|
||||
const y = this._toCoordinateY(index);
|
||||
|
||||
@@ -9,7 +9,7 @@ import { EventEmitter, IEvent } from 'common/EventEmitter';
|
||||
import { Disposable } from 'common/Lifecycle';
|
||||
import { ScreenDprMonitor } from 'browser/ScreenDprMonitor';
|
||||
import { addDisposableDomListener } from 'browser/Lifecycle';
|
||||
import { IColorSet } from 'browser/Types';
|
||||
import { IColorSet, IRenderDebouncer } from 'browser/Types';
|
||||
import { IOptionsService, IBufferService } from 'common/services/Services';
|
||||
import { ICharSizeService, IRenderService } from 'browser/services/Services';
|
||||
|
||||
@@ -22,7 +22,7 @@ interface ISelectionState {
|
||||
export class RenderService extends Disposable implements IRenderService {
|
||||
public serviceBrand: undefined;
|
||||
|
||||
private _renderDebouncer: RenderDebouncer;
|
||||
private _renderDebouncer: IRenderDebouncer;
|
||||
private _screenDprMonitor: ScreenDprMonitor;
|
||||
|
||||
private _isPaused: boolean = false;
|
||||
|
||||
+11
-11
@@ -47,11 +47,11 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal {
|
||||
protected readonly _instantiationService: IInstantiationService;
|
||||
protected readonly _bufferService: IBufferService;
|
||||
protected readonly _logService: ILogService;
|
||||
protected readonly _coreService: ICoreService;
|
||||
protected readonly _charsetService: ICharsetService;
|
||||
protected readonly _coreMouseService: ICoreMouseService;
|
||||
protected readonly _dirtyRowService: IDirtyRowService;
|
||||
|
||||
public readonly coreMouseService: ICoreMouseService;
|
||||
public readonly coreService: ICoreService;
|
||||
public readonly unicodeService: IUnicodeService;
|
||||
public readonly optionsService: IOptionsService;
|
||||
|
||||
@@ -100,10 +100,10 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal {
|
||||
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.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);
|
||||
@@ -112,14 +112,14 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal {
|
||||
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._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(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 });
|
||||
@@ -250,8 +250,8 @@ export abstract class CoreTerminal extends Disposable implements ICoreTerminal {
|
||||
this._inputHandler.reset();
|
||||
this._bufferService.reset();
|
||||
this._charsetService.reset();
|
||||
this._coreService.reset();
|
||||
this._coreMouseService.reset();
|
||||
this.coreService.reset();
|
||||
this.coreMouseService.reset();
|
||||
}
|
||||
|
||||
protected _updateOptions(key: string): void {
|
||||
|
||||
Vendored
+3
-1
@@ -7,10 +7,12 @@ import { IFunctionIdentifier, ITerminalOptions as IPublicTerminalOptions } from
|
||||
import { IEvent, IEventEmitter } from 'common/EventEmitter';
|
||||
import { IDeleteEvent, IInsertEvent } from 'common/CircularList';
|
||||
import { IParams } from 'common/parser/Types';
|
||||
import { IOptionsService, IUnicodeService } from 'common/services/Services';
|
||||
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;
|
||||
|
||||
@@ -21,6 +21,7 @@ export const DEFAULT_OPTIONS: ITerminalOptions = Object.freeze({
|
||||
cursorBlink: false,
|
||||
cursorStyle: 'block',
|
||||
cursorWidth: 1,
|
||||
customGlyphs: true,
|
||||
bellSound: DEFAULT_BELL_SOUND,
|
||||
bellStyle: 'none',
|
||||
drawBoldTextInBrightColors: true,
|
||||
|
||||
@@ -244,6 +244,7 @@ export interface ITerminalOptions {
|
||||
cursorBlink: boolean;
|
||||
cursorStyle: 'block' | 'underline' | 'bar';
|
||||
cursorWidth: number;
|
||||
customGlyphs: boolean;
|
||||
disableStdin: boolean;
|
||||
drawBoldTextInBrightColors: boolean;
|
||||
fastScrollModifier: 'alt' | 'ctrl' | 'shift' | undefined;
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
|
||||
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
|
||||
* @license MIT
|
||||
*
|
||||
* Originally forked from (with the author's permission):
|
||||
* Fabrice Bellard's javascript vt100 for jslinux:
|
||||
* http://bellard.org/jslinux/
|
||||
* Copyright (c) 2011 Fabrice Bellard
|
||||
* The original design remains. The terminal itself
|
||||
* has been extended to include xterm CSI codes, among
|
||||
* other features.
|
||||
*
|
||||
* Terminal Emulation References:
|
||||
* http://vt100.net/
|
||||
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
|
||||
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
|
||||
* http://invisible-island.net/vttest/
|
||||
* http://www.inwap.com/pdp10/ansicode.txt
|
||||
* http://linux.die.net/man/4/console_codes
|
||||
* http://linux.die.net/man/7/urxvt
|
||||
*/
|
||||
|
||||
import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
|
||||
import { IBuffer } from 'common/buffer/Types';
|
||||
import { CoreTerminal } from 'common/CoreTerminal';
|
||||
import { EventEmitter, forwardEvent, IEvent } from 'common/EventEmitter';
|
||||
import { ITerminalOptions as IInitializedTerminalOptions } from 'common/services/Services';
|
||||
import { IMarker, ITerminalOptions, ScrollSource } from 'common/Types';
|
||||
|
||||
export class Terminal extends CoreTerminal {
|
||||
// TODO: We should remove options once components adopt optionsService
|
||||
public get options(): IInitializedTerminalOptions { return this.optionsService.options; }
|
||||
|
||||
private _onBell = new EventEmitter<void>();
|
||||
public get onBell(): IEvent<void> { return this._onBell.event; }
|
||||
private _onCursorMove = new EventEmitter<void>();
|
||||
public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }
|
||||
private _onTitleChange = new EventEmitter<string>();
|
||||
public get onTitleChange(): IEvent<string> { return this._onTitleChange.event; }
|
||||
|
||||
private _onA11yCharEmitter = new EventEmitter<string>();
|
||||
public get onA11yChar(): IEvent<string> { return this._onA11yCharEmitter.event; }
|
||||
private _onA11yTabEmitter = new EventEmitter<number>();
|
||||
public get onA11yTab(): IEvent<number> { return this._onA11yTabEmitter.event; }
|
||||
|
||||
/**
|
||||
* Creates a new `Terminal` object.
|
||||
*
|
||||
* @param options An object containing a set of options, the available options are:
|
||||
* - `cursorBlink` (boolean): Whether the terminal cursor blinks
|
||||
* - `cols` (number): The number of columns of the terminal (horizontal size)
|
||||
* - `rows` (number): The number of rows of the terminal (vertical size)
|
||||
*
|
||||
* @public
|
||||
* @class Xterm Xterm
|
||||
* @alias module:xterm/src/xterm
|
||||
*/
|
||||
constructor(
|
||||
options: ITerminalOptions = {}
|
||||
) {
|
||||
super(options);
|
||||
|
||||
this._setup();
|
||||
|
||||
// Setup InputHandler listeners
|
||||
this.register(this._inputHandler.onRequestBell(() => this.bell()));
|
||||
this.register(this._inputHandler.onRequestReset(() => this.reset()));
|
||||
this.register(forwardEvent(this._inputHandler.onCursorMove, this._onCursorMove));
|
||||
this.register(forwardEvent(this._inputHandler.onTitleChange, this._onTitleChange));
|
||||
this.register(forwardEvent(this._inputHandler.onA11yChar, this._onA11yCharEmitter));
|
||||
this.register(forwardEvent(this._inputHandler.onA11yTab, this._onA11yTabEmitter));
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
if (this._isDisposed) {
|
||||
return;
|
||||
}
|
||||
super.dispose();
|
||||
this.write = () => { };
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience property to active buffer.
|
||||
*/
|
||||
public get buffer(): IBuffer {
|
||||
return this.buffers.active;
|
||||
}
|
||||
|
||||
protected _updateOptions(key: string): void {
|
||||
super._updateOptions(key);
|
||||
|
||||
// TODO: These listeners should be owned by individual components
|
||||
switch (key) {
|
||||
case 'tabStopWidth': this.buffers.setupTabStops(); break;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Support paste here?
|
||||
|
||||
public get markers(): IMarker[] {
|
||||
return this.buffer.markers;
|
||||
}
|
||||
|
||||
public addMarker(cursorYOffset: number): IMarker | undefined {
|
||||
// Disallow markers on the alt buffer
|
||||
if (this.buffer !== this.buffers.normal) {
|
||||
return;
|
||||
}
|
||||
|
||||
return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);
|
||||
}
|
||||
|
||||
public bell(): void {
|
||||
this._onBell.fire();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the terminal.
|
||||
*
|
||||
* @param x The number of columns to resize to.
|
||||
* @param y The number of rows to resize to.
|
||||
*/
|
||||
public resize(x: number, y: number): void {
|
||||
if (x === this.cols && y === this.rows) {
|
||||
return;
|
||||
}
|
||||
|
||||
super.resize(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the entire buffer, making the prompt line the new first line.
|
||||
*/
|
||||
public clear(): void {
|
||||
if (this.buffer.ybase === 0 && this.buffer.y === 0) {
|
||||
// Don't clear if it's already clear
|
||||
return;
|
||||
}
|
||||
this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)!);
|
||||
this.buffer.lines.length = 1;
|
||||
this.buffer.ydisp = 0;
|
||||
this.buffer.ybase = 0;
|
||||
this.buffer.y = 0;
|
||||
for (let i = 1; i < this.rows; i++) {
|
||||
this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));
|
||||
}
|
||||
this._onScroll.fire({ position: this.buffer.ydisp, source: ScrollSource.TERMINAL });
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset terminal.
|
||||
* Note: Calling this directly from JS is synchronous but does not clear
|
||||
* input buffers and does not reset the parser, thus the terminal will
|
||||
* continue to apply pending input data.
|
||||
* If you need in band reset (synchronous with input data) consider
|
||||
* using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).
|
||||
*/
|
||||
public reset(): void {
|
||||
/**
|
||||
* Since _setup handles a full terminal creation, we have to carry forward
|
||||
* a few things that should not reset.
|
||||
*/
|
||||
this.options.rows = this.rows;
|
||||
this.options.cols = this.cols;
|
||||
|
||||
this._setup();
|
||||
super.reset();
|
||||
}
|
||||
}
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
import { IBuffer, IBufferSet } from 'common/buffer/Types';
|
||||
import { IEvent } from 'common/EventEmitter';
|
||||
import { IFunctionIdentifier, IParams } from 'common/parser/Types';
|
||||
import { ICoreTerminal, IDisposable, IMarker, ITerminalOptions } from 'common/Types';
|
||||
|
||||
export interface ITerminal extends ICoreTerminal {
|
||||
rows: number;
|
||||
cols: number;
|
||||
buffer: IBuffer;
|
||||
buffers: IBufferSet;
|
||||
markers: IMarker[];
|
||||
// TODO: We should remove options once components adopt optionsService
|
||||
options: ITerminalOptions;
|
||||
|
||||
onCursorMove: IEvent<void>;
|
||||
onData: IEvent<string>;
|
||||
onBinary: IEvent<string>;
|
||||
onLineFeed: IEvent<void>;
|
||||
onResize: IEvent<{ cols: number, rows: number }>;
|
||||
onTitleChange: IEvent<string>;
|
||||
resize(columns: number, rows: number): void;
|
||||
addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable;
|
||||
addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable;
|
||||
addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable;
|
||||
addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable;
|
||||
addMarker(cursorYOffset: number): IMarker | undefined;
|
||||
dispose(): void;
|
||||
clear(): void;
|
||||
write(data: string | Uint8Array, callback?: () => void): void;
|
||||
reset(): void;
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
/**
|
||||
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
import { deepStrictEqual, strictEqual, throws } from 'assert';
|
||||
import { Terminal } from 'headless/public/Terminal';
|
||||
|
||||
let term: Terminal;
|
||||
|
||||
describe('Headless API Tests', function(): void {
|
||||
beforeEach(() => {
|
||||
// Create default terminal to be used by most tests
|
||||
term = new Terminal();
|
||||
});
|
||||
|
||||
it('Default options', async () => {
|
||||
strictEqual(term.cols, 80);
|
||||
strictEqual(term.rows, 24);
|
||||
});
|
||||
|
||||
it('Proposed API check', async () => {
|
||||
term = new Terminal({ allowProposedApi: false });
|
||||
throws(() => term.buffer, (error) => error.message === 'You must set the allowProposedApi option to true to use proposed API');
|
||||
});
|
||||
|
||||
it('write', async () => {
|
||||
await writeSync('foo');
|
||||
await writeSync('bar');
|
||||
await writeSync('文');
|
||||
lineEquals(0, 'foobar文');
|
||||
});
|
||||
|
||||
it('write with callback', async () => {
|
||||
let result: string | undefined;
|
||||
await new Promise<void>(r => {
|
||||
term.write('foo', () => { result = 'a'; });
|
||||
term.write('bar', () => { result += 'b'; });
|
||||
term.write('文', () => {
|
||||
result += 'c';
|
||||
r();
|
||||
});
|
||||
});
|
||||
lineEquals(0, 'foobar文');
|
||||
strictEqual(result, 'abc');
|
||||
});
|
||||
|
||||
it('write - bytes (UTF8)', async () => {
|
||||
await writeSync(new Uint8Array([102, 111, 111])); // foo
|
||||
await writeSync(new Uint8Array([98, 97, 114])); // bar
|
||||
await writeSync(new Uint8Array([230, 150, 135])); // 文
|
||||
lineEquals(0, 'foobar文');
|
||||
});
|
||||
|
||||
it('write - bytes (UTF8) with callback', async () => {
|
||||
let result: string | undefined;
|
||||
await new Promise<void>(r => {
|
||||
term.write(new Uint8Array([102, 111, 111]), () => { result = 'A'; }); // foo
|
||||
term.write(new Uint8Array([98, 97, 114]), () => { result += 'B'; }); // bar
|
||||
term.write(new Uint8Array([230, 150, 135]), () => { // 文
|
||||
result += 'C';
|
||||
r();
|
||||
});
|
||||
});
|
||||
lineEquals(0, 'foobar文');
|
||||
strictEqual(result, 'ABC');
|
||||
});
|
||||
|
||||
it('writeln', async () => {
|
||||
await writelnSync('foo');
|
||||
await writelnSync('bar');
|
||||
await writelnSync('文');
|
||||
lineEquals(0, 'foo');
|
||||
lineEquals(1, 'bar');
|
||||
lineEquals(2, '文');
|
||||
});
|
||||
|
||||
it('writeln with callback', async () => {
|
||||
let result: string | undefined;
|
||||
await new Promise<void>(r => {
|
||||
term.writeln('foo', () => { result = '1'; });
|
||||
term.writeln('bar', () => { result += '2'; });
|
||||
term.writeln('文', () => {
|
||||
result += '3';
|
||||
r();
|
||||
});
|
||||
});
|
||||
lineEquals(0, 'foo');
|
||||
lineEquals(1, 'bar');
|
||||
lineEquals(2, '文');
|
||||
strictEqual(result, '123');
|
||||
});
|
||||
|
||||
it('writeln - bytes (UTF8)', async () => {
|
||||
await writelnSync(new Uint8Array([102, 111, 111]));
|
||||
await writelnSync(new Uint8Array([98, 97, 114]));
|
||||
await writelnSync(new Uint8Array([230, 150, 135]));
|
||||
lineEquals(0, 'foo');
|
||||
lineEquals(1, 'bar');
|
||||
lineEquals(2, '文');
|
||||
});
|
||||
|
||||
it('clear', async () => {
|
||||
term = new Terminal({ rows: 5 });
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await writeSync('\n\rtest' + i);
|
||||
}
|
||||
term.clear();
|
||||
strictEqual(term.buffer.active.length, 5);
|
||||
lineEquals(0, 'test9');
|
||||
for (let i = 1; i < 5; i++) {
|
||||
lineEquals(i, '');
|
||||
}
|
||||
});
|
||||
|
||||
it('getOption, setOption', async () => {
|
||||
strictEqual(term.getOption('scrollback'), 1000);
|
||||
term.setOption('scrollback', 50);
|
||||
strictEqual(term.getOption('scrollback'), 50);
|
||||
});
|
||||
|
||||
describe('loadAddon', () => {
|
||||
it('constructor', async () => {
|
||||
term = new Terminal({ cols: 5 });
|
||||
let cols = 0;
|
||||
term.loadAddon({
|
||||
activate: (t) => cols = t.cols,
|
||||
dispose: () => {}
|
||||
});
|
||||
strictEqual(cols, 5);
|
||||
});
|
||||
|
||||
it('dispose (addon)', async () => {
|
||||
let disposeCalled = false;
|
||||
const addon = {
|
||||
activate: () => {},
|
||||
dispose: () => disposeCalled = true
|
||||
};
|
||||
term.loadAddon(addon);
|
||||
strictEqual(disposeCalled, false);
|
||||
addon.dispose();
|
||||
strictEqual(disposeCalled, true);
|
||||
});
|
||||
|
||||
it('dispose (terminal)', async () => {
|
||||
let disposeCalled = false;
|
||||
term.loadAddon({
|
||||
activate: () => {},
|
||||
dispose: () => disposeCalled = true
|
||||
});
|
||||
strictEqual(disposeCalled, false);
|
||||
term.dispose();
|
||||
strictEqual(disposeCalled, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Events', () => {
|
||||
it('onCursorMove', async () => {
|
||||
let callCount = 0;
|
||||
term.onCursorMove(e => callCount++);
|
||||
await writeSync('foo');
|
||||
strictEqual(callCount, 1);
|
||||
await writeSync('bar');
|
||||
strictEqual(callCount, 2);
|
||||
});
|
||||
|
||||
it('onData', async () => {
|
||||
const calls: string[] = [];
|
||||
term.onData(e => calls.push(e));
|
||||
await writeSync('\x1b[5n'); // DSR Status Report
|
||||
deepStrictEqual(calls, ['\x1b[0n']);
|
||||
});
|
||||
|
||||
it('onLineFeed', async () => {
|
||||
let callCount = 0;
|
||||
term.onLineFeed(() => callCount++);
|
||||
await writelnSync('foo');
|
||||
strictEqual(callCount, 1);
|
||||
await writelnSync('bar');
|
||||
strictEqual(callCount, 2);
|
||||
});
|
||||
|
||||
it('onScroll', async () => {
|
||||
term = new Terminal({ rows: 5 });
|
||||
const calls: number[] = [];
|
||||
term.onScroll(e => calls.push(e));
|
||||
for (let i = 0; i < 4; i++) {
|
||||
await writelnSync('foo');
|
||||
}
|
||||
deepStrictEqual(calls, []);
|
||||
await writelnSync('bar');
|
||||
deepStrictEqual(calls, [1]);
|
||||
await writelnSync('baz');
|
||||
deepStrictEqual(calls, [1, 2]);
|
||||
});
|
||||
|
||||
it('onResize', async () => {
|
||||
const calls: [number, number][] = [];
|
||||
term.onResize(e => calls.push([e.cols, e.rows]));
|
||||
deepStrictEqual(calls, []);
|
||||
term.resize(10, 5);
|
||||
deepStrictEqual(calls, [[10, 5]]);
|
||||
term.resize(20, 15);
|
||||
deepStrictEqual(calls, [[10, 5], [20, 15]]);
|
||||
});
|
||||
|
||||
it('onTitleChange', async () => {
|
||||
const calls: string[] = [];
|
||||
term.onTitleChange(e => calls.push(e));
|
||||
deepStrictEqual(calls, []);
|
||||
await writeSync('\x1b]2;foo\x9c');
|
||||
deepStrictEqual(calls, ['foo']);
|
||||
});
|
||||
|
||||
it('onBell', async () => {
|
||||
const calls: boolean[] = [];
|
||||
term.onBell(() => calls.push(true));
|
||||
deepStrictEqual(calls, []);
|
||||
await writeSync('\x07');
|
||||
deepStrictEqual(calls, [true]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buffer', () => {
|
||||
it('cursorX, cursorY', async () => {
|
||||
term = new Terminal({ rows: 5, cols: 5 });
|
||||
strictEqual(term.buffer.active.cursorX, 0);
|
||||
strictEqual(term.buffer.active.cursorY, 0);
|
||||
await writeSync('foo');
|
||||
strictEqual(term.buffer.active.cursorX, 3);
|
||||
strictEqual(term.buffer.active.cursorY, 0);
|
||||
await writeSync('\n');
|
||||
strictEqual(term.buffer.active.cursorX, 3);
|
||||
strictEqual(term.buffer.active.cursorY, 1);
|
||||
await writeSync('\r');
|
||||
strictEqual(term.buffer.active.cursorX, 0);
|
||||
strictEqual(term.buffer.active.cursorY, 1);
|
||||
await writeSync('abcde');
|
||||
strictEqual(term.buffer.active.cursorX, 5);
|
||||
strictEqual(term.buffer.active.cursorY, 1);
|
||||
await writeSync('\n\r\n\n\n\n\n');
|
||||
strictEqual(term.buffer.active.cursorX, 0);
|
||||
strictEqual(term.buffer.active.cursorY, 4);
|
||||
});
|
||||
|
||||
it('viewportY', async () => {
|
||||
term = new Terminal({ rows: 5 });
|
||||
strictEqual(term.buffer.active.viewportY, 0);
|
||||
await writeSync('\n\n\n\n');
|
||||
strictEqual(term.buffer.active.viewportY, 0);
|
||||
await writeSync('\n');
|
||||
strictEqual(term.buffer.active.viewportY, 1);
|
||||
await writeSync('\n\n\n\n');
|
||||
strictEqual(term.buffer.active.viewportY, 5);
|
||||
term.scrollLines(-1);
|
||||
strictEqual(term.buffer.active.viewportY, 4);
|
||||
term.scrollToTop();
|
||||
strictEqual(term.buffer.active.viewportY, 0);
|
||||
});
|
||||
|
||||
it('baseY', async () => {
|
||||
term = new Terminal({ rows: 5 });
|
||||
strictEqual(term.buffer.active.baseY, 0);
|
||||
await writeSync('\n\n\n\n');
|
||||
strictEqual(term.buffer.active.baseY, 0);
|
||||
await writeSync('\n');
|
||||
strictEqual(term.buffer.active.baseY, 1);
|
||||
await writeSync('\n\n\n\n');
|
||||
strictEqual(term.buffer.active.baseY, 5);
|
||||
term.scrollLines(-1);
|
||||
strictEqual(term.buffer.active.baseY, 5);
|
||||
term.scrollToTop();
|
||||
strictEqual(term.buffer.active.baseY, 5);
|
||||
});
|
||||
|
||||
it('length', async () => {
|
||||
term = new Terminal({ rows: 5 });
|
||||
strictEqual(term.buffer.active.length, 5);
|
||||
await writeSync('\n\n\n\n');
|
||||
strictEqual(term.buffer.active.length, 5);
|
||||
await writeSync('\n');
|
||||
strictEqual(term.buffer.active.length, 6);
|
||||
await writeSync('\n\n\n\n');
|
||||
strictEqual(term.buffer.active.length, 10);
|
||||
});
|
||||
|
||||
describe('getLine', () => {
|
||||
it('invalid index', async () => {
|
||||
term = new Terminal({ rows: 5 });
|
||||
strictEqual(term.buffer.active.getLine(-1), undefined);
|
||||
strictEqual(term.buffer.active.getLine(5), undefined);
|
||||
});
|
||||
|
||||
it('isWrapped', async () => {
|
||||
term = new Terminal({ cols: 5 });
|
||||
strictEqual(term.buffer.active.getLine(0)!.isWrapped, false);
|
||||
strictEqual(term.buffer.active.getLine(1)!.isWrapped, false);
|
||||
await writeSync('abcde');
|
||||
strictEqual(term.buffer.active.getLine(0)!.isWrapped, false);
|
||||
strictEqual(term.buffer.active.getLine(1)!.isWrapped, false);
|
||||
await writeSync('f');
|
||||
strictEqual(term.buffer.active.getLine(0)!.isWrapped, false);
|
||||
strictEqual(term.buffer.active.getLine(1)!.isWrapped, true);
|
||||
});
|
||||
|
||||
it('translateToString', async () => {
|
||||
term = new Terminal({ cols: 5 });
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(), ' ');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(true), '');
|
||||
await writeSync('foo');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'foo ');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(true), 'foo');
|
||||
await writeSync('bar');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'fooba');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(true), 'fooba');
|
||||
strictEqual(term.buffer.active.getLine(1)!.translateToString(true), 'r');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(false, 1), 'ooba');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(false, 1, 3), 'oo');
|
||||
});
|
||||
|
||||
it('getCell', async () => {
|
||||
term = new Terminal({ cols: 5 });
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(-1), undefined);
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(5), undefined);
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getChars(), '');
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getWidth(), 1);
|
||||
await writeSync('a文');
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getChars(), 'a');
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getWidth(), 1);
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(1)!.getChars(), '文');
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(1)!.getWidth(), 2);
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(2)!.getChars(), '');
|
||||
strictEqual(term.buffer.active.getLine(0)!.getCell(2)!.getWidth(), 0);
|
||||
});
|
||||
});
|
||||
|
||||
it('active, normal, alternate', async () => {
|
||||
term = new Terminal({ cols: 5 });
|
||||
strictEqual(term.buffer.active.type, 'normal');
|
||||
strictEqual(term.buffer.normal.type, 'normal');
|
||||
strictEqual(term.buffer.alternate.type, 'alternate');
|
||||
|
||||
await writeSync('norm ');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'norm ');
|
||||
strictEqual(term.buffer.normal.getLine(0)!.translateToString(), 'norm ');
|
||||
strictEqual(term.buffer.alternate.getLine(0), undefined);
|
||||
|
||||
await writeSync('\x1b[?47h\r'); // use alternate screen buffer
|
||||
strictEqual(term.buffer.active.type, 'alternate');
|
||||
strictEqual(term.buffer.normal.type, 'normal');
|
||||
strictEqual(term.buffer.alternate.type, 'alternate');
|
||||
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(), ' ');
|
||||
await writeSync('alt ');
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'alt ');
|
||||
strictEqual(term.buffer.normal.getLine(0)!.translateToString(), 'norm ');
|
||||
strictEqual(term.buffer.alternate.getLine(0)!.translateToString(), 'alt ');
|
||||
|
||||
await writeSync('\x1b[?47l\r'); // use normal screen buffer
|
||||
strictEqual(term.buffer.active.type, 'normal');
|
||||
strictEqual(term.buffer.normal.type, 'normal');
|
||||
strictEqual(term.buffer.alternate.type, 'alternate');
|
||||
|
||||
strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'norm ');
|
||||
strictEqual(term.buffer.normal.getLine(0)!.translateToString(), 'norm ');
|
||||
strictEqual(term.buffer.alternate.getLine(0), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('modes', () => {
|
||||
it('defaults', () => {
|
||||
deepStrictEqual(term.modes, {
|
||||
applicationCursorKeysMode: false,
|
||||
applicationKeypadMode: false,
|
||||
bracketedPasteMode: false,
|
||||
insertMode: false,
|
||||
mouseTrackingMode: 'none',
|
||||
originMode: false,
|
||||
reverseWraparoundMode: false,
|
||||
sendFocusMode: false,
|
||||
wraparoundMode: true
|
||||
});
|
||||
});
|
||||
it('applicationCursorKeysMode', async () => {
|
||||
await writeSync('\x1b[?1h');
|
||||
strictEqual(term.modes.applicationCursorKeysMode, true);
|
||||
await writeSync('\x1b[?1l');
|
||||
strictEqual(term.modes.applicationCursorKeysMode, false);
|
||||
});
|
||||
it('applicationKeypadMode', async () => {
|
||||
await writeSync('\x1b[?66h');
|
||||
strictEqual(term.modes.applicationKeypadMode, true);
|
||||
await writeSync('\x1b[?66l');
|
||||
strictEqual(term.modes.applicationKeypadMode, false);
|
||||
});
|
||||
it('bracketedPasteMode', async () => {
|
||||
await writeSync('\x1b[?2004h');
|
||||
strictEqual(term.modes.bracketedPasteMode, true);
|
||||
await writeSync('\x1b[?2004l');
|
||||
strictEqual(term.modes.bracketedPasteMode, false);
|
||||
});
|
||||
it('insertMode', async () => {
|
||||
await writeSync('\x1b[4h');
|
||||
strictEqual(term.modes.insertMode, true);
|
||||
await writeSync('\x1b[4l');
|
||||
strictEqual(term.modes.insertMode, false);
|
||||
});
|
||||
it('mouseTrackingMode', async () => {
|
||||
await writeSync('\x1b[?9h');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'x10');
|
||||
await writeSync('\x1b[?9l');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'none');
|
||||
await writeSync('\x1b[?1000h');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'vt200');
|
||||
await writeSync('\x1b[?1000l');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'none');
|
||||
await writeSync('\x1b[?1002h');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'drag');
|
||||
await writeSync('\x1b[?1002l');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'none');
|
||||
await writeSync('\x1b[?1003h');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'any');
|
||||
await writeSync('\x1b[?1003l');
|
||||
strictEqual(term.modes.mouseTrackingMode, 'none');
|
||||
});
|
||||
it('originMode', async () => {
|
||||
await writeSync('\x1b[?6h');
|
||||
strictEqual(term.modes.originMode, true);
|
||||
await writeSync('\x1b[?6l');
|
||||
strictEqual(term.modes.originMode, false);
|
||||
});
|
||||
it('reverseWraparoundMode', async () => {
|
||||
await writeSync('\x1b[?45h');
|
||||
strictEqual(term.modes.reverseWraparoundMode, true);
|
||||
await writeSync('\x1b[?45l');
|
||||
strictEqual(term.modes.reverseWraparoundMode, false);
|
||||
});
|
||||
it('sendFocusMode', async () => {
|
||||
await writeSync('\x1b[?1004h');
|
||||
strictEqual(term.modes.sendFocusMode, true);
|
||||
await writeSync('\x1b[?1004l');
|
||||
strictEqual(term.modes.sendFocusMode, false);
|
||||
});
|
||||
it('wraparoundMode', async () => {
|
||||
await writeSync('\x1b[?7h');
|
||||
strictEqual(term.modes.wraparoundMode, true);
|
||||
await writeSync('\x1b[?7l');
|
||||
strictEqual(term.modes.wraparoundMode, false);
|
||||
});
|
||||
});
|
||||
|
||||
it('dispose', async () => {
|
||||
term.dispose();
|
||||
strictEqual((term as any)._core._isDisposed, true);
|
||||
});
|
||||
});
|
||||
|
||||
function writeSync(text: string | Uint8Array): Promise<void> {
|
||||
return new Promise<void>(r => term.write(text, r));
|
||||
}
|
||||
|
||||
function writelnSync(text: string | Uint8Array): Promise<void> {
|
||||
return new Promise<void>(r => term.writeln(text, r));
|
||||
}
|
||||
|
||||
function lineEquals(index: number, text: string): void {
|
||||
strictEqual(term.buffer.active.getLine(index)!.translateToString(true), text);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
import { IEvent } from 'common/EventEmitter';
|
||||
import { BufferNamespaceApi } from 'common/public/BufferNamespaceApi';
|
||||
import { ParserApi } from 'common/public/ParserApi';
|
||||
import { UnicodeApi } from 'common/public/UnicodeApi';
|
||||
import { IBufferNamespace as IBufferNamespaceApi, IMarker, IModes, IParser, ITerminalAddon, ITerminalOptions, IUnicodeHandling, Terminal as ITerminalApi } from 'xterm-headless';
|
||||
import { Terminal as TerminalCore } from 'headless/Terminal';
|
||||
import { AddonManager } from 'common/public/AddonManager';
|
||||
|
||||
export class Terminal implements ITerminalApi {
|
||||
private _core: TerminalCore;
|
||||
private _addonManager: AddonManager;
|
||||
private _parser: IParser | undefined;
|
||||
private _buffer: BufferNamespaceApi | undefined;
|
||||
|
||||
constructor(options?: ITerminalOptions) {
|
||||
this._core = new TerminalCore(options);
|
||||
this._addonManager = new AddonManager();
|
||||
}
|
||||
|
||||
private _checkProposedApi(): void {
|
||||
if (!this._core.optionsService.options.allowProposedApi) {
|
||||
throw new Error('You must set the allowProposedApi option to true to use proposed API');
|
||||
}
|
||||
}
|
||||
|
||||
public get onBell(): IEvent<void> { return this._core.onBell; }
|
||||
public get onBinary(): IEvent<string> { return this._core.onBinary; }
|
||||
public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }
|
||||
public get onData(): IEvent<string> { return this._core.onData; }
|
||||
public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }
|
||||
public get onResize(): IEvent<{ cols: number, rows: number }> { return this._core.onResize; }
|
||||
public get onScroll(): IEvent<number> { return this._core.onScroll; }
|
||||
public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }
|
||||
|
||||
public get parser(): IParser {
|
||||
this._checkProposedApi();
|
||||
if (!this._parser) {
|
||||
this._parser = new ParserApi(this._core);
|
||||
}
|
||||
return this._parser;
|
||||
}
|
||||
public get unicode(): IUnicodeHandling {
|
||||
this._checkProposedApi();
|
||||
return new UnicodeApi(this._core);
|
||||
}
|
||||
public get rows(): number { return this._core.rows; }
|
||||
public get cols(): number { return this._core.cols; }
|
||||
public get buffer(): IBufferNamespaceApi {
|
||||
this._checkProposedApi();
|
||||
if (!this._buffer) {
|
||||
this._buffer = new BufferNamespaceApi(this._core);
|
||||
}
|
||||
return this._buffer;
|
||||
}
|
||||
public get markers(): ReadonlyArray<IMarker> {
|
||||
this._checkProposedApi();
|
||||
return this._core.markers;
|
||||
}
|
||||
public get modes(): IModes {
|
||||
const m = this._core.coreService.decPrivateModes;
|
||||
let mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any' = 'none';
|
||||
switch (this._core.coreMouseService.activeProtocol) {
|
||||
case 'X10': mouseTrackingMode = 'x10'; break;
|
||||
case 'VT200': mouseTrackingMode = 'vt200'; break;
|
||||
case 'DRAG': mouseTrackingMode = 'drag'; break;
|
||||
case 'ANY': mouseTrackingMode = 'any'; break;
|
||||
}
|
||||
return {
|
||||
applicationCursorKeysMode: m.applicationCursorKeys,
|
||||
applicationKeypadMode: m.applicationKeypad,
|
||||
bracketedPasteMode: m.bracketedPasteMode,
|
||||
insertMode: this._core.coreService.modes.insertMode,
|
||||
mouseTrackingMode: mouseTrackingMode,
|
||||
originMode: m.origin,
|
||||
reverseWraparoundMode: m.reverseWraparound,
|
||||
sendFocusMode: m.sendFocus,
|
||||
wraparoundMode: m.wraparound
|
||||
};
|
||||
}
|
||||
public resize(columns: number, rows: number): void {
|
||||
this._verifyIntegers(columns, rows);
|
||||
this._core.resize(columns, rows);
|
||||
}
|
||||
public registerMarker(cursorYOffset: number): IMarker | undefined {
|
||||
this._checkProposedApi();
|
||||
this._verifyIntegers(cursorYOffset);
|
||||
return this._core.addMarker(cursorYOffset);
|
||||
}
|
||||
public addMarker(cursorYOffset: number): IMarker | undefined {
|
||||
return this.registerMarker(cursorYOffset);
|
||||
}
|
||||
public dispose(): void {
|
||||
this._addonManager.dispose();
|
||||
this._core.dispose();
|
||||
}
|
||||
public scrollLines(amount: number): void {
|
||||
this._verifyIntegers(amount);
|
||||
this._core.scrollLines(amount);
|
||||
}
|
||||
public scrollPages(pageCount: number): void {
|
||||
this._verifyIntegers(pageCount);
|
||||
this._core.scrollPages(pageCount);
|
||||
}
|
||||
public scrollToTop(): void {
|
||||
this._core.scrollToTop();
|
||||
}
|
||||
public scrollToBottom(): void {
|
||||
this._core.scrollToBottom();
|
||||
}
|
||||
public scrollToLine(line: number): void {
|
||||
this._verifyIntegers(line);
|
||||
this._core.scrollToLine(line);
|
||||
}
|
||||
public clear(): void {
|
||||
this._core.clear();
|
||||
}
|
||||
public write(data: string | Uint8Array, callback?: () => void): void {
|
||||
this._core.write(data, callback);
|
||||
}
|
||||
public writeUtf8(data: Uint8Array, callback?: () => void): void {
|
||||
this._core.write(data, callback);
|
||||
}
|
||||
public writeln(data: string | Uint8Array, callback?: () => void): void {
|
||||
this._core.write(data);
|
||||
this._core.write('\r\n', callback);
|
||||
}
|
||||
public getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'logLevel' | 'rendererType' | 'termName' | 'wordSeparator'): string;
|
||||
public getOption(key: 'allowTransparency' | 'altClickMovesCursor' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'visualBell'): boolean;
|
||||
public getOption(key: 'cols' | 'fontSize' | 'letterSpacing' | 'lineHeight' | 'rows' | 'tabStopWidth' | 'scrollback'): number;
|
||||
public getOption(key: string): any;
|
||||
public getOption(key: any): any {
|
||||
return this._core.optionsService.getOption(key);
|
||||
}
|
||||
public setOption(key: 'bellSound' | 'fontFamily' | 'termName' | 'wordSeparator', value: string): void;
|
||||
public setOption(key: 'fontWeight' | 'fontWeightBold', value: 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number): void;
|
||||
public setOption(key: 'logLevel', value: 'debug' | 'info' | 'warn' | 'error' | 'off'): void;
|
||||
public setOption(key: 'bellStyle', value: 'none' | 'visual' | 'sound' | 'both'): void;
|
||||
public setOption(key: 'cursorStyle', value: 'block' | 'underline' | 'bar'): void;
|
||||
public setOption(key: 'allowTransparency' | 'altClickMovesCursor' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'visualBell', value: boolean): void;
|
||||
public setOption(key: 'fontSize' | 'letterSpacing' | 'lineHeight' | 'tabStopWidth' | 'scrollback', value: number): void;
|
||||
public setOption(key: 'cols' | 'rows', value: number): void;
|
||||
public setOption(key: string, value: any): void;
|
||||
public setOption(key: any, value: any): void {
|
||||
this._core.optionsService.setOption(key, value);
|
||||
}
|
||||
public reset(): void {
|
||||
this._core.reset();
|
||||
}
|
||||
public loadAddon(addon: ITerminalAddon): void {
|
||||
// TODO: This could cause issues if the addon calls renderer apis
|
||||
return this._addonManager.loadAddon(this as any, addon);
|
||||
}
|
||||
|
||||
private _verifyIntegers(...values: number[]): void {
|
||||
for (const value of values) {
|
||||
if (value === Infinity || isNaN(value) || value % 1 !== 0) {
|
||||
throw new Error('This API only accepts integers');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"extends": "../tsconfig-library-base",
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"es2015",
|
||||
"es2016.Array.Include"
|
||||
],
|
||||
"outDir": "../../out",
|
||||
"types": [
|
||||
"../../node_modules/@types/mocha",
|
||||
"../../node_modules/@types/node"
|
||||
],
|
||||
"baseUrl": "../",
|
||||
"paths": {
|
||||
"common/*": [ "./common/*" ]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"./**/*",
|
||||
"../../typings/xterm.d.ts", // common/Types.d.ts imports from 'xterm'
|
||||
"../../typings/xterm-headless.d.ts"
|
||||
],
|
||||
"references": [
|
||||
{ "path": "../common" }
|
||||
]
|
||||
}
|
||||
+98
-12
@@ -69,12 +69,9 @@ describe('API Integration Tests', function(): void {
|
||||
it('write - bytes (UTF8)', async () => {
|
||||
await openTerminal(page);
|
||||
await page.evaluate(`
|
||||
// foo
|
||||
window.term.write(new Uint8Array([102, 111, 111]));
|
||||
// bar
|
||||
window.term.write(new Uint8Array([98, 97, 114]));
|
||||
// 文
|
||||
window.term.write(new Uint8Array([230, 150, 135]));
|
||||
window.term.write(new Uint8Array([102, 111, 111])); // foo
|
||||
window.term.write(new Uint8Array([98, 97, 114])); // bar
|
||||
window.term.write(new Uint8Array([230, 150, 135])); // 文
|
||||
`);
|
||||
await pollFor(page, `window.term.buffer.active.getLine(0).translateToString(true)`, 'foobar文');
|
||||
});
|
||||
@@ -82,12 +79,9 @@ describe('API Integration Tests', function(): void {
|
||||
it('write - bytes (UTF8) with callback', async () => {
|
||||
await openTerminal(page);
|
||||
await page.evaluate(`
|
||||
// foo
|
||||
window.term.write(new Uint8Array([102, 111, 111]), () => { window.__x = 'A'; });
|
||||
// bar
|
||||
window.term.write(new Uint8Array([98, 97, 114]), () => { window.__x += 'B'; });
|
||||
// 文
|
||||
window.term.write(new Uint8Array([230, 150, 135]), () => { window.__x += 'C'; });
|
||||
window.term.write(new Uint8Array([102, 111, 111]), () => { window.__x = 'A'; }); // foo
|
||||
window.term.write(new Uint8Array([98, 97, 114]), () => { window.__x += 'B'; }); // bar
|
||||
window.term.write(new Uint8Array([230, 150, 135]), () => { window.__x += 'C'; }); // 文
|
||||
`);
|
||||
await pollFor(page, `window.term.buffer.active.getLine(0).translateToString(true)`, 'foobar文');
|
||||
await pollFor(page, `window.__x`, 'ABC');
|
||||
@@ -568,6 +562,98 @@ describe('API Integration Tests', function(): void {
|
||||
});
|
||||
});
|
||||
|
||||
describe('modes', () => {
|
||||
it('defaults', async () => {
|
||||
await openTerminal(page);
|
||||
assert.deepStrictEqual(await page.evaluate(`window.term.modes`), {
|
||||
applicationCursorKeysMode: false,
|
||||
applicationKeypadMode: false,
|
||||
bracketedPasteMode: false,
|
||||
insertMode: false,
|
||||
mouseTrackingMode: 'none',
|
||||
originMode: false,
|
||||
reverseWraparoundMode: false,
|
||||
sendFocusMode: false,
|
||||
wraparoundMode: true
|
||||
});
|
||||
});
|
||||
it('applicationCursorKeysMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?1h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.applicationCursorKeysMode`), true);
|
||||
await writeSync(page, '\\x1b[?1l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.applicationCursorKeysMode`), false);
|
||||
});
|
||||
it('applicationKeypadMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?66h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.applicationKeypadMode`), true);
|
||||
await writeSync(page, '\\x1b[?66l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.applicationKeypadMode`), false);
|
||||
});
|
||||
it('bracketedPasteMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?2004h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.bracketedPasteMode`), true);
|
||||
await writeSync(page, '\\x1b[?2004l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.bracketedPasteMode`), false);
|
||||
});
|
||||
it('insertMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[4h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.insertMode`), true);
|
||||
await writeSync(page, '\\x1b[4l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.insertMode`), false);
|
||||
});
|
||||
it('mouseTrackingMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?9h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'x10');
|
||||
await writeSync(page, '\\x1b[?9l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'none');
|
||||
await writeSync(page, '\\x1b[?1000h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'vt200');
|
||||
await writeSync(page, '\\x1b[?1000l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'none');
|
||||
await writeSync(page, '\\x1b[?1002h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'drag');
|
||||
await writeSync(page, '\\x1b[?1002l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'none');
|
||||
await writeSync(page, '\\x1b[?1003h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'any');
|
||||
await writeSync(page, '\\x1b[?1003l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.mouseTrackingMode`), 'none');
|
||||
});
|
||||
it('originMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?6h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.originMode`), true);
|
||||
await writeSync(page, '\\x1b[?6l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.originMode`), false);
|
||||
});
|
||||
it('reverseWraparoundMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?45h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.reverseWraparoundMode`), true);
|
||||
await writeSync(page, '\\x1b[?45l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.reverseWraparoundMode`), false);
|
||||
});
|
||||
it('sendFocusMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?1004h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.sendFocusMode`), true);
|
||||
await writeSync(page, '\\x1b[?1004l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.sendFocusMode`), false);
|
||||
});
|
||||
it('wraparoundMode', async () => {
|
||||
await openTerminal(page);
|
||||
await writeSync(page, '\\x1b[?7h');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.wraparoundMode`), true);
|
||||
await writeSync(page, '\\x1b[?7l');
|
||||
assert.strictEqual(await page.evaluate(`window.term.modes.wraparoundMode`), false);
|
||||
});
|
||||
});
|
||||
|
||||
it('dispose', async () => {
|
||||
await page.evaluate(`
|
||||
window.term = new Terminal();
|
||||
|
||||
@@ -40,42 +40,42 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
beforeEach(() => {
|
||||
parser = new EscapeSequenceParser();
|
||||
parser.setPrintHandler((data, start, end) => {});
|
||||
parser.registerCsiHandler({final: '@'}, params => true);
|
||||
parser.registerCsiHandler({final: 'A'}, params => true);
|
||||
parser.registerCsiHandler({final: 'B'}, params => true);
|
||||
parser.registerCsiHandler({final: 'C'}, params => true);
|
||||
parser.registerCsiHandler({final: 'D'}, params => true);
|
||||
parser.registerCsiHandler({final: 'E'}, params => true);
|
||||
parser.registerCsiHandler({final: 'F'}, params => true);
|
||||
parser.registerCsiHandler({final: 'G'}, params => true);
|
||||
parser.registerCsiHandler({final: 'H'}, params => true);
|
||||
parser.registerCsiHandler({final: 'I'}, params => true);
|
||||
parser.registerCsiHandler({final: 'J'}, params => true);
|
||||
parser.registerCsiHandler({final: 'K'}, params => true);
|
||||
parser.registerCsiHandler({final: 'L'}, params => true);
|
||||
parser.registerCsiHandler({final: 'M'}, params => true);
|
||||
parser.registerCsiHandler({final: 'P'}, params => true);
|
||||
parser.registerCsiHandler({final: 'S'}, params => true);
|
||||
parser.registerCsiHandler({final: 'T'}, params => true);
|
||||
parser.registerCsiHandler({final: 'X'}, params => true);
|
||||
parser.registerCsiHandler({final: 'Z'}, params => true);
|
||||
parser.registerCsiHandler({final: '`'}, params => true);
|
||||
parser.registerCsiHandler({final: 'a'}, params => true);
|
||||
parser.registerCsiHandler({final: 'b'}, params => true);
|
||||
parser.registerCsiHandler({final: 'c'}, params => true);
|
||||
parser.registerCsiHandler({final: 'd'}, params => true);
|
||||
parser.registerCsiHandler({final: 'e'}, params => true);
|
||||
parser.registerCsiHandler({final: 'f'}, params => true);
|
||||
parser.registerCsiHandler({final: 'g'}, params => true);
|
||||
parser.registerCsiHandler({final: 'h'}, params => true);
|
||||
parser.registerCsiHandler({final: 'l'}, params => true);
|
||||
parser.registerCsiHandler({final: 'm'}, params => true);
|
||||
parser.registerCsiHandler({final: 'n'}, params => true);
|
||||
parser.registerCsiHandler({final: 'p'}, params => true);
|
||||
parser.registerCsiHandler({final: 'q'}, params => true);
|
||||
parser.registerCsiHandler({final: 'r'}, params => true);
|
||||
parser.registerCsiHandler({final: 's'}, params => true);
|
||||
parser.registerCsiHandler({final: 'u'}, params => true);
|
||||
parser.registerCsiHandler({ final: '@' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'A' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'B' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'C' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'D' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'E' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'F' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'G' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'H' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'I' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'J' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'K' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'L' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'M' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'P' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'S' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'T' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'X' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'Z' }, params => true);
|
||||
parser.registerCsiHandler({ final: '`' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'a' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'b' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'c' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'd' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'e' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'f' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'g' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'h' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'l' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'm' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'n' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'p' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'q' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'r' }, params => true);
|
||||
parser.registerCsiHandler({ final: 's' }, params => true);
|
||||
parser.registerCsiHandler({ final: 'u' }, params => true);
|
||||
parser.setExecuteHandler(C0.BEL, () => true);
|
||||
parser.setExecuteHandler(C0.LF, () => true);
|
||||
parser.setExecuteHandler(C0.VT, () => true);
|
||||
@@ -90,24 +90,24 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
parser.setExecuteHandler(C1.HTS, () => true);
|
||||
parser.registerOscHandler(0, new OscHandler(data => true));
|
||||
parser.registerOscHandler(1, new FastOscHandler());
|
||||
parser.registerEscHandler({final: '7'}, () => true);
|
||||
parser.registerEscHandler({final: '8'}, () => true);
|
||||
parser.registerEscHandler({final: 'D'}, () => true);
|
||||
parser.registerEscHandler({final: 'E'}, () => true);
|
||||
parser.registerEscHandler({final: 'H'}, () => true);
|
||||
parser.registerEscHandler({final: 'M'}, () => true);
|
||||
parser.registerEscHandler({final: '='}, () => true);
|
||||
parser.registerEscHandler({final: '>'}, () => true);
|
||||
parser.registerEscHandler({final: 'c'}, () => true);
|
||||
parser.registerEscHandler({final: 'n'}, () => true);
|
||||
parser.registerEscHandler({final: 'o'}, () => true);
|
||||
parser.registerEscHandler({final: '|'}, () => true);
|
||||
parser.registerEscHandler({final: '}'}, () => true);
|
||||
parser.registerEscHandler({final: '~'}, () => true);
|
||||
parser.registerEscHandler({intermediates: '%', final: '@'}, () => true);
|
||||
parser.registerEscHandler({intermediates: '%', final: 'G'}, () => true);
|
||||
parser.registerDcsHandler({final: 'p'}, new DcsHandler(data => true));
|
||||
parser.registerDcsHandler({final: 'q'}, new FastDcsHandler());
|
||||
parser.registerEscHandler({ final: '7' }, () => true);
|
||||
parser.registerEscHandler({ final: '8' }, () => true);
|
||||
parser.registerEscHandler({ final: 'D' }, () => true);
|
||||
parser.registerEscHandler({ final: 'E' }, () => true);
|
||||
parser.registerEscHandler({ final: 'H' }, () => true);
|
||||
parser.registerEscHandler({ final: 'M' }, () => true);
|
||||
parser.registerEscHandler({ final: '=' }, () => true);
|
||||
parser.registerEscHandler({ final: '>' }, () => true);
|
||||
parser.registerEscHandler({ final: 'c' }, () => true);
|
||||
parser.registerEscHandler({ final: 'n' }, () => true);
|
||||
parser.registerEscHandler({ final: 'o' }, () => true);
|
||||
parser.registerEscHandler({ final: '|' }, () => true);
|
||||
parser.registerEscHandler({ final: '}' }, () => true);
|
||||
parser.registerEscHandler({ final: '~' }, () => true);
|
||||
parser.registerEscHandler({ intermediates: '%', final: '@' }, () => true);
|
||||
parser.registerEscHandler({ intermediates: '%', final: 'G' }, () => true);
|
||||
parser.registerDcsHandler({ final: 'p' }, new DcsHandler(data => true));
|
||||
parser.registerDcsHandler({ final: 'q' }, new FastDcsHandler());
|
||||
});
|
||||
|
||||
perfContext('PRINT - a', () => {
|
||||
@@ -121,8 +121,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', async () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('EXECUTE - \\n', () => {
|
||||
@@ -136,8 +136,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('ESCAPE - ESC E', () => {
|
||||
@@ -151,8 +151,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('ESCAPE with collect - ESC % G', () => {
|
||||
@@ -166,8 +166,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('CSI - CSI A', () => {
|
||||
@@ -181,8 +181,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('CSI with collect - CSI ? p', () => {
|
||||
@@ -196,8 +196,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('CSI with params (short) - CSI 1;2 m', () => {
|
||||
@@ -211,8 +211,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('CSI with params (long) - CSI 1;2;3;4;5;6;7;8;9;0 m', () => {
|
||||
@@ -226,8 +226,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('OSC string interface (short seq) - OSC 0;hi ST', () => {
|
||||
@@ -241,8 +241,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('OSC string interface (long seq) - OSC 0;<text> ST', () => {
|
||||
@@ -256,8 +256,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('OSC class interface (short seq) - OSC 0;hi ST', () => {
|
||||
@@ -271,8 +271,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('OSC class interface (long seq) - OSC 0;<text> ST', () => {
|
||||
@@ -286,8 +286,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('DCS string interface (short seq)', () => {
|
||||
@@ -301,8 +301,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', async () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('DCS string interface (long seq)', () => {
|
||||
@@ -316,8 +316,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', async () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('DCS class interface (short seq)', () => {
|
||||
@@ -331,8 +331,8 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', async () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('DCS class interface (long seq)', () => {
|
||||
@@ -346,7 +346,7 @@ perfContext('Parser throughput - 50MB data', () => {
|
||||
});
|
||||
new ThroughputRuntimeCase('', async () => {
|
||||
parser.parse(parsed, parsed.length);
|
||||
return {payloadSize: parsed.length};
|
||||
}, {fork: true}).showAverageThroughput();
|
||||
return { payloadSize: parsed.length };
|
||||
}, { fork: true }).showAverageThroughput();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -47,22 +47,22 @@ perfContext('Terminal: ls -lR /usr/lib', () => {
|
||||
perfContext('write/string/async', () => {
|
||||
let terminal: Terminal;
|
||||
before(() => {
|
||||
terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000});
|
||||
terminal = new Terminal({ cols: 80, rows: 25, scrollback: 1000 });
|
||||
});
|
||||
new ThroughputRuntimeCase('', async () => {
|
||||
await new Promise<void>(res => terminal.write(content, res));
|
||||
return {payloadSize: contentUtf8.length};
|
||||
}, {fork: false}).showAverageThroughput();
|
||||
return { payloadSize: contentUtf8.length };
|
||||
}, { fork: false }).showAverageThroughput();
|
||||
});
|
||||
|
||||
perfContext('write/Utf8/async', () => {
|
||||
let terminal: Terminal;
|
||||
before(() => {
|
||||
terminal = new Terminal({cols: 80, rows: 25, scrollback: 1000});
|
||||
terminal = new Terminal({ cols: 80, rows: 25, scrollback: 1000 });
|
||||
});
|
||||
new ThroughputRuntimeCase('', async () => {
|
||||
await new Promise<void>(res => terminal.write(content, res));
|
||||
return {payloadSize: contentUtf8.length};
|
||||
}, {fork: false}).showAverageThroughput();
|
||||
return { payloadSize: contentUtf8.length };
|
||||
}, { fork: false }).showAverageThroughput();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"include": [],
|
||||
"references": [
|
||||
{ "path": "./src/browser" },
|
||||
{ "path": "./src/headless" },
|
||||
{ "path": "./test/api" },
|
||||
{ "path": "./test/benchmark" },
|
||||
{ "path": "./addons/xterm-addon-attach" },
|
||||
|
||||
Vendored
+1313
File diff suppressed because it is too large
Load Diff
Vendored
+79
-19
@@ -90,6 +90,14 @@ declare module 'xterm' {
|
||||
*/
|
||||
cursorWidth?: number;
|
||||
|
||||
/**
|
||||
* Whether to draw custom glyphs for block element and box drawing characters instead of using
|
||||
* the font. This should typically result in better rendering with continuous lines, even when
|
||||
* line height and letter spacing is used. Note that this doesn't work with the DOM renderer
|
||||
* which renders all characters using the font. The default is true.
|
||||
*/
|
||||
customGlyphs?: boolean;
|
||||
|
||||
/**
|
||||
* Whether input should be disabled.
|
||||
*/
|
||||
@@ -622,6 +630,11 @@ declare module 'xterm' {
|
||||
*/
|
||||
readonly unicode: IUnicodeHandling;
|
||||
|
||||
/**
|
||||
* Gets the terminal modes as set by SM/DECSET.
|
||||
*/
|
||||
readonly modes: IModes;
|
||||
|
||||
/**
|
||||
* Natural language strings that can be localized.
|
||||
*/
|
||||
@@ -634,6 +647,12 @@ declare module 'xterm' {
|
||||
*/
|
||||
constructor(options?: ITerminalOptions);
|
||||
|
||||
/**
|
||||
* Adds an event listener for when the bell is triggered.
|
||||
* @returns an `IDisposable` to stop listening.
|
||||
*/
|
||||
onBell: IEvent<void>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when a binary event fires. This is used to
|
||||
* enable non UTF-8 conformant binary messages to be sent to the backend.
|
||||
@@ -674,19 +693,6 @@ declare module 'xterm' {
|
||||
*/
|
||||
onLineFeed: IEvent<void>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when a scroll occurs. The event value is the
|
||||
* new position of the viewport.
|
||||
* @returns an `IDisposable` to stop listening.
|
||||
*/
|
||||
onScroll: IEvent<number>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when a selection change occurs.
|
||||
* @returns an `IDisposable` to stop listening.
|
||||
*/
|
||||
onSelectionChange: IEvent<void>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when rows are rendered. The event value
|
||||
* contains the start row and end rows of the rendered area (ranges from `0`
|
||||
@@ -702,6 +708,19 @@ declare module 'xterm' {
|
||||
*/
|
||||
onResize: IEvent<{ cols: number, rows: number }>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when a scroll occurs. The event value is the
|
||||
* new position of the viewport.
|
||||
* @returns an `IDisposable` to stop listening.
|
||||
*/
|
||||
onScroll: IEvent<number>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when a selection change occurs.
|
||||
* @returns an `IDisposable` to stop listening.
|
||||
*/
|
||||
onSelectionChange: IEvent<void>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when an OSC 0 or OSC 2 title change occurs.
|
||||
* The event value is the new title.
|
||||
@@ -709,12 +728,6 @@ declare module 'xterm' {
|
||||
*/
|
||||
onTitleChange: IEvent<string>;
|
||||
|
||||
/**
|
||||
* Adds an event listener for when the bell is triggered.
|
||||
* @returns an `IDisposable` to stop listening.
|
||||
*/
|
||||
onBell: IEvent<void>;
|
||||
|
||||
/**
|
||||
* Unfocus the terminal.
|
||||
*/
|
||||
@@ -1622,4 +1635,51 @@ declare module 'xterm' {
|
||||
*/
|
||||
activeVersion: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminal modes as set by SM/DECSET.
|
||||
*/
|
||||
export interface IModes {
|
||||
/**
|
||||
* Application Cursor Keys (DECCKM): `CSI ? 1 h`
|
||||
*/
|
||||
readonly applicationCursorKeysMode: boolean;
|
||||
/**
|
||||
* Application Keypad Mode (DECNKM): `CSI ? 6 6 h`
|
||||
*/
|
||||
readonly applicationKeypadMode: boolean;
|
||||
/**
|
||||
* Bracketed Paste Mode: `CSI ? 2 0 0 4 h`
|
||||
*/
|
||||
readonly bracketedPasteMode: boolean;
|
||||
/**
|
||||
* Insert Mode (IRM): `CSI 4 h`
|
||||
*/
|
||||
readonly insertMode: boolean;
|
||||
/**
|
||||
* Mouse Tracking, this can be one of the following:
|
||||
* - none: This is the default value and can be reset with DECRST
|
||||
* - x10: Send Mouse X & Y on button press `CSI ? 9 h`
|
||||
* - vt200: Send Mouse X & Y on button press and release `CSI ? 1 0 0 0 h`
|
||||
* - drag: Use Cell Motion Mouse Tracking `CSI ? 1 0 0 2 h`
|
||||
* - any: Use All Motion Mouse Tracking `CSI ? 1 0 0 3 h`
|
||||
*/
|
||||
readonly mouseTrackingMode: 'none' | 'x10' | 'vt200' | 'drag' | 'any';
|
||||
/**
|
||||
* Origin Mode (DECOM): `CSI ? 6 h`
|
||||
*/
|
||||
readonly originMode: boolean;
|
||||
/**
|
||||
* Reverse-wraparound Mode: `CSI ? 4 5 h`
|
||||
*/
|
||||
readonly reverseWraparoundMode: boolean;
|
||||
/**
|
||||
* Send FocusIn/FocusOut events: `CSI ? 1 0 0 4 h`
|
||||
*/
|
||||
readonly sendFocusMode: boolean;
|
||||
/**
|
||||
* Auto-Wrap Mode (DECAWM): `CSI ? 7 h`
|
||||
*/
|
||||
readonly wraparoundMode: boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* This webpack config does a production build for xterm.js headless. It works by taking the output
|
||||
* from tsc (via `yarn watch` or `yarn prebuild`) which are put into `out/` and webpacks them into a
|
||||
* production mode umd library module in `lib-headless/`. The aliases are used fix up the absolute
|
||||
* paths output by tsc (because of `baseUrl` and `paths` in `tsconfig.json`.
|
||||
*/
|
||||
module.exports = {
|
||||
entry: './out/headless/public/Terminal.js',
|
||||
devtool: 'source-map',
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.js$/,
|
||||
use: ["source-map-loader"],
|
||||
enforce: "pre",
|
||||
exclude: /node_modules/
|
||||
}
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
modules: ['./node_modules'],
|
||||
extensions: [ '.js' ],
|
||||
alias: {
|
||||
common: path.resolve('./out/common'),
|
||||
headless: path.resolve('./out/headless')
|
||||
}
|
||||
},
|
||||
output: {
|
||||
filename: 'xterm-headless.js',
|
||||
path: path.resolve('./headless/lib-headless'),
|
||||
library: {
|
||||
type: 'commonjs'
|
||||
}
|
||||
},
|
||||
mode: 'production'
|
||||
};
|
||||
@@ -3356,9 +3356,9 @@ path-key@^3.0.0, path-key@^3.1.0:
|
||||
integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==
|
||||
|
||||
path-parse@^1.0.6:
|
||||
version "1.0.6"
|
||||
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c"
|
||||
integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==
|
||||
version "1.0.7"
|
||||
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735"
|
||||
integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==
|
||||
|
||||
path-to-regexp@0.1.7:
|
||||
version "0.1.7"
|
||||
|
||||
Reference in New Issue
Block a user