diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile
index e5736562..141f7711 100644
--- a/.devcontainer/Dockerfile
+++ b/.devcontainer/Dockerfile
@@ -1,4 +1,4 @@
-FROM node:10
+FROM node:14
# Configure apt
ENV DEBIAN_FRONTEND=noninteractive
diff --git a/.eslintrc.json b/.eslintrc.json
index 8c416f15..427c7a16 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -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",
@@ -43,10 +44,11 @@
"@typescript-eslint/array-type": [
"warn",
{
- "default": "array-simple",
+ "default": "array",
"readonly": "generic"
}
],
+ "@typescript-eslint/consistent-type-assertions": "warn",
"@typescript-eslint/consistent-type-definitions": "warn",
"@typescript-eslint/explicit-function-return-type": [
"warn",
@@ -151,6 +153,10 @@
"warn",
"never"
],
+ "object-curly-spacing": [
+ "warn",
+ "always"
+ ],
"prefer-const": "warn",
"spaced-comment": [
"warn",
@@ -160,5 +166,13 @@
"exceptions": ["-"]
}
]
- }
+ },
+ "overrides": [
+ {
+ "files": ["**/*.test.ts"],
+ "rules": {
+ "object-curly-spacing": "off"
+ }
+ }
+ ]
}
diff --git a/.mocha.env b/.mocha.env
new file mode 100644
index 00000000..78a9f930
--- /dev/null
+++ b/.mocha.env
@@ -0,0 +1 @@
+NODE_PATH=./out
diff --git a/.mocharc.yml b/.mocharc.yml
new file mode 100644
index 00000000..c19fe15a
--- /dev/null
+++ b/.mocharc.yml
@@ -0,0 +1,11 @@
+require:
+ - source-map-support/register
+spec:
+ - out/**/*.test.js
+ - addons/**/out/*.test.js
+watch-files:
+ - out/**/*.js
+ - addons/**/out/*.js
+reporter: spec
+color: true
+check-leaks: true
diff --git a/.vscode/settings.json b/.vscode/settings.json
index f07ca545..9fa94d5f 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,4 +1,5 @@
{
"typescript.preferences.importModuleSpecifier": "non-relative",
- "typescript.preferences.quoteStyle": "single"
+ "typescript.preferences.quoteStyle": "single",
+ "mochaExplorer.envPath": ".mocha.env"
}
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
index 2f752faf..4d268f61 100644
--- a/.vscode/tasks.json
+++ b/.vscode/tasks.json
@@ -1,51 +1,70 @@
{
- "version": "2.0.0",
- "presentation": {
- "echo": false,
- "reveal": "always",
- "focus": false,
- "panel": "dedicated",
- "showReuseMessage": true
- },
- "tasks": [
- {
- "type": "npm",
- "script": "test",
- "group": "test",
- "problemMatcher": []
- },
- {
- "type": "npm",
- "script": "watch",
- "group": "build",
- "isBackground": true,
- "problemMatcher": [],
- "presentation": {
- "group": "vscode"
- }
- },
- {
- "type": "npm",
- "script": "start",
- "group": "build",
- "isBackground": true,
- "problemMatcher": [],
- "presentation": {
- "group": "vscode"
- }
- },
- {
- "label": "Start demo",
- "dependsOn": ["npm: watch", "npm: start"],
- "group": {
- "kind": "build",
- "isDefault": true
- },
- "isBackground": true,
- "problemMatcher": [],
- "presentation": {
- "group": "vscode"
- }
- }
- ]
+ "version": "2.0.0",
+ "presentation": {
+ "echo": false,
+ "reveal": "always",
+ "focus": false,
+ "panel": "dedicated",
+ "showReuseMessage": true
+ },
+ "tasks": [
+ {
+ "type": "npm",
+ "script": "test",
+ "group": "test",
+ "problemMatcher": []
+ },
+ {
+ "type": "npm",
+ "script": "watch",
+ "group": "build",
+ "isBackground": true,
+ "problemMatcher": "$tsc-watch",
+ "presentation": {
+ "group": "vscode"
+ }
+ },
+ {
+ "type": "npm",
+ "script": "start",
+ "dependsOn": "npm: watch",
+ "group": "build",
+ "isBackground": true,
+ "problemMatcher": [],
+ "presentation": {
+ "group": "vscode"
+ }
+ },
+ {
+ "label": "Start demo",
+ "dependsOn": "npm: start",
+ "group": {
+ "kind": "build",
+ "isDefault": true
+ },
+ "isBackground": true,
+ "problemMatcher": {
+ "owner": "typescript",
+ "fileLocation": [
+ "relative",
+ "${workspaceFolder}"
+ ],
+ "pattern": [
+ {
+ "regexp": "^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$",
+ "file": 1,
+ "location": 2,
+ "message": 3
+ }
+ ],
+ "background": {
+ "beginsPattern": "assets by",
+ "endsPattern": "webpack \\d+\\.\\d+\\.\\d+ compiled successfully"
+ }
+ },
+ "presentation": {
+ "group": "vscode"
+ }
+ }
+ ]
}
diff --git a/README.md b/README.md
index ce687da9..6b713d45 100644
--- a/README.md
+++ b/README.md
@@ -6,11 +6,11 @@ Xterm.js is a front-end component written in TypeScript that lets applications b
## Features
-- **Terminal apps just work**: Xterm.js works with most terminal apps such as `bash`, `vim` and `tmux`, this includes support for curses-based apps and mouse event support.
+- **Terminal apps just work**: Xterm.js works with most terminal apps such as `bash`, `vim`, and `tmux`, including support for curses-based apps and mouse events.
- **Performant**: Xterm.js is *really* fast, it even includes a GPU-accelerated renderer.
-- **Rich unicode support**: Supports CJK, emojis and IMEs.
+- **Rich Unicode support**: Supports CJK, emojis, and IMEs.
- **Self-contained**: Requires zero dependencies to work.
-- **Accessible**: Screen reader and minimum contrast ratio support can be turned on
+- **Accessible**: Screen reader and minimum contrast ratio support can be turned on.
- **And much more**: Links, theming, addons, well documented API, etc.
## What xterm.js is not
@@ -20,13 +20,13 @@ Xterm.js is a front-end component written in TypeScript that lets applications b
## Getting Started
-First you need to install the module, we ship exclusively through [npm](https://www.npmjs.com/) so you need that installed and then add xterm.js as a dependency by running:
+First, you need to install the module, we ship exclusively through [npm](https://www.npmjs.com/), so you need that installed and then add xterm.js as a dependency by running:
-```
+```bash
npm install xterm
```
-To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your html page. Then create a `
` onto which xterm can attach itself. Finally instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
+To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your HTML page. Then create a `` onto which xterm can attach itself. Finally, instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
```html
@@ -58,7 +58,7 @@ import { Terminal } from 'xterm';
⚠️ *This section describes the new addon format introduced in v3.14.0, see [here](https://github.com/xtermjs/xterm.js/blob/3.14.2/README.md#addons) for the instructions on the old format*
-Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon you first need to install it in your project:
+Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon, you first need to install it in your project:
```bash
npm i -S xterm-addon-web-links
@@ -76,7 +76,7 @@ const terminal = new Terminal();
terminal.loadAddon(new WebLinksAddon());
```
-The xterm.js team maintains the following addons but they can be built by anyone:
+The xterm.js team maintains the following addons, but anyone can build them:
- [`xterm-addon-attach`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-attach): Attaches to a server running a process via a websocket
- [`xterm-addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-fit): Fits the terminal to the containing element
@@ -85,23 +85,27 @@ The xterm.js team maintains the following addons but they can be built by anyone
## Browser Support
-Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox* and *Safari*.
+Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox*, and *Safari*.
We also partially support *Internet Explorer 11*, meaning xterm.js should work for the most part, but we reserve the right to not provide workarounds specifically for it unless it's absolutely necessary to get the basic input/output flow working.
-Xterm.js works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers, these are the versions we strive to keep working.
+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.
-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.
+Note that some APIs are marked *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.
## Real-world uses
Xterm.js is used in several world-class applications to provide great terminal experiences.
- [**SourceLair**](https://www.sourcelair.com/): In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js.
-- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile and powerful open source code editor that provides an integrated terminal based on xterm.js.
+- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile, and powerful open source code editor that provides an integrated terminal based on xterm.js.
- [**ttyd**](https://github.com/tsl0922/ttyd): A command-line tool for sharing terminal over the web, with fully-featured terminal emulation based on xterm.js.
- [**Katacoda**](https://www.katacoda.com/): Katacoda is an Interactive Learning Platform for software developers, covering the latest Cloud Native technologies.
- [**Eclipse Che**](http://www.eclipse.org/che): Developer workspace server, cloud IDE, and Eclipse next-generation IDE.
@@ -113,10 +117,10 @@ Xterm.js is used in several world-class applications to provide great terminal e
- [**Next Tech**](https://next.tech "Next Tech"): Online platform for interactive coding and web development courses. Live container-backed terminal uses xterm.js.
- [**RStudio**](https://www.rstudio.com/products/RStudio "RStudio"): RStudio is an integrated development environment (IDE) for R.
- [**Terminal for Atom**](https://github.com/jsmecham/atom-terminal-tab): A simple terminal for the Atom text editor.
-- [**Eclipse Orion**](https://orionhub.org): A modern, open source software development environment that runs in the cloud. Code, deploy and run in the cloud.
+- [**Eclipse Orion**](https://orionhub.org): A modern, open source software development environment that runs in the cloud. Code, deploy, and run in the cloud.
- [**Gravitational Teleport**](https://github.com/gravitational/teleport): Gravitational Teleport is a modern SSH server for remotely accessing clusters of Linux servers via SSH or HTTPS.
- [**Hexlet**](https://en.hexlet.io): Practical programming courses (JavaScript, PHP, Unix, databases, functional programming). A steady path from the first line of code to the first job.
-- [**Selenoid UI**](https://github.com/aerokube/selenoid-ui): Simple UI for the scallable golang implementation of Selenium Hub named Selenoid. We use XTerm for streaming logs over websockets from docker containers.
+- [**Selenoid UI**](https://github.com/aerokube/selenoid-ui): Simple UI for the scalable golang implementation of Selenium Hub named Selenoid. We use XTerm for streaming logs over websockets from docker containers.
- [**Portainer**](https://portainer.io): Simple management UI for Docker.
- [**SSHy**](https://github.com/stuicey/SSHy): HTML5 Based SSHv2 Web Client with E2E encryption utilising xterm.js, SJCL & websockets.
- [**JupyterLab**](https://github.com/jupyterlab/jupyterlab): An extensible computational environment for Jupyter, supporting interactive data science and scientific computing across all programming languages.
@@ -143,7 +147,6 @@ Xterm.js is used in several world-class applications to provide great terminal e
- [**cPanel & WHM**](https://cpanel.com): The hosting platform of choice.
- [**Nutanix**](https://github.com/nutanix): Nutanix Enterprise Cloud uses xterm in the webssh functionality within Nutanix Calm, and is also looking to move our old noserial (termjs) functionality to xterm.js.
- [**SSH Web Client**](https://github.com/roke22/PHP-SSH2-Web-Client): SSH Web Client with PHP.
-- [**Shellvault**](https://www.shellvault.io): The cloud-based SSH terminal you can access from anywhere.
- [**Juno**](http://junolab.org/): A flexible Julia IDE, based on Atom.
- [**webssh**](https://github.com/huashengdun/webssh): Web based ssh client.
- [**info-beamer hosted**](https://info-beamer.com): Uses xterm.js to manage digital signage devices from the web dashboard.
@@ -163,16 +166,27 @@ 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 supported, with results displayed by xterm.js.
-- [**TRASA**](https://trasa.io): Zero trust access to Web, SSH, RDP and Database services.
+- [**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.
- [**FleetDeck**](https://fleetdeck.io): Remote desktop & virtual terminal
-[And much more...](https://github.com/xtermjs/xterm.js/network/dependents)
+- [**Commas**](https://github.com/CyanSalt/commas): Commas is a hackable terminal and command runner.
+- [**Devtron**](https://github.com/devtron-labs/devtron): Software Delivery Workflow For Kubernetes.
+- [**NxShell**](https://github.com/nxshell/nxshell): An easy to use new terminal for SSH.
+- [**gifcast**](https://dstein64.github.io/gifcast/): Converts an asciinema cast to an animated GIF.
+- [**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.
+- [**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 in our list. Note: Please add any new contributions to the end of the list only.
+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.
## Releases
@@ -182,21 +196,21 @@ All current and past releases are available on this repo's [Releases page](https
### Beta builds
-Our CI releases beta builds to npm for every change that goes into master, install the latest beta build with:
+Our CI releases beta builds to npm for every change that goes into master. Install the latest beta build with:
-```
+```bash
npm install -S xterm@beta
```
-These should generally be stable but some bugs may slip in, we recommend using the beta build primarily to test out new features and for verifying bug fixes.
+These should generally be stable, but some bugs may slip in. We recommend using the beta build primarily to test out new features and to verify bug fixes.
## Contributing
-You can read the [guide on the wiki](https://github.com/xtermjs/xterm.js/wiki/Contributing) to learn how to contribute and setup xterm.js for development.
+You can read the [guide on the wiki](https://github.com/xtermjs/xterm.js/wiki/Contributing) to learn how to contribute and set up xterm.js for development.
## License Agreement
-If you contribute code to this project, you are implicitly allowing your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work.
+If you contribute code to this project, you implicitly allow your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work.
Copyright (c) 2017-2019, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)
Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)
diff --git a/addons/xterm-addon-attach/src/AttachAddon.ts b/addons/xterm-addon-attach/src/AttachAddon.ts
index 279d1b2e..9fbd796b 100644
--- a/addons/xterm-addon-attach/src/AttachAddon.ts
+++ b/addons/xterm-addon-attach/src/AttachAddon.ts
@@ -20,7 +20,7 @@ export class AttachAddon implements ITerminalAddon {
this._socket = socket;
// always set binary type to arraybuffer, we do not handle blobs
this._socket.binaryType = 'arraybuffer';
- this._bidirectional = (options && options.bidirectional === false) ? false : true;
+ this._bidirectional = !(options && options.bidirectional === false);
}
public activate(terminal: Terminal): void {
@@ -41,7 +41,9 @@ export class AttachAddon implements ITerminalAddon {
}
public dispose(): void {
- this._disposables.forEach(d => d.dispose());
+ for (const d of this._disposables) {
+ d.dispose();
+ }
}
private _sendData(data: string): void {
diff --git a/addons/xterm-addon-attach/test/AttachAddon.api.ts b/addons/xterm-addon-attach/test/AttachAddon.api.ts
index 41e579f5..8335cf0f 100644
--- a/addons/xterm-addon-attach/test/AttachAddon.api.ts
+++ b/addons/xterm-addon-attach/test/AttachAddon.api.ts
@@ -4,10 +4,10 @@
*/
import WebSocket = require('ws');
-import { openTerminal, pollFor, getBrowserType } from '../../../out-test/api/TestUtils';
+import { openTerminal, pollFor, launchBrowser } from '../../../out-test/api/TestUtils';
import { Browser, Page } from 'playwright';
-const APP = 'http://127.0.0.1:3000/test';
+const APP = 'http://127.0.0.1:3001/test';
let browser: Browser;
let page: Page;
@@ -16,10 +16,7 @@ const height = 600;
describe('AttachAddon', () => {
before(async function(): Promise {
- const browserType = getBrowserType();
- browser = await browserType.launch({
- headless: process.argv.indexOf('--headless') !== -1
- });
+ browser = await launchBrowser();
page = await (await browser.newContext()).newPage();
await page.setViewportSize({ width, height });
});
diff --git a/addons/xterm-addon-fit/package.json b/addons/xterm-addon-fit/package.json
index 859d6ebf..f9d96c4a 100644
--- a/addons/xterm-addon-fit/package.json
+++ b/addons/xterm-addon-fit/package.json
@@ -1,6 +1,6 @@
{
"name": "xterm-addon-fit",
- "version": "0.4.0",
+ "version": "0.5.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
diff --git a/addons/xterm-addon-fit/test/FitAddon.api.ts b/addons/xterm-addon-fit/test/FitAddon.api.ts
index 1111dff0..987092ad 100644
--- a/addons/xterm-addon-fit/test/FitAddon.api.ts
+++ b/addons/xterm-addon-fit/test/FitAddon.api.ts
@@ -4,10 +4,10 @@
*/
import { assert } from 'chai';
-import { openTerminal, getBrowserType } from '../../../out-test/api/TestUtils';
+import { openTerminal, launchBrowser } from '../../../out-test/api/TestUtils';
import { Browser, Page } from 'playwright';
-const APP = 'http://127.0.0.1:3000/test';
+const APP = 'http://127.0.0.1:3001/test';
let browser: Browser;
let page: Page;
@@ -16,10 +16,7 @@ const height = 768;
describe('FitAddon', () => {
before(async function(): Promise {
- const browserType = getBrowserType();
- browser = await browserType.launch({
- headless: process.argv.indexOf('--headless') !== -1
- });
+ browser = await launchBrowser();
page = await (await browser.newContext()).newPage();
await page.setViewportSize({ width, height });
await page.goto(APP);
@@ -45,7 +42,7 @@ describe('FitAddon', () => {
describe('proposeDimensions', () => {
afterEach(async () => {
- return unloadFit();
+ return await unloadFit();
});
it('default', async function(): Promise {
@@ -84,7 +81,7 @@ describe('FitAddon', () => {
describe('fit', () => {
afterEach(async () => {
- return unloadFit();
+ return await unloadFit();
});
it('default', async function(): Promise {
diff --git a/addons/xterm-addon-ligatures/README.md b/addons/xterm-addon-ligatures/README.md
index 6336bf83..8f869d73 100644
--- a/addons/xterm-addon-ligatures/README.md
+++ b/addons/xterm-addon-ligatures/README.md
@@ -51,3 +51,4 @@ This package makes use of the following fonts for testing:
[Fira Code License]: https://github.com/tonsky/FiraCode/blob/master/LICENSE
[Iosevka]: https://github.com/be5invis/Iosevka
[Iosevka License]: https://github.com/be5invis/Iosevka/blob/master/LICENSE.md
+
diff --git a/addons/xterm-addon-ligatures/package.json b/addons/xterm-addon-ligatures/package.json
index df85c020..b1688772 100644
--- a/addons/xterm-addon-ligatures/package.json
+++ b/addons/xterm-addon-ligatures/package.json
@@ -1,6 +1,6 @@
{
"name": "xterm-addon-ligatures",
- "version": "0.3.0",
+ "version": "0.5.1",
"description": "Add support for programming ligatures to xterm.js",
"author": {
"name": "The xterm.js authors",
@@ -31,12 +31,12 @@
],
"license": "MIT",
"dependencies": {
- "font-finder": "^1.0.4",
- "font-ligatures": "^1.3.3"
+ "font-finder": "^1.1.0",
+ "font-ligatures": "^1.4.0"
},
"devDependencies": {
"@types/sinon": "^5.0.1",
- "axios": "^0.18.0",
+ "axios": "^0.21.2",
"mkdirp": "0.5.5",
"sinon": "6.3.5",
"yauzl": "^2.10.0"
diff --git a/addons/xterm-addon-ligatures/src/font.ts b/addons/xterm-addon-ligatures/src/font.ts
index 825fc797..abdbbc04 100644
--- a/addons/xterm-addon-ligatures/src/font.ts
+++ b/addons/xterm-addon-ligatures/src/font.ts
@@ -3,12 +3,28 @@
* @license MIT
*/
-import * as fontFinder from 'font-finder';
-import * as fontLigatures from 'font-ligatures';
+import { FontList } from 'font-finder';
+import { Font, loadBuffer, loadFile } from 'font-ligatures';
import parse from './parse';
-let fontsPromise: Promise | undefined = undefined;
+interface IFontMetadata {
+ family: string;
+ fullName: string;
+ postscriptName: string;
+ blob: () => Promise;
+}
+
+interface IFontAccessNavigator {
+ fonts: {
+ query: () => Promise;
+ };
+ permissions: {
+ request?: (permission: { name: string }) => Promise<{state: string}>;
+ };
+}
+
+let fontsPromise: Promise> | undefined = undefined;
/**
* Loads the font ligature wrapper for the specified font family if it could be
@@ -16,9 +32,50 @@ let fontsPromise: Promise | undefined = undefined;
* @param fontFamily The CSS font family definition to resolve
* @param cacheSize The size of the ligature cache to maintain if the font is resolved
*/
-export default async function load(fontFamily: string, cacheSize: number): Promise {
+export default async function load(fontFamily: string, cacheSize: number): Promise {
if (!fontsPromise) {
- fontsPromise = fontFinder.list();
+ // Web environment that supports font access API
+ if (typeof navigator !== 'undefined' && 'fonts' in navigator) {
+ try {
+ const status = await (navigator as unknown as IFontAccessNavigator).permissions.request?.({
+ name: 'local-fonts'
+ });
+ if (status && status.state !== 'granted') {
+ throw new Error('Permission to access local fonts not granted.');
+ }
+ } catch (err) {
+ // A `TypeError` indicates the 'local-fonts'
+ // permission is not yet implemented, so
+ // only `throw` if this is _not_ the problem.
+ if (err.name !== 'TypeError') {
+ throw err;
+ }
+ }
+ const fonts: Record = {};
+ try {
+ const fontsIterator = await (navigator as unknown as IFontAccessNavigator).fonts.query();
+ for (const metadata of fontsIterator) {
+ if (!fonts.hasOwnProperty(metadata.family)) {
+ fonts[metadata.family] = [];
+ }
+ fonts[metadata.family].push(metadata);
+ }
+ fontsPromise = Promise.resolve(fonts);
+ } catch (err) {
+ console.error(err.name, err.message);
+ }
+ }
+ // Node environment or no font access API
+ else {
+ try {
+ fontsPromise = (await import('font-finder')).list();
+ } catch (err) {
+ // No-op
+ }
+ }
+ if (!fontsPromise) {
+ fontsPromise = Promise.resolve({});
+ }
}
const fonts = await fontsPromise;
@@ -31,7 +88,11 @@ export default async function load(fontFamily: string, cacheSize: number): Promi
}
if (fonts.hasOwnProperty(family) && fonts[family].length > 0) {
- return await fontLigatures.loadFile(fonts[family][0].path, { cacheSize });
+ const font = fonts[family][0];
+ if ('blob' in font) {
+ return loadBuffer(await (await font.blob()).arrayBuffer(), { cacheSize });
+ }
+ return await loadFile(font.path, { cacheSize });
}
}
diff --git a/addons/xterm-addon-ligatures/src/parse.ts b/addons/xterm-addon-ligatures/src/parse.ts
index 5ad7747f..6289e468 100644
--- a/addons/xterm-addon-ligatures/src/parse.ts
+++ b/addons/xterm-addon-ligatures/src/parse.ts
@@ -68,7 +68,7 @@ function parseString(context: IParseContext, quoteChar: '\'' | '"'): string {
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (escaped) {
- if (/[0-9a-fA-F]/.test(char)) {
+ if (/[\dA-Fa-f]/.test(char)) {
// Unicode escape
context.offset--;
str += parseUnicode(context);
@@ -107,7 +107,7 @@ function parseIdentifier(context: IParseContext): string {
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (escaped) {
- if (/[0-9a-fA-F]/.test(char)) {
+ if (/[\dA-Fa-f]/.test(char)) {
// Unicode escape
context.offset--;
str += parseUnicode(context);
@@ -156,7 +156,7 @@ function parseUnicode(context: IParseContext): string {
// of the escape and is swallowed.
return unicodeToString(str);
}
- if (str.length >= 6 || !/[0-9a-fA-F]/.test(char)) {
+ if (str.length >= 6 || !/[\dA-Fa-f]/.test(char)) {
// If the next character is not a valid hex digit or we have reached the
// maximum of 6 digits in the escape, terminate the escape.
context.offset--;
diff --git a/addons/xterm-addon-ligatures/webpack.config.js b/addons/xterm-addon-ligatures/webpack.config.js
index 253e1207..ea69841e 100644
--- a/addons/xterm-addon-ligatures/webpack.config.js
+++ b/addons/xterm-addon-ligatures/webpack.config.js
@@ -30,7 +30,18 @@ module.exports = {
},
mode: 'production',
externals: {
- 'font-finder':'font-finder',
- 'font-ligatures':'font-ligatures'
+ 'font-finder': 'font-finder',
+ 'stream': 'stream',
+ 'os': 'os',
+ 'util': 'util'
+ },
+ resolve: {
+ // The ligature modules contains fallbacks for node environments, we never want to browserify them
+ fallback: {
+ stream: false,
+ util: false,
+ os: false,
+ path: false
+ }
}
};
diff --git a/addons/xterm-addon-ligatures/yarn.lock b/addons/xterm-addon-ligatures/yarn.lock
index d8e64e49..f6ce913b 100644
--- a/addons/xterm-addon-ligatures/yarn.lock
+++ b/addons/xterm-addon-ligatures/yarn.lock
@@ -45,23 +45,17 @@ array-from@^2.1.1:
resolved "https://registry.yarnpkg.com/array-from/-/array-from-2.1.1.tgz#cfe9d8c26628b9dc5aecc62a9f5d8f1f352c1195"
integrity sha1-z+nYwmYoudxa7MYqn12PHzUsEZU=
-axios@^0.18.0:
- version "0.18.1"
- resolved "https://registry.yarnpkg.com/axios/-/axios-0.18.1.tgz#ff3f0de2e7b5d180e757ad98000f1081b87bcea3"
+axios@^0.21.2:
+ version "0.21.2"
+ resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.2.tgz#21297d5084b2aeeb422f5d38e7be4fbb82239017"
+ integrity sha512-87otirqUw3e8CzHTMO+/9kh/FSgXt/eVDvipijwDtEuwbkySWZ9SBm6VEubmJ/kLKEoLQV/POhxXFb66bfekfg==
dependencies:
- follow-redirects "1.5.10"
- is-buffer "^2.0.2"
+ follow-redirects "^1.14.0"
buffer-crc32@~0.2.3:
version "0.2.13"
resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242"
-debug@=3.1.0:
- version "3.1.0"
- resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261"
- dependencies:
- ms "2.0.0"
-
diff@^3.5.0:
version "3.5.0"
resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12"
@@ -72,26 +66,33 @@ fd-slicer@~1.1.0:
dependencies:
pend "~1.2.0"
-follow-redirects@1.5.10:
- version "1.5.10"
- resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.5.10.tgz#7b7a9f9aea2fdff36786a94ff643ed07f4ff5e2a"
- dependencies:
- debug "=3.1.0"
+follow-redirects@^1.14.0:
+ version "1.14.3"
+ resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.3.tgz#6ada78118d8d24caee595595accdc0ac6abd022e"
+ integrity sha512-3MkHxknWMUtb23apkgz/83fDoe+y+qr0TdgacGIA7bew+QLBo3vdgEN2xEsuXNivpFy4CyDhBBZnNZOtalmenw==
-font-finder@^1.0.3, font-finder@^1.0.4:
+font-finder@^1.0.3:
version "1.0.4"
resolved "https://registry.yarnpkg.com/font-finder/-/font-finder-1.0.4.tgz#2ca944954dd8d0e1b5bdc4c596cc08607761d89b"
dependencies:
get-system-fonts "^2.0.0"
promise-stream-reader "^1.0.1"
-font-ligatures@^1.3.3:
- version "1.3.3"
- resolved "https://registry.yarnpkg.com/font-ligatures/-/font-ligatures-1.3.3.tgz#63fff18dc8adb3a11fe5eec1f4e8d7edfa8075b9"
- integrity sha512-NSGpHgVNX81M7AWS1XylK1UZbN3QllfUIDAAuPv6TUcl5O2b781JcKS5L2RopAU0AqlTyX3ZuX/04eaMpbVrHA==
+font-finder@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.npmjs.org/font-finder/-/font-finder-1.1.0.tgz#2bff2b2762acba720239c8bec898a96daae90858"
+ integrity sha512-wpCL2uIbi6GurJbU7ZlQ3nGd61Ho+dSU6U83/xJT5UPFfN35EeCW/rOtS+5k+IuEZu2SYmHzDIPL9eA5tSYRAw==
+ dependencies:
+ get-system-fonts "^2.0.0"
+ promise-stream-reader "^1.0.1"
+
+font-ligatures@^1.4.0:
+ version "1.4.0"
+ resolved "https://registry.npmjs.org/font-ligatures/-/font-ligatures-1.4.0.tgz#6a7b370d96be1358dddfad67830e82fbfd59e6dc"
+ integrity sha512-n7DFnnEpJ0NrVoLqZIL4tMGVs+CnFwQc92m80LWyrbgAFO4x234+t2/H9o4eOYA1eh6ta9dZAEEsJAwsBdNezA==
dependencies:
font-finder "^1.0.3"
- lru-cache "^4.1.3"
+ lru-cache "^6.0.0"
opentype.js "^0.8.0"
get-system-fonts@^2.0.0:
@@ -102,10 +103,6 @@ has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
-is-buffer@^2.0.2:
- version "2.0.3"
- resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.3.tgz#4ecf3fcf749cbd1e472689e109ac66261a25e725"
-
isarray@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf"
@@ -120,9 +117,9 @@ lodash.get@^4.4.2:
resolved "https://registry.yarnpkg.com/lodash.get/-/lodash.get-4.4.2.tgz#2d177f652fa31e939b4438d5341499dfa3825e99"
lodash@^4.17.15:
- version "4.17.19"
- resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b"
- integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==
+ version "4.17.21"
+ resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
+ integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
lolex@^2.7.5:
version "2.7.5"
@@ -136,12 +133,12 @@ lolex@^5.0.1:
dependencies:
"@sinonjs/commons" "^1.7.0"
-lru-cache@^4.1.3:
- version "4.1.3"
- resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.3.tgz#a1175cf3496dfc8436c156c334b4955992bce69c"
+lru-cache@^6.0.0:
+ version "6.0.0"
+ resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94"
+ integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==
dependencies:
- pseudomap "^1.0.2"
- yallist "^2.1.2"
+ yallist "^4.0.0"
minimist@^1.2.5:
version "1.2.5"
@@ -155,10 +152,6 @@ mkdirp@0.5.5:
dependencies:
minimist "^1.2.5"
-ms@2.0.0:
- version "2.0.0"
- resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
-
nise@^1.4.5:
version "1.5.3"
resolved "https://registry.yarnpkg.com/nise/-/nise-1.5.3.tgz#9d2cfe37d44f57317766c6e9408a359c5d3ac1f7"
@@ -190,10 +183,6 @@ promise-stream-reader@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/promise-stream-reader/-/promise-stream-reader-1.0.1.tgz#4e793a79c9d49a73ccd947c6da9c127f12923649"
-pseudomap@^1.0.2:
- version "1.0.2"
- resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3"
-
sinon@6.3.5:
version "6.3.5"
resolved "https://registry.yarnpkg.com/sinon/-/sinon-6.3.5.tgz#0f6d6a5b4ebaad1f6e8e019395542d1d02c144a0"
@@ -224,9 +213,10 @@ type-detect@4.0.8, type-detect@^4.0.8:
version "4.0.8"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
-yallist@^2.1.2:
- version "2.1.2"
- resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52"
+yallist@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
+ integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
yauzl@^2.10.0:
version "2.10.0"
diff --git a/addons/xterm-addon-search/package.json b/addons/xterm-addon-search/package.json
index 711335cb..08fe195f 100644
--- a/addons/xterm-addon-search/package.json
+++ b/addons/xterm-addon-search/package.json
@@ -1,6 +1,6 @@
{
"name": "xterm-addon-search",
- "version": "0.7.0",
+ "version": "0.8.1",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
diff --git a/addons/xterm-addon-search/src/SearchAddon.ts b/addons/xterm-addon-search/src/SearchAddon.ts
index f5505689..1409328d 100644
--- a/addons/xterm-addon-search/src/SearchAddon.ts
+++ b/addons/xterm-addon-search/src/SearchAddon.ts
@@ -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 {
@@ -158,8 +158,15 @@ export class SearchAddon implements ITerminalAddon {
};
if (incremental) {
+ // Try to expand selection to right first.
result = this._findInLine(term, searchPosition, searchOptions, false);
- if (!(result && result.row === startRow && result.col === startCol)) {
+ const isOldResultHighlighted = result && result.row === startRow && result.col === startCol;
+ if (!isOldResultHighlighted) {
+ // If selection was not able to be expanded to the right, then try reverse search
+ if (currentSelection) {
+ searchPosition.startRow = currentSelection.endRow;
+ searchPosition.startCol = currentSelection.endColumn;
+ }
result = this._findInLine(term, searchPosition, searchOptions, true);
}
} else {
@@ -233,8 +240,8 @@ export class SearchAddon implements ITerminalAddon {
* @param term the substring that starts at searchIndex
*/
private _isWholeWord(searchIndex: number, line: string, term: string): boolean {
- return (((searchIndex === 0) || (NON_WORD_CHARACTERS.indexOf(line[searchIndex - 1]) !== -1)) &&
- (((searchIndex + term.length) === line.length) || (NON_WORD_CHARACTERS.indexOf(line[searchIndex + term.length]) !== -1)));
+ return ((searchIndex === 0) || (NON_WORD_CHARACTERS.includes(line[searchIndex - 1]))) &&
+ (((searchIndex + term.length) === line.length) || (NON_WORD_CHARACTERS.includes(line[searchIndex + term.length])));
}
/**
@@ -245,6 +252,7 @@ export class SearchAddon implements ITerminalAddon {
* @param term The search term.
* @param position The position to start the search.
* @param searchOptions Search options.
+ * @param isReverseSearch Whether the search should start from the right side of the terminal and search to the left.
* @return The search result if it was found.
*/
protected _findInLine(term: string, searchPosition: ISearchPosition, searchOptions: ISearchOptions = {}, isReverseSearch: boolean = false): ISearchResult | undefined {
@@ -254,7 +262,7 @@ export class SearchAddon implements ITerminalAddon {
// Ignore wrapped lines, only consider on unwrapped line (first row of command string).
const firstLine = terminal.buffer.active.getLine(row);
- if (firstLine && firstLine.isWrapped) {
+ if (firstLine?.isWrapped) {
if (isReverseSearch) {
searchPosition.startCol += terminal.cols;
return;
@@ -386,7 +394,7 @@ export class SearchAddon implements ITerminalAddon {
// If it is not in the viewport then we scroll else it just gets selected
if (result.row >= (terminal.buffer.active.viewportY + terminal.rows) || result.row < terminal.buffer.active.viewportY) {
let scroll = result.row - terminal.buffer.active.viewportY;
- scroll = scroll - Math.floor(terminal.rows / 2);
+ scroll -= Math.floor(terminal.rows / 2);
terminal.scrollLines(scroll);
}
return true;
diff --git a/addons/xterm-addon-search/test/SearchAddon.api.ts b/addons/xterm-addon-search/test/SearchAddon.api.ts
index 3707aecd..8bdf61cf 100644
--- a/addons/xterm-addon-search/test/SearchAddon.api.ts
+++ b/addons/xterm-addon-search/test/SearchAddon.api.ts
@@ -6,10 +6,10 @@
import { assert } from 'chai';
import { readFile } from 'fs';
import { resolve } from 'path';
-import { openTerminal, writeSync, getBrowserType } from '../../../out-test/api/TestUtils';
+import { openTerminal, writeSync, launchBrowser } from '../../../out-test/api/TestUtils';
import { Browser, Page } from 'playwright';
-const APP = 'http://127.0.0.1:3000/test';
+const APP = 'http://127.0.0.1:3001/test';
let browser: Browser;
let page: Page;
@@ -18,10 +18,7 @@ const height = 600;
describe('Search Tests', function(): void {
before(async function(): Promise {
- const browserType = getBrowserType();
- browser = await browserType.launch({
- headless: process.argv.indexOf('--headless') !== -1
- });
+ browser = await launchBrowser();
page = await (await browser.newContext()).newPage();
await page.setViewportSize({ width, height });
await page.goto(APP);
diff --git a/addons/xterm-addon-serialize/benchmark/SerializeAddon.benchmark.ts b/addons/xterm-addon-serialize/benchmark/SerializeAddon.benchmark.ts
index 0147631d..87741b63 100644
--- a/addons/xterm-addon-serialize/benchmark/SerializeAddon.benchmark.ts
+++ b/addons/xterm-addon-serialize/benchmark/SerializeAddon.benchmark.ts
@@ -35,7 +35,7 @@ perfContext('Terminal: sh -c "dd if=/dev/urandom count=40 bs=1k | hexdump | lolc
chunks.push(data as unknown as Buffer);
length += data.length;
});
- await new Promise(resolve => p.on('exit', () => resolve()));
+ await new Promise(resolve => p.on('exit', () => resolve()));
contentUtf8 = Buffer.concat(chunks, length);
// translate to content string
const buffer = new Uint32Array(contentUtf8.length);
diff --git a/addons/xterm-addon-serialize/package.json b/addons/xterm-addon-serialize/package.json
index bb799aec..77a54dbf 100644
--- a/addons/xterm-addon-serialize/package.json
+++ b/addons/xterm-addon-serialize/package.json
@@ -1,12 +1,13 @@
{
"name": "xterm-addon-serialize",
- "version": "0.4.0",
+ "version": "0.6.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
},
"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 .",
diff --git a/addons/xterm-addon-serialize/src/SerializeAddon.ts b/addons/xterm-addon-serialize/src/SerializeAddon.ts
index dad6aa4f..24020b74 100644
--- a/addons/xterm-addon-serialize/src/SerializeAddon.ts
+++ b/addons/xterm-addon-serialize/src/SerializeAddon.ts
@@ -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
@@ -21,7 +25,7 @@ abstract class BaseSerializeHandler {
const cell2 = this._buffer.getNullCell();
let oldCell = cell1;
- this._beforeSerialize(endRow - startRow);
+ this._beforeSerialize(endRow - startRow, startRow, endRow);
for (let row = startRow; row < endRow; row++) {
const line = this._buffer.getLine(row);
@@ -36,7 +40,7 @@ abstract class BaseSerializeHandler {
oldCell = c;
}
}
- this._rowEnd(row);
+ this._rowEnd(row, row === endRow - 1);
}
this._afterSerialize();
@@ -45,8 +49,8 @@ abstract class BaseSerializeHandler {
}
protected _nextCell(cell: IBufferCell, oldCell: IBufferCell, row: number, col: number): void { }
- protected _rowEnd(row: number): void { }
- protected _beforeSerialize(rows: number): void { }
+ protected _rowEnd(row: number, isLastRow: boolean): void { }
+ protected _beforeSerialize(rows: number, startRow: number, endRow: number): void { }
protected _afterSerialize(): void { }
protected _serializeString(): string { return ''; }
}
@@ -68,30 +72,157 @@ function equalFlags(cell1: IBufferCell, cell2: IBufferCell): boolean {
&& cell1.isBlink() === cell2.isBlink()
&& cell1.isInvisible() === cell2.isInvisible()
&& cell1.isItalic() === cell2.isItalic()
- && cell1.isDim() === cell2.isDim();
+ && cell1.isDim() === cell2.isDim()
+ && cell1.isStrikethrough() === cell2.isStrikethrough();
}
class StringSerializeHandler extends BaseSerializeHandler {
private _rowIndex: number = 0;
private _allRows: string[] = new Array();
+ private _allRowSeparators: string[] = new Array();
private _currentRow: string = '';
private _nullCellCount: number = 0;
- constructor(buffer: IBuffer) {
+ // 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._buffer.getNullCell();
+
+ // where exact the cursor styles comes from
+ // because we can't copy the cell directly
+ // so we remember where the content comes from instead
+ private _cursorStyleRow: number = 0;
+ private _cursorStyleCol: number = 0;
+
+ // this is a null cell for reference for checking whether background is empty or not
+ private _backgroundCell: IBufferCell = this._buffer.getNullCell();
+
+ private _firstRow: number = 0;
+ private _lastCursorRow: number = 0;
+ private _lastCursorCol: number = 0;
+ private _lastContentCursorRow: number = 0;
+ private _lastContentCursorCol: number = 0;
+
+ constructor(
+ buffer: IBuffer,
+ private readonly _terminal: Terminal
+ ) {
super(buffer);
}
- protected _beforeSerialize(rows: number): void {
+ protected _beforeSerialize(rows: number, start: number, end: number): void {
this._allRows = new Array(rows);
+ this._lastContentCursorRow = start;
+ this._lastCursorRow = start;
+ this._firstRow = start;
}
- protected _rowEnd(row: number): void {
- this._allRows[this._rowIndex++] = this._currentRow;
+ private _thisRowLastChar: IBufferCell = this._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 += `\u001b[${this._nullCellCount}X`;
+ }
+
+ let rowSeparator = '';
+
+ // handle row separator
+ if (!isLastRow) {
+ // Enable BCE
+ if (row - this._firstRow >= this._terminal.rows) {
+ this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol, this._backgroundCell);
+ }
+
+ // Fetch current line
+ const currentLine = this._buffer.getLine(row)!;
+ // Fetch next line
+ const nextLine = this._buffer.getLine(row + 1)!;
+
+ if (!nextLine.isWrapped) {
+ // just insert the line break
+ rowSeparator = '\r\n';
+ // we sended the enter
+ this._lastCursorRow = row + 1;
+ this._lastCursorCol = 0;
+ } else {
+ rowSeparator = '';
+ const thisRowLastChar = currentLine.getCell(currentLine.length - 1, this._thisRowLastChar)!;
+ const thisRowLastSecondChar = currentLine.getCell(currentLine.length - 2, this._thisRowLastSecondChar)!;
+ const nextRowFirstChar = nextLine.getCell(0, this._nextRowFirstChar)!;
+ const isNextRowFirstCharDoubleWidth = nextRowFirstChar.getWidth() > 1;
+
+ // validate whether this line wrap is ever possible
+ // which mean whether cursor can placed at a overflow position (x === row) naturally
+ let isValid = false;
+
+ if (
+ // you must output character to cause overflow, control sequence can't do this
+ nextRowFirstChar.getChars() &&
+ isNextRowFirstCharDoubleWidth ? this._nullCellCount <= 1 : this._nullCellCount <= 0
+ ) {
+ if (
+ // the last character can't be null,
+ // you can't use control sequence to move cursor to (x === row)
+ (thisRowLastChar.getChars() || thisRowLastChar.getWidth() === 0) &&
+ // change background of the first wrapped cell also affects BCE
+ // so we mark it as invalid to simply the process to determine line separator
+ equalBg(thisRowLastChar, nextRowFirstChar)
+ ) {
+ isValid = true;
+ }
+
+ if (
+ // the second to last character can't be null if the next line starts with CJK,
+ // you can't use control sequence to move cursor to (x === row)
+ isNextRowFirstCharDoubleWidth &&
+ (thisRowLastSecondChar.getChars() || thisRowLastSecondChar.getWidth() === 0) &&
+ // change background of the first wrapped cell also affects BCE
+ // so we mark it as invalid to simply the process to determine line separator
+ equalBg(thisRowLastChar, nextRowFirstChar) &&
+ equalBg(thisRowLastSecondChar, nextRowFirstChar)
+ ) {
+ isValid = true;
+ }
+ }
+
+ if (!isValid) {
+ // force the wrap with magic
+ // insert enough character to force the wrap
+ rowSeparator = '-'.repeat(this._nullCellCount + 1);
+ // move back and erase next line head
+ rowSeparator += '\u001b[1D\u001b[1X';
+
+ if (this._nullCellCount > 0) {
+ // do these because we filled the last several null slot, which we shouldn't
+ 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.
+ // without this, wrap will be missing from outputs.
+ this._lastContentCursorRow = row + 1;
+ this._lastContentCursorCol = 0;
+
+ // force commit the cursor position
+ this._lastCursorRow = row + 1;
+ this._lastCursorCol = 0;
+ }
+ }
+ }
+
+ this._allRows[this._rowIndex] = this._currentRow;
+ this._allRowSeparators[this._rowIndex++] = rowSeparator;
this._currentRow = '';
this._nullCellCount = 0;
}
- protected _nextCell(cell: IBufferCell, oldCell: IBufferCell, row: number, col: number): void {
+ private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): number[] {
const sgrSeq: number[] = [];
const fgChanged = !equalFg(cell, oldCell);
const bgChanged = !equalBg(cell, oldCell);
@@ -99,7 +230,9 @@ class StringSerializeHandler extends BaseSerializeHandler {
if (fgChanged || bgChanged || flagsChanged) {
if (cell.isAttributeDefault()) {
- this._currentRow += '\x1b[0m';
+ if (!oldCell.isAttributeDefault()) {
+ sgrSeq.push(0);
+ }
} else {
if (fgChanged) {
const color = cell.getFgColor();
@@ -127,34 +260,133 @@ class StringSerializeHandler extends BaseSerializeHandler {
if (cell.isInvisible() !== oldCell.isInvisible()) { sgrSeq.push(cell.isInvisible() ? 8 : 28); }
if (cell.isItalic() !== oldCell.isItalic()) { sgrSeq.push(cell.isItalic() ? 3 : 23); }
if (cell.isDim() !== oldCell.isDim()) { sgrSeq.push(cell.isDim() ? 2 : 22); }
+ if (cell.isStrikethrough() !== oldCell.isStrikethrough()) { sgrSeq.push(cell.isStrikethrough() ? 9 : 29); }
}
}
}
- if (sgrSeq.length) {
- this._currentRow += `\x1b[${sgrSeq.join(';')}m`;
+ return sgrSeq;
+ }
+
+ protected _nextCell(cell: IBufferCell, oldCell: IBufferCell, row: number, col: number): void {
+ // a width 0 cell don't need to be count because it is just a placeholder after a CJK character;
+ const isPlaceHolderCell = cell.getWidth() === 0;
+
+ if (isPlaceHolderCell) {
+ return;
}
- // Count number of null cells encountered after the last non-null cell and move the cursor
- // if a non-null cell is found (eg. \t or cursor move)
- if (cell.getChars() === '') {
+ // this cell don't have content
+ const isEmptyCell = cell.getChars() === '';
+
+ const sgrSeq = this._diffStyle(cell, this._cursorStyle);
+
+ // the empty cell style is only assumed to be changed when background changed, because foreground is always 0.
+ const styleChanged = isEmptyCell ? !equalBg(this._cursorStyle, cell) : sgrSeq.length > 0;
+
+ /**
+ * handles style change
+ */
+ if (styleChanged) {
+ // before update the style, we need to fill empty cell back
+ if (this._nullCellCount > 0) {
+ // use clear right to set background.
+ if (!equalBg(this._cursorStyle, this._backgroundCell)) {
+ this._currentRow += `\u001b[${this._nullCellCount}X`;
+ }
+ // use move right to move cursor.
+ this._currentRow += `\u001b[${this._nullCellCount}C`;
+ this._nullCellCount = 0;
+ }
+
+ this._lastContentCursorRow = this._lastCursorRow = row;
+ this._lastContentCursorCol = this._lastCursorCol = col;
+
+ this._currentRow += `\u001b[${sgrSeq.join(';')}m`;
+
+ // update the last cursor style
+ const line = this._buffer.getLine(row);
+ if (line !== undefined) {
+ line.getCell(col, this._cursorStyle);
+ this._cursorStyleRow = row;
+ this._cursorStyleCol = col;
+ }
+ }
+
+ /**
+ * handles actual content
+ */
+ if (isEmptyCell) {
this._nullCellCount += cell.getWidth();
- } else if (this._nullCellCount > 0) {
- this._currentRow += `\x1b[${this._nullCellCount}C`;
- this._nullCellCount = 0;
- }
+ } else {
+ if (this._nullCellCount > 0) {
+ // we can just assume we have same style with previous one here
+ // because style change is handled by previous stage
+ // use move right when background is empty, use clear right when there is background.
+ if (equalBg(this._cursorStyle, this._backgroundCell)) {
+ this._currentRow += `\u001b[${this._nullCellCount}C`;
+ } else {
+ this._currentRow += `\u001b[${this._nullCellCount}X`;
+ this._currentRow += `\u001b[${this._nullCellCount}C`;
+ }
+ this._nullCellCount = 0;
+ }
- this._currentRow += cell.getChars();
+ this._currentRow += cell.getChars();
+
+ // update cursor
+ this._lastContentCursorRow = this._lastCursorRow = row;
+ this._lastContentCursorCol = this._lastCursorCol = col + cell.getWidth();
+ }
}
protected _serializeString(): string {
let rowEnd = this._allRows.length;
- for (; rowEnd > 0; rowEnd--) {
- if (this._allRows[rowEnd - 1]) {
- break;
+
+ // the fixup is only required for data without scrollback
+ // because it will always be placed at last line otherwise
+ if (this._buffer.length - this._firstRow <= this._terminal.rows) {
+ rowEnd = this._lastContentCursorRow + 1 - this._firstRow;
+ this._lastCursorCol = this._lastContentCursorCol;
+ this._lastCursorRow = this._lastContentCursorRow;
+ }
+
+ let content = '';
+
+ for (let i = 0; i < rowEnd; i++) {
+ content += this._allRows[i];
+ if (i + 1 < rowEnd) {
+ content += this._allRowSeparators[i];
}
}
- return this._allRows.slice(0, rowEnd).join('\r\n');
+
+ // restore the cursor
+ const realCursorRow = this._buffer.baseY + this._buffer.cursorY;
+ const realCursorCol = this._buffer.cursorX;
+
+ const cursorMoved = (realCursorRow !== this._lastCursorRow || realCursorCol !== this._lastCursorCol);
+
+ const moveRight = (offset: number): void => {
+ if (offset > 0) {
+ content += `\u001b[${offset}C`;
+ } else if (offset < 0) {
+ content += `\u001b[${-offset}D`;
+ }
+ };
+ const moveDown = (offset: number): void => {
+ if (offset > 0) {
+ content += `\u001b[${offset}B`;
+ } else if (offset < 0) {
+ content += `\u001b[${-offset}A`;
+ }
+ };
+
+ if (cursorMoved) {
+ moveDown(realCursorRow - this._lastCursorRow);
+ moveRight(realCursorCol - this._lastCursorCol);
+ }
+
+ return content;
}
}
@@ -167,21 +399,73 @@ export class SerializeAddon implements ITerminalAddon {
this._terminal = terminal;
}
- public serialize(rows?: number): string {
- // TODO: Add re-position cursor support
- // TODO: Add word wrap mode support
+ private _serializeBuffer(terminal: Terminal, buffer: IBuffer, scrollback?: number): string {
+ const maxRows = buffer.length;
+ const handler = new StringSerializeHandler(buffer, terminal);
+ const correctRows = (scrollback === undefined) ? maxRows : constrain(scrollback + terminal.rows, 0, maxRows);
+ return handler.serialize(maxRows - correctRows, maxRows);
+ }
+
+ private _serializeModes(terminal: Terminal): string {
+ let content = '';
+ const modes = terminal.modes;
+
+ // 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(options?: ISerializeOptions): string {
// TODO: Add combinedData support
if (!this._terminal) {
throw new Error('Cannot use addon until it has been loaded');
}
- const maxRows = this._terminal.buffer.active.length;
- const handler = new StringSerializeHandler(this._terminal.buffer.active);
+ // Normal buffer
+ let content = this._serializeBuffer(this._terminal, this._terminal.buffer.normal, options?.scrollback);
- rows = (rows === undefined) ? maxRows : constrain(rows, 0, maxRows);
+ // Alternate buffer
+ if (!options?.excludeAltBuffer) {
+ if (this._terminal.buffer.active.type === 'alternate') {
+ const alternativeScreenContent = this._serializeBuffer(this._terminal, this._terminal.buffer.alternate, undefined);
+ content += `\u001b[?1049h\u001b[H${alternativeScreenContent}`;
+ }
+ }
- return handler.serialize(maxRows - rows, maxRows);
+ // Modes
+ if (!options?.excludeModes) {
+ content += this._serializeModes(this._terminal);
+ }
+
+ return content;
}
public dispose(): void { }
}
+
+
+interface ISerializeOptions {
+ scrollback?: number;
+ excludeModes?: boolean;
+ excludeAltBuffer?: boolean;
+}
diff --git a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts
index 5b615db1..334016e6 100644
--- a/addons/xterm-addon-serialize/test/SerializeAddon.api.ts
+++ b/addons/xterm-addon-serialize/test/SerializeAddon.api.ts
@@ -4,22 +4,41 @@
*/
import { assert } from 'chai';
-import { openTerminal, writeSync, getBrowserType } from '../../../out-test/api/TestUtils';
+import { openTerminal, writeSync, launchBrowser } from '../../../out-test/api/TestUtils';
import { Browser, Page } from 'playwright';
-const APP = 'http://127.0.0.1:3000/test';
+const APP = 'http://127.0.0.1:3001/test';
let browser: Browser;
let page: Page;
const width = 800;
const height = 600;
+const writeRawSync = (page: any, str: string): Promise => writeSync(page, '\' +' + JSON.stringify(str) + '+ \'');
+
+const testNormalScreenEqual = async (page: any, str: string): Promise => {
+ await writeRawSync(page, str);
+ const originalBuffer = await page.evaluate(`inspectBuffer(term.buffer.normal);`);
+
+ const result = await page.evaluate(`serializeAddon.serialize();`) as string;
+ await page.evaluate(`term.reset();`);
+ await writeRawSync(page, result);
+ const newBuffer = await page.evaluate(`inspectBuffer(term.buffer.normal);`);
+
+ // chai decides -0 and 0 are different number...
+ // and firefox have a bug that output -0 for unknown reason
+ assert.equal(JSON.stringify(originalBuffer), JSON.stringify(newBuffer));
+};
+
+async function testSerializeEquals(writeContent: string, expectedSerialized: string): Promise {
+ await writeRawSync(page, writeContent);
+ const result = await page.evaluate(`serializeAddon.serialize();`) as string;
+ assert.strictEqual(result, expectedSerialized);
+}
+
describe('SerializeAddon', () => {
before(async function(): Promise {
- const browserType = getBrowserType();
- browser = await browserType.launch({
- headless: process.argv.indexOf('--headless') !== -1
- });
+ browser = await launchBrowser();
page = await (await browser.newContext()).newPage();
await page.setViewportSize({ width, height });
await page.goto(APP);
@@ -27,19 +46,72 @@ describe('SerializeAddon', () => {
await page.evaluate(`
window.serializeAddon = new SerializeAddon();
window.term.loadAddon(window.serializeAddon);
+ window.inspectBuffer = (buffer) => {
+ const lines = [];
+ for (let i = 0; i < buffer.length; i++) {
+ // Do this intentionally to get content of underlining source
+ const bufferLine = buffer.getLine(i)._line;
+ lines.push(JSON.stringify(bufferLine));
+ }
+ return {
+ x: buffer.cursorX,
+ y: buffer.cursorY,
+ data: lines
+ };
+ }
`);
});
after(async () => await browser.close());
beforeEach(async () => await page.evaluate(`window.term.reset()`));
+ it('produce different output when we call test util with different text', async function(): Promise {
+ await writeRawSync(page, '12345');
+ const buffer1 = await page.evaluate(`inspectBuffer(term.buffer.normal);`);
+
+ await page.evaluate(`term.reset();`);
+ await writeRawSync(page, '67890');
+ const buffer2 = await page.evaluate(`inspectBuffer(term.buffer.normal);`);
+
+ assert.throw(() => {
+ assert.equal(JSON.stringify(buffer1), JSON.stringify(buffer2));
+ });
+ });
+
+ it('produce different output when we call test util with different line wrap', async function(): Promise {
+ await writeRawSync(page, '1234567890\r\n12345');
+ const buffer3 = await page.evaluate(`inspectBuffer(term.buffer.normal);`);
+
+ await page.evaluate(`term.reset();`);
+ await writeRawSync(page, '1234567890n12345');
+ const buffer4 = await page.evaluate(`inspectBuffer(term.buffer.normal);`);
+
+ assert.throw(() => {
+ assert.equal(JSON.stringify(buffer3), JSON.stringify(buffer4));
+ });
+ });
+
it('empty content', async function(): Promise {
- const rows = 10;
- const cols = 10;
assert.equal(await page.evaluate(`serializeAddon.serialize();`), '');
});
- it('trim last empty lines', async function(): Promise {
+ it('unwrap wrapped line', async function(): Promise {
+ const lines = ['123456789123456789'];
+ await writeSync(page, lines.join('\\r\\n'));
+ assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
+ });
+
+ it('does not unwrap non-wrapped line', async function(): Promise {
+ const lines = [
+ '123456789',
+ '123456789'
+ ];
+ await writeSync(page, lines.join('\\r\\n'));
+ assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
+ });
+
+
+ it('preserve last empty lines', async function(): Promise {
const cols = 10;
const lines = [
'',
@@ -55,7 +127,7 @@ describe('SerializeAddon', () => {
''
];
await writeSync(page, lines.join('\\r\\n'));
- assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.slice(0, 8).join('\r\n'));
+ assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
});
it('digits content', async function(): Promise {
@@ -67,21 +139,34 @@ describe('SerializeAddon', () => {
assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
});
- it('serialize half rows of content', async function(): Promise {
- const rows = 10;
- const halfRows = rows >> 1;
+ it('serialize with half of scrollback', async function(): Promise {
+ const rows = 20;
+ const scrollback = rows - 10;
+ const halfScrollback = scrollback / 2;
const cols = 10;
const lines = newArray((index: number) => digitsString(cols, index), rows);
await writeSync(page, lines.join('\\r\\n'));
- assert.equal(await page.evaluate(`serializeAddon.serialize(${halfRows});`), lines.slice(halfRows, 2 * halfRows).join('\r\n'));
+ assert.equal(await page.evaluate(`serializeAddon.serialize({ scrollback: ${halfScrollback} });`), lines.slice(halfScrollback, rows).join('\r\n'));
});
- it('serialize 0 rows of content', async function(): Promise {
- const rows = 10;
+ it('serialize 0 rows of scrollback', async function(): Promise {
+ const rows = 20;
const cols = 10;
const lines = newArray((index: number) => digitsString(cols, index), rows);
await writeSync(page, lines.join('\\r\\n'));
- assert.equal(await page.evaluate(`serializeAddon.serialize(0);`), '');
+ assert.equal(await page.evaluate(`serializeAddon.serialize({ scrollback: 0 });`), lines.slice(rows - 10, rows).join('\r\n'));
+ });
+
+ it('serialize exclude modes', async () => {
+ await writeSync(page, 'before\\x1b[?1hafter');
+ assert.equal(await page.evaluate(`serializeAddon.serialize();`), 'beforeafter\x1b[?1h');
+ assert.equal(await page.evaluate(`serializeAddon.serialize({ excludeModes: true });`), 'beforeafter');
+ });
+
+ it('serialize exclude alt buffer', async () => {
+ await writeSync(page, 'normal\\x1b[?1049h\\x1b[Halt');
+ assert.equal(await page.evaluate(`serializeAddon.serialize();`), 'normal\x1b[?1049h\x1b[Halt');
+ assert.equal(await page.evaluate(`serializeAddon.serialize({ excludeAltBuffer: true });`), 'normal');
});
it('serialize all rows of content with color16', async function(): Promise {
@@ -105,17 +190,19 @@ 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(STRIKETHROUGH) + line,
+ sgr(NO_INVERSE) + line,
+ sgr(NO_BOLD) + line,
+ sgr(NO_UNDERLINED) + line,
+ sgr(NO_BLINK) + line,
+ sgr(NO_INVISIBLE) + line,
+ sgr(NO_STRIKETHROUGH) + line
];
const rows = lines.length;
await writeSync(page, lines.join('\\r\\n'));
@@ -137,16 +224,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'));
@@ -156,19 +243,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'));
@@ -178,16 +265,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'));
@@ -197,19 +284,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'));
@@ -219,16 +306,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'));
@@ -238,19 +325,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'));
@@ -276,17 +363,15 @@ describe('SerializeAddon', () => {
'中文中文',
'12中文',
'中文12',
- '1中文中文中' // this line is going to be wrapped at last character because it has line length of 11 (1+2*5)
- ];
- const expected = [
- '中文中文',
- '12中文',
- '中文12',
- '1中文中文',
- '中'
+ // This line is going to be wrapped at last character
+ // because it has line length of 11 (1+2*5).
+ // We concat it back without the null cell currently.
+ // But this may be incorrect.
+ // see also #3097
+ '1中文中文中'
];
await writeSync(page, lines.join('\\r\\n'));
- assert.equal(await page.evaluate(`serializeAddon.serialize();`), expected.join('\r\n'));
+ assert.equal(await page.evaluate(`serializeAddon.serialize();`), lines.join('\r\n'));
});
it('serialize CJK Mixed with tab correctly', async () => {
@@ -299,15 +384,173 @@ describe('SerializeAddon', () => {
await writeSync(page, lines.join('\\r\\n'));
assert.equal(await page.evaluate(`serializeAddon.serialize();`), expected.join('\r\n'));
});
+
+ it('serialize with alt screen correctly', async () => {
+ const SMCUP = '\u001b[?1049h';
+ const CUP = '\u001b[H';
+
+ const lines = [
+ `1${SMCUP}${CUP}2`
+ ];
+ const expected = [
+ `1${SMCUP}${CUP}2`
+ ];
+
+ await writeSync(page, lines.join('\\r\\n'));
+ assert.equal(await page.evaluate(`window.term.buffer.active.type`), 'alternate');
+ assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize();`)), JSON.stringify(expected.join('\r\n')));
+ });
+
+ it('serialize without alt screen correctly', async () => {
+ const SMCUP = '\u001b[?1049h';
+ const RMCUP = '\u001b[?1049l';
+
+ const lines = [
+ `1${SMCUP}2${RMCUP}`
+ ];
+ const expected = [
+ `1`
+ ];
+
+ await writeSync(page, lines.join('\\r\\n'));
+ assert.equal(await page.evaluate(`window.term.buffer.active.type`), 'normal');
+ assert.equal(JSON.stringify(await page.evaluate(`serializeAddon.serialize();`)), JSON.stringify(expected.join('\r\n')));
+ });
+
+ it('serialize with background', async () => {
+ const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`;
+
+ const lines = [
+ `1\u001b[44m${CLEAR_RIGHT(5)}`,
+ `2${CLEAR_RIGHT(9)}`
+ ];
+
+ await testNormalScreenEqual(page, lines.join('\r\n'));
+ });
+
+ it('cause the BCE on scroll', async () => {
+ const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`;
+
+ const padLines = newArray(
+ (index: number) => digitsString(10, index),
+ 10
+ );
+
+ const lines = [
+ ...padLines,
+ `\u001b[44m${CLEAR_RIGHT(5)}1111111111111111`
+ ];
+
+ await testNormalScreenEqual(page, lines.join('\r\n'));
+ });
+
+ it('handle invalid wrap before scroll', async () => {
+ const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`;
+ const MOVE_UP = (l: number): string => `\u001b[${l}A`;
+ const MOVE_DOWN = (l: number): string => `\u001b[${l}B`;
+ const MOVE_LEFT = (l: number): string => `\u001b[${l}D`;
+
+ // A line wrap happened after current line.
+ // But there is no content.
+ // so wrap shouldn't even be able to happen.
+ const segments = [
+ `123456789012345`,
+ MOVE_UP(1),
+ CLEAR_RIGHT(5),
+ MOVE_DOWN(1),
+ MOVE_LEFT(5),
+ CLEAR_RIGHT(5),
+ MOVE_UP(1),
+ '1'
+ ];
+
+ await testNormalScreenEqual(page, segments.join(''));
+ });
+
+ it('handle invalid wrap after scroll', async () => {
+ const CLEAR_RIGHT = (l: number): string => `\u001b[${l}X`;
+ const MOVE_UP = (l: number): string => `\u001b[${l}A`;
+ const MOVE_DOWN = (l: number): string => `\u001b[${l}B`;
+ const MOVE_LEFT = (l: number): string => `\u001b[${l}D`;
+
+ const padLines = newArray(
+ (index: number) => digitsString(10, index),
+ 10
+ );
+
+ // A line wrap happened after current line.
+ // But there is no content.
+ // so wrap shouldn't even be able to happen.
+ const lines = [
+ padLines.join('\r\n'),
+ '\r\n',
+ `123456789012345`,
+ MOVE_UP(1),
+ CLEAR_RIGHT(5),
+ MOVE_DOWN(1),
+ MOVE_LEFT(5),
+ CLEAR_RIGHT(5),
+ MOVE_UP(1),
+ '1'
+ ];
+
+ await testNormalScreenEqual(page, lines.join(''));
+ });
+
+ 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(initial: T | ((index: number) => T), count: number): T[] {
const array: T[] = new Array(count);
for (let i = 0; i < array.length; i++) {
if (typeof initial === 'function') {
- array[i] = (<(index: number) => T>initial)(i);
+ array[i] = (initial as (index: number) => T)(i);
} else {
- array[i] = initial;
+ array[i] = initial as T;
}
}
return array;
@@ -321,7 +564,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`;
}
@@ -350,20 +593,20 @@ const BG_RGB_GREEN = '48;2;0;255;0';
const BG_RGB_YELLOW = '48;2;255;255;0';
const BG_RESET = '49';
-const INVERSE = '7';
const BOLD = '1';
+const DIM = '2';
+const ITALIC = '3';
const UNDERLINED = '4';
const BLINK = '5';
+const INVERSE = '7';
const INVISIBLE = '8';
+const STRIKETHROUGH = '9';
-const NO_INVERSE = '27';
const NO_BOLD = '22';
+const NO_DIM = '22';
+const NO_ITALIC = '23';
const NO_UNDERLINED = '24';
const NO_BLINK = '25';
+const NO_INVERSE = '27';
const NO_INVISIBLE = '28';
-
-const ITALIC = '3';
-const DIM = '2';
-
-const NO_ITALIC = '23';
-const NO_DIM = '22';
+const NO_STRIKETHROUGH = '29';
diff --git a/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts b/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts
index 9e7b500a..a29dbb28 100644
--- a/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts
+++ b/addons/xterm-addon-serialize/typings/xterm-addon-serialize.d.ts
@@ -3,36 +3,53 @@
* @license MIT
*/
-
import { Terminal, ITerminalAddon } from 'xterm';
declare module 'xterm-addon-serialize' {
/**
- * An xterm.js addon that enables web links.
+ * An xterm.js addon that enables serialization of terminal contents.
*/
export class SerializeAddon implements ITerminalAddon {
constructor();
/**
- * Activates the addon
+ * Activates the addon.
* @param terminal The terminal the addon is being loaded in.
*/
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 rows The number of rows to serialize, starting from the bottom of the
- * terminal. This defaults to the number of rows in the viewport.
+ * 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 options Custom options to allow control over what gets serialized.
*/
- public serialize(rows?: number): string;
+ public serialize(options?: ISerializeOptions): string;
/**
* Disposes the addon.
*/
public dispose(): void;
}
+
+ export interface ISerializeOptions {
+ /**
+ * The number of rows in the scrollback buffer to serialize, starting from the bottom of the
+ * scrollback buffer. When not specified, all available rows in the scrollback buffer will be
+ * serialized.
+ */
+ scrollback?: number;
+
+ /**
+ * Whether to exclude the terminal modes from the serialization. False by default.
+ */
+ excludeModes?: boolean;
+
+ /**
+ * Whether to exclude the alt buffer from the serialization. False by default.
+ */
+ excludeAltBuffer?: boolean;
+ }
}
diff --git a/addons/xterm-addon-serialize/webpack.config.js b/addons/xterm-addon-serialize/webpack.config.js
index 4cabbad9..7c0ccd01 100644
--- a/addons/xterm-addon-serialize/webpack.config.js
+++ b/addons/xterm-addon-serialize/webpack.config.js
@@ -25,7 +25,8 @@ module.exports = {
filename: mainFile,
path: path.resolve('./lib'),
library: addonName,
- libraryTarget: 'umd'
+ libraryTarget: 'umd',
+ globalObject: 'this'
},
mode: 'production'
};
diff --git a/addons/xterm-addon-unicode11/package.json b/addons/xterm-addon-unicode11/package.json
index 397bf2b9..9fc69416 100644
--- a/addons/xterm-addon-unicode11/package.json
+++ b/addons/xterm-addon-unicode11/package.json
@@ -1,6 +1,6 @@
{
"name": "xterm-addon-unicode11",
- "version": "0.2.0",
+ "version": "0.3.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
diff --git a/addons/xterm-addon-unicode11/src/Unicode11Addon.ts b/addons/xterm-addon-unicode11/src/Unicode11Addon.ts
index cb8c9c56..d4ddf77e 100644
--- a/addons/xterm-addon-unicode11/src/Unicode11Addon.ts
+++ b/addons/xterm-addon-unicode11/src/Unicode11Addon.ts
@@ -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());
diff --git a/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts b/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts
index d0e09da2..4c695b00 100644
--- a/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts
+++ b/addons/xterm-addon-unicode11/test/Unicode11Addon.api.ts
@@ -4,10 +4,10 @@
*/
import { assert } from 'chai';
-import { openTerminal, getBrowserType } from '../../../out-test/api/TestUtils';
+import { openTerminal, launchBrowser } from '../../../out-test/api/TestUtils';
import { Browser, Page } from 'playwright';
-const APP = 'http://127.0.0.1:3000/test';
+const APP = 'http://127.0.0.1:3001/test';
let browser: Browser;
let page: Page;
@@ -16,10 +16,7 @@ const height = 600;
describe('Unicode11Addon', () => {
before(async function(): Promise {
- const browserType = getBrowserType();
- browser = await browserType.launch({
- headless: process.argv.indexOf('--headless') !== -1
- });
+ browser = await launchBrowser();
page = await (await browser.newContext()).newPage();
await page.setViewportSize({ width, height });
});
diff --git a/addons/xterm-addon-unicode11/webpack.config.js b/addons/xterm-addon-unicode11/webpack.config.js
index 66a83a2f..10c0adc3 100644
--- a/addons/xterm-addon-unicode11/webpack.config.js
+++ b/addons/xterm-addon-unicode11/webpack.config.js
@@ -32,7 +32,8 @@ module.exports = {
filename: mainFile,
path: path.resolve('./lib'),
library: addonName,
- libraryTarget: 'umd'
+ libraryTarget: 'umd',
+ globalObject: 'this'
},
mode: 'production'
};
diff --git a/addons/xterm-addon-web-links/src/WebLinkProvider.ts b/addons/xterm-addon-web-links/src/WebLinkProvider.ts
index af6ad7d3..f0caf974 100644
--- a/addons/xterm-addon-web-links/src/WebLinkProvider.ts
+++ b/addons/xterm-addon-web-links/src/WebLinkProvider.ts
@@ -3,25 +3,45 @@
* @license MIT
*/
-import { ILinkProvider, IBufferCellPosition, ILink, Terminal } from 'xterm';
+import { ILinkProvider, ILink, Terminal, IViewportRange } from 'xterm';
+
+interface ILinkProviderOptions {
+ hover?(event: MouseEvent, text: string, location: IViewportRange): void;
+ leave?(event: MouseEvent, text: string): void;
+}
export class WebLinkProvider implements ILinkProvider {
constructor(
private readonly _terminal: Terminal,
private readonly _regex: RegExp,
- private readonly _handler: (event: MouseEvent, uri: string) => void
+ private readonly _handler: (event: MouseEvent, uri: string) => void,
+ private readonly _options: ILinkProviderOptions = {}
) {
}
public provideLinks(y: number, callback: (links: ILink[] | undefined) => void): void {
- callback(LinkComputer.computeLink(y, this._regex, this._terminal, this._handler));
+ const links = LinkComputer.computeLink(y, this._regex, this._terminal, this._handler);
+ callback(this._addCallbacks(links));
+ }
+
+ private _addCallbacks(links: ILink[]): ILink[] {
+ return links.map(link => {
+ link.leave = this._options.leave;
+ link.hover = (event: MouseEvent, uri: string): void => {
+ if (this._options.hover) {
+ const { range } = link;
+ this._options.hover(event, uri, range);
+ }
+ };
+ return link;
+ });
}
}
export class LinkComputer {
- public static computeLink(y: number, regex: RegExp, terminal: Terminal, handler: (event: MouseEvent, uri: string) => void): ILink[] {
+ public static computeLink(y: number, regex: RegExp, terminal: Terminal, activate: (event: MouseEvent, uri: string) => void): ILink[] {
const rex = new RegExp(regex.source, (regex.flags || '') + 'g');
const [line, startLineIndex] = LinkComputer._translateBufferLineToStringWithWrap(y - 1, false, terminal);
@@ -69,7 +89,7 @@ export class LinkComputer {
}
};
- result.push({ range, text, activate: handler });
+ result.push({ range, text, activate });
}
return result;
diff --git a/addons/xterm-addon-web-links/src/WebLinksAddon.ts b/addons/xterm-addon-web-links/src/WebLinksAddon.ts
index dce405a5..46ddcf7b 100644
--- a/addons/xterm-addon-web-links/src/WebLinksAddon.ts
+++ b/addons/xterm-addon-web-links/src/WebLinksAddon.ts
@@ -3,7 +3,7 @@
* @license MIT
*/
-import { Terminal, ILinkMatcherOptions, ITerminalAddon, IDisposable } from 'xterm';
+import { Terminal, ILinkMatcherOptions, ITerminalAddon, IDisposable, IViewportRange } from 'xterm';
import { WebLinkProvider } from './WebLinkProvider';
const protocolClause = '(https?:\\/\\/)';
@@ -36,6 +36,11 @@ function handleLink(event: MouseEvent, uri: string): void {
}
}
+interface ILinkProviderOptions {
+ hover?(event: MouseEvent, text: string, location: IViewportRange): void;
+ leave?(event: MouseEvent, text: string): void;
+}
+
export class WebLinksAddon implements ITerminalAddon {
private _linkMatcherId: number | undefined;
private _terminal: Terminal | undefined;
@@ -43,20 +48,22 @@ export class WebLinksAddon implements ITerminalAddon {
constructor(
private _handler: (event: MouseEvent, uri: string) => void = handleLink,
- private _options: ILinkMatcherOptions = {},
+ private _options: ILinkMatcherOptions | ILinkProviderOptions = {},
private _useLinkProvider: boolean = false
) {
- this._options.matchIndex = 1;
}
public activate(terminal: Terminal): void {
this._terminal = terminal;
if (this._useLinkProvider && 'registerLinkProvider' in this._terminal) {
- this._linkProvider = this._terminal.registerLinkProvider(new WebLinkProvider(this._terminal, strictUrlRegex, this._handler));
+ const options = this._options as ILinkProviderOptions;
+ this._linkProvider = this._terminal.registerLinkProvider(new WebLinkProvider(this._terminal, strictUrlRegex, this._handler, options));
} else {
// TODO: This should be removed eventually
- this._linkMatcherId = (this._terminal as Terminal).registerLinkMatcher(strictUrlRegex, this._handler, this._options);
+ const options = this._options as ILinkMatcherOptions;
+ options.matchIndex = 1;
+ this._linkMatcherId = (this._terminal as Terminal).registerLinkMatcher(strictUrlRegex, this._handler, options);
}
}
diff --git a/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts b/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts
index 6e42ff96..fe44dc31 100644
--- a/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts
+++ b/addons/xterm-addon-web-links/test/WebLinksAddon.api.ts
@@ -4,10 +4,10 @@
*/
import { assert } from 'chai';
-import { openTerminal, pollFor, writeSync, getBrowserType } from '../../../out-test/api/TestUtils';
+import { openTerminal, pollFor, writeSync, launchBrowser } from '../../../out-test/api/TestUtils';
import { Browser, Page } from 'playwright';
-const APP = 'http://127.0.0.1:3000/test';
+const APP = 'http://127.0.0.1:3001/test';
let browser: Browser;
let page: Page;
@@ -16,10 +16,7 @@ const height = 600;
describe('WebLinksAddon', () => {
before(async function(): Promise {
- const browserType = getBrowserType();
- browser = await browserType.launch({
- headless: process.argv.indexOf('--headless') !== -1
- });
+ browser = await launchBrowser();
page = await (await browser.newContext()).newPage();
await page.setViewportSize({ width, height });
});
diff --git a/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts b/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts
index f0564704..78a258e5 100644
--- a/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts
+++ b/addons/xterm-addon-web-links/typings/xterm-addon-web-links.d.ts
@@ -4,7 +4,7 @@
*/
-import { Terminal, ILinkMatcherOptions, ITerminalAddon } from 'xterm';
+import { Terminal, ILinkMatcherOptions, ITerminalAddon, IViewportRange } from 'xterm';
declare module 'xterm-addon-web-links' {
/**
@@ -20,7 +20,7 @@ declare module 'xterm-addon-web-links' {
* link provider (new) may cause issues. Link provider will eventually be
* the default and only option.
*/
- constructor(handler?: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions, useLinkProvider?: boolean);
+ constructor(handler?: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions | ILinkProviderOptions, useLinkProvider?: boolean);
/**
* Activates the addon
@@ -33,4 +33,21 @@ declare module 'xterm-addon-web-links' {
*/
public dispose(): void;
}
+
+ /**
+ * An object containing options for a link provider.
+ */
+ export interface ILinkProviderOptions {
+ /**
+ * A callback that fires when the mouse hovers over a link for a period of
+ * time (defined by {@link ITerminalOptions.linkTooltipHoverDuration}).
+ */
+ hover?(event: MouseEvent, text: string, location: IViewportRange): void;
+
+ /**
+ * A callback that fires when the mouse leaves a link. Note that this can
+ * happen even when tooltipCallback hasn't fired for the link yet.
+ */
+ leave?(event: MouseEvent, text: string): void;
+ }
}
diff --git a/addons/xterm-addon-webgl/README.md b/addons/xterm-addon-webgl/README.md
index 026a738e..67fafe7b 100644
--- a/addons/xterm-addon-webgl/README.md
+++ b/addons/xterm-addon-webgl/README.md
@@ -1,8 +1,6 @@
## xterm-addon-webgl
-An addon for [xterm.js](https://github.com/xtermjs/xterm.js) that enables a WebGL-based renderer. This addon requires xterm.js v4+.
-
-⚠️ This is an experimental addon that is [missing some features and may be unstable](https://github.com/xtermjs/xterm.js/issues?q=is%3Aopen+is%3Aissue+label%3Aarea%2Faddon%2Fwebgl) ⚠️
+An addon for [xterm.js](https://github.com/xtermjs/xterm.js) that enables a WebGL2-based renderer. This addon requires xterm.js v4+.
### Install
@@ -21,3 +19,18 @@ terminal.loadAddon(new WebglAddon());
```
See the full [API](https://github.com/xtermjs/xterm.js/blob/master/addons/xterm-addon-webgl/typings/xterm-addon-webgl.d.ts) for more advanced usage.
+
+### Handling Context Loss
+
+The browser may drop WebGL contexts for various reasons like OOM or after the system has been suspended. There is an API exposed that fires the `webglcontextlost` event fired on the canvas so embedders can handle it however they wish. An easy, but suboptimal way, to handle this is by disposing of WebglAddon when the event fires:
+
+```ts
+const terminal = new Terminal();
+const addon = new WebglAddon();
+addon.onContextLoss(e => {
+ addon.dispose();
+});
+terminal.loadAddon(addon);
+```
+
+Read more about handling WebGL context losses on the [Khronos wiki](https://www.khronos.org/webgl/wiki/HandlingContextLost).
diff --git a/addons/xterm-addon-webgl/package.json b/addons/xterm-addon-webgl/package.json
index c0e91b37..226f34ba 100644
--- a/addons/xterm-addon-webgl/package.json
+++ b/addons/xterm-addon-webgl/package.json
@@ -1,6 +1,6 @@
{
"name": "xterm-addon-webgl",
- "version": "0.9.0",
+ "version": "0.11.2",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
diff --git a/addons/xterm-addon-webgl/src/GlyphRenderer.ts b/addons/xterm-addon-webgl/src/GlyphRenderer.ts
index 8be4c011..71b3659e 100644
--- a/addons/xterm-addon-webgl/src/GlyphRenderer.ts
+++ b/addons/xterm-addon-webgl/src/GlyphRenderer.ts
@@ -176,8 +176,9 @@ export class GlyphRenderer {
const i = (y * terminal.cols + x) * INDICES_PER_CELL;
- // Exit early if this is a null/space character
- if (code === NULL_CELL_CODE || code === WHITESPACE_CELL_CODE || code === undefined/* This is used for the right side of wide chars */) {
+ // Exit early if this is a null character, allow space character to continue as it may have
+ // underline/strikethrough styles
+ if (code === NULL_CELL_CODE || code === undefined/* This is used for the right side of wide chars */) {
fill(array, 0, i, i + INDICES_PER_CELL - 1 - CELL_POSITION_INDICES);
return;
}
@@ -263,7 +264,7 @@ export class GlyphRenderer {
// Get attributes from fg (excluding inverse) and resolve inverse by pullibng rgb colors
// from bg. This is needed since the inverse fg color should be based on the original bg
// color, not on the selection color
- fg = (fg & ~(Attributes.CM_MASK | Attributes.RGB_MASK | FgFlags.INVERSE));
+ fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK | FgFlags.INVERSE);
switch (workCell.getBgColorMode()) {
case Attributes.CM_P16:
case Attributes.CM_P256:
diff --git a/addons/xterm-addon-webgl/src/WebglAddon.ts b/addons/xterm-addon-webgl/src/WebglAddon.ts
index aef1301e..ad2393d8 100644
--- a/addons/xterm-addon-webgl/src/WebglAddon.ts
+++ b/addons/xterm-addon-webgl/src/WebglAddon.ts
@@ -3,14 +3,17 @@
* @license MIT
*/
-import { Terminal, ITerminalAddon } from 'xterm';
+import { Terminal, ITerminalAddon, IEvent } from 'xterm';
import { WebglRenderer } from './WebglRenderer';
-import { IRenderService } from 'browser/services/Services';
+import { ICharacterJoinerService, IRenderService } from 'browser/services/Services';
import { IColorSet } from 'browser/Types';
+import { EventEmitter } from 'common/EventEmitter';
export class WebglAddon implements ITerminalAddon {
private _terminal?: Terminal;
private _renderer?: WebglRenderer;
+ private _onContextLoss = new EventEmitter();
+ public get onContextLoss(): IEvent { return this._onContextLoss.event; }
constructor(
private _preserveDrawingBuffer?: boolean
@@ -21,9 +24,11 @@ export class WebglAddon implements ITerminalAddon {
throw new Error('Cannot activate WebglAddon before Terminal.open');
}
this._terminal = terminal;
- const renderService: IRenderService = (terminal)._core._renderService;
- const colors: IColorSet = (terminal)._core._colorManager.colors;
- this._renderer = new WebglRenderer(terminal, colors, this._preserveDrawingBuffer);
+ const renderService: IRenderService = (terminal as any)._core._renderService;
+ const characterJoinerService: ICharacterJoinerService = (terminal as any)._core._characterJoinerService;
+ const colors: IColorSet = (terminal as any)._core._colorManager.colors;
+ this._renderer = new WebglRenderer(terminal, colors, characterJoinerService, this._preserveDrawingBuffer);
+ this._renderer.onContextLoss(() => this._onContextLoss.fire());
renderService.setRenderer(this._renderer);
}
diff --git a/addons/xterm-addon-webgl/src/WebglRenderer.ts b/addons/xterm-addon-webgl/src/WebglRenderer.ts
index 9f982165..9d8bde79 100644
--- a/addons/xterm-addon-webgl/src/WebglRenderer.ts
+++ b/addons/xterm-addon-webgl/src/WebglRenderer.ts
@@ -12,13 +12,17 @@ import { RectangleRenderer } from './RectangleRenderer';
import { IWebGL2RenderingContext } from './Types';
import { RenderModel, COMBINED_CHAR_BIT_MASK, RENDER_MODEL_BG_OFFSET, RENDER_MODEL_FG_OFFSET, RENDER_MODEL_INDICIES_PER_CELL } from './RenderModel';
import { Disposable } from 'common/Lifecycle';
-import { NULL_CELL_CODE } from 'common/buffer/Constants';
+import { Content, NULL_CELL_CHAR, NULL_CELL_CODE } from 'common/buffer/Constants';
import { Terminal, IEvent } from 'xterm';
import { IRenderLayer } from './renderLayer/Types';
import { IRenderDimensions, IRenderer, IRequestRedrawEvent } from 'browser/renderer/Types';
import { ITerminal, IColorSet } from 'browser/Types';
import { EventEmitter } from 'common/EventEmitter';
import { CellData } from 'common/buffer/CellData';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { ICharacterJoinerService } from 'browser/services/Services';
+import { CharData, ICellData } from 'common/Types';
+import { AttributeData } from 'common/buffer/AttributeData';
export class WebglRenderer extends Disposable implements IRenderer {
private _renderLayers: IRenderLayer[];
@@ -41,9 +45,13 @@ export class WebglRenderer extends Disposable implements IRenderer {
private _onRequestRedraw = new EventEmitter();
public get onRequestRedraw(): IEvent { return this._onRequestRedraw.event; }
+ private _onContextLoss = new EventEmitter();
+ public get onContextLoss(): IEvent { return this._onContextLoss.event; }
+
constructor(
private _terminal: Terminal,
private _colors: IColorSet,
+ private readonly _characterJoinerService: ICharacterJoinerService,
preserveDrawingBuffer?: boolean
) {
super();
@@ -52,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,
@@ -82,6 +90,9 @@ export class WebglRenderer extends Disposable implements IRenderer {
if (!this._gl) {
throw new Error('WebGL2 not supported ' + this._gl);
}
+
+ this.register(addDisposableDomListener(this._canvas, 'webglcontextlost', (e) => { this._onContextLoss.fire(e); }));
+
this._core.screenElement!.appendChild(this._canvas);
this._rectangleRenderer = new RectangleRenderer(this._terminal, this._colors, this._gl, this.dimensions);
@@ -94,8 +105,10 @@ export class WebglRenderer extends Disposable implements IRenderer {
}
public dispose(): void {
- this._renderLayers.forEach(l => l.dispose());
- this._core.screenElement!.removeChild(this._canvas);
+ for (const l of this._renderLayers) {
+ l.dispose();
+ }
+ this._canvas.parentElement?.removeChild(this._canvas);
super.dispose();
}
@@ -106,22 +119,18 @@ export class WebglRenderer extends Disposable implements IRenderer {
public setColors(colors: IColorSet): void {
this._colors = colors;
// Clear layers and force a full render
- this._renderLayers.forEach(l => {
+ for (const l of this._renderLayers) {
l.setColors(this._terminal, this._colors);
l.reset(this._terminal);
- });
+ }
this._rectangleRenderer.setColors();
this._glyphRenderer.setColors();
this._refreshCharAtlas();
- this._rectangleRenderer.updateSelection(this._model.selection);
- this._glyphRenderer.updateSelection(this._model);
-
// Force a full refresh
this._model.clear();
- this._model.clearSelection();
}
public onDevicePixelRatioChange(): void {
@@ -138,10 +147,11 @@ export class WebglRenderer extends Disposable implements IRenderer {
this._updateDimensions();
this._model.resize(this._terminal.cols, this._terminal.rows);
- this._rectangleRenderer.onResize();
// Resize all render layers
- this._renderLayers.forEach(l => l.resize(this._terminal, this.dimensions));
+ for (const l of this._renderLayers) {
+ l.resize(this._terminal, this.dimensions);
+ }
// Resize the canvas
this._canvas.width = this.dimensions.scaledCanvasWidth;
@@ -152,6 +162,13 @@ export class WebglRenderer extends Disposable implements IRenderer {
// Resize the screen
this._core.screenElement!.style.width = `${this.dimensions.canvasWidth}px`;
this._core.screenElement!.style.height = `${this.dimensions.canvasHeight}px`;
+
+ this._rectangleRenderer.onResize();
+ if (this._model.selection.hasSelection) {
+ // Update selection as dimensions have changed
+ this._rectangleRenderer.updateSelection(this._model.selection);
+ }
+
this._glyphRenderer.setDimensions(this.dimensions);
this._glyphRenderer.onResize();
@@ -159,7 +176,6 @@ export class WebglRenderer extends Disposable implements IRenderer {
// Force a full refresh
this._model.clear();
- this._model.clearSelection();
}
public onCharSizeChanged(): void {
@@ -167,30 +183,37 @@ export class WebglRenderer extends Disposable implements IRenderer {
}
public onBlur(): void {
- this._renderLayers.forEach(l => l.onBlur(this._terminal));
+ for (const l of this._renderLayers) {
+ l.onBlur(this._terminal);
+ }
}
public onFocus(): void {
- this._renderLayers.forEach(l => l.onFocus(this._terminal));
+ for (const l of this._renderLayers) {
+ l.onFocus(this._terminal);
+ }
}
public onSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
- this._renderLayers.forEach(l => l.onSelectionChanged(this._terminal, start, end, columnSelectMode));
+ for (const l of this._renderLayers) {
+ l.onSelectionChanged(this._terminal, start, end, columnSelectMode);
+ }
this._updateSelectionModel(start, end, columnSelectMode);
- this._rectangleRenderer.updateSelection(this._model.selection);
- this._glyphRenderer.updateSelection(this._model);
-
this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1 });
}
public onCursorMove(): void {
- this._renderLayers.forEach(l => l.onCursorMove(this._terminal));
+ for (const l of this._renderLayers) {
+ l.onCursorMove(this._terminal);
+ }
}
public onOptionsChanged(): void {
- this._renderLayers.forEach(l => l.onOptionsChanged(this._terminal));
+ for (const l of this._renderLayers) {
+ l.onOptionsChanged(this._terminal);
+ }
this._updateDimensions();
this._refreshCharAtlas();
}
@@ -207,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');
}
@@ -220,12 +243,13 @@ export class WebglRenderer extends Disposable implements IRenderer {
this._charAtlas?.clearTexture();
this._model.clear();
this._updateModel(0, this._terminal.rows - 1);
- this._glyphRenderer.updateSelection(this._model);
this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1 });
}
public clear(): void {
- this._renderLayers.forEach(l => l.reset(this._terminal));
+ for (const l of this._renderLayers) {
+ l.reset(this._terminal);
+ }
}
public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {
@@ -248,12 +272,14 @@ export class WebglRenderer extends Disposable implements IRenderer {
}
// Update render layers
- this._renderLayers.forEach(l => l.onGridChanged(this._terminal, start, end));
+ for (const l of this._renderLayers) {
+ l.onGridChanged(this._terminal, start, end);
+ }
// Tell renderer the frame is beginning
if (this._glyphRenderer.beginFrame()) {
this._model.clear();
- this._model.clearSelection();
+ this._updateSelectionModel(undefined, undefined);
}
// Update model to reflect what's drawn
@@ -266,16 +292,41 @@ export class WebglRenderer extends Disposable implements IRenderer {
private _updateModel(start: number, end: number): void {
const terminal = this._core;
+ let cell: ICellData = this._workCell;
for (let y = start; y <= end; y++) {
const row = y + terminal.buffer.ydisp;
const line = terminal.buffer.lines.get(row)!;
this._model.lineLengths[y] = 0;
+ const joinedRanges = this._characterJoinerService.getJoinedCharacters(row);
for (let x = 0; x < terminal.cols; x++) {
- line.loadCell(x, this._workCell);
+ line.loadCell(x, cell);
- const chars = this._workCell.getChars();
- let code = this._workCell.getCode();
+ // If true, indicates that the current character(s) to draw were joined.
+ let isJoined = false;
+ let lastCharX = x;
+
+ // Process any joined character ranges as needed. Because of how the
+ // ranges are produced, we know that they are valid for the characters
+ // and attributes of our input.
+ if (joinedRanges.length > 0 && x === joinedRanges[0][0]) {
+ isJoined = true;
+ const range = joinedRanges.shift()!;
+
+ // We already know the exact start and end column of the joined range,
+ // so we get the string and width representing it directly
+ cell = new JoinedCellData(
+ cell,
+ line!.translateToString(true, range[0], range[1]),
+ range[1] - range[0]
+ );
+
+ // Skip over the cells occupied by this range in the loop
+ lastCharX = range[1] - 1;
+ }
+
+ const chars = cell.getChars();
+ let code = cell.getCode();
const i = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
if (code !== NULL_CELL_CODE) {
@@ -284,33 +335,52 @@ export class WebglRenderer extends Disposable implements IRenderer {
// Nothing has changed, no updates needed
if (this._model.cells[i] === code &&
- this._model.cells[i + RENDER_MODEL_BG_OFFSET] === this._workCell.bg &&
- this._model.cells[i + RENDER_MODEL_FG_OFFSET] === this._workCell.fg) {
+ this._model.cells[i + RENDER_MODEL_BG_OFFSET] === cell.bg &&
+ this._model.cells[i + RENDER_MODEL_FG_OFFSET] === cell.fg) {
continue;
}
// Flag combined chars with a bit mask so they're easily identifiable
if (chars.length > 1) {
- code = code | COMBINED_CHAR_BIT_MASK;
+ code |= COMBINED_CHAR_BIT_MASK;
}
// Cache the results in the model
this._model.cells[i] = code;
- this._model.cells[i + RENDER_MODEL_BG_OFFSET] = this._workCell.bg;
- this._model.cells[i + RENDER_MODEL_FG_OFFSET] = this._workCell.fg;
+ this._model.cells[i + RENDER_MODEL_BG_OFFSET] = cell.bg;
+ this._model.cells[i + RENDER_MODEL_FG_OFFSET] = cell.fg;
- this._glyphRenderer.updateCell(x, y, code, this._workCell.bg, this._workCell.fg, chars);
+ this._glyphRenderer.updateCell(x, y, code, cell.bg, cell.fg, chars);
+
+ if (isJoined) {
+ // Restore work cell
+ cell = this._workCell;
+
+ // Null out non-first cells
+ for (x++; x < lastCharX; x++) {
+ const j = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
+ this._glyphRenderer.updateCell(x, y, NULL_CELL_CODE, 0, 0, NULL_CELL_CHAR);
+ this._model.cells[j] = NULL_CELL_CODE;
+ this._model.cells[j + RENDER_MODEL_BG_OFFSET] = this._workCell.bg;
+ this._model.cells[j + RENDER_MODEL_FG_OFFSET] = this._workCell.fg;
+ }
+ }
}
}
this._rectangleRenderer.updateBackgrounds(this._model);
+ if (this._model.selection.hasSelection) {
+ // Model could be updated but the selection is unchanged
+ this._glyphRenderer.updateSelection(this._model);
+ }
}
- private _updateSelectionModel(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
+ private _updateSelectionModel(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean = false): void {
const terminal = this._terminal;
// Selection does not exist
if (!start || !end || (start[0] === end[0] && start[1] === end[1])) {
this._model.clearSelection();
+ this._rectangleRenderer.updateSelection(this._model.selection);
return;
}
@@ -323,6 +393,7 @@ export class WebglRenderer extends Disposable implements IRenderer {
// No need to draw the selection
if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) {
this._model.clearSelection();
+ this._rectangleRenderer.updateSelection(this._model.selection);
return;
}
@@ -334,6 +405,8 @@ export class WebglRenderer extends Disposable implements IRenderer {
this._model.selection.viewportCappedEndRow = viewportCappedEndRow;
this._model.selection.startCol = start[0];
this._model.selection.endCol = end[0];
+
+ this._rectangleRenderer.updateSelection(this._model.selection);
}
/**
@@ -408,3 +481,49 @@ export class WebglRenderer extends Disposable implements IRenderer {
this.dimensions.actualCellWidth = this.dimensions.scaledCellWidth / this._devicePixelRatio;
}
}
+
+// TODO: Share impl with core
+export class JoinedCellData extends AttributeData implements ICellData {
+ private _width: number;
+ // .content carries no meaning for joined CellData, simply nullify it
+ // thus we have to overload all other .content accessors
+ public content: number = 0;
+ public fg: number;
+ public bg: number;
+ public combinedData: string = '';
+
+ constructor(firstCell: ICellData, chars: string, width: number) {
+ super();
+ this.fg = firstCell.fg;
+ this.bg = firstCell.bg;
+ this.combinedData = chars;
+ this._width = width;
+ }
+
+ public isCombined(): number {
+ // always mark joined cell data as combined
+ return Content.IS_COMBINED_MASK;
+ }
+
+ public getWidth(): number {
+ return this._width;
+ }
+
+ public getChars(): string {
+ return this.combinedData;
+ }
+
+ public getCode(): number {
+ // code always gets the highest possible fake codepoint (read as -1)
+ // this is needed as code is used by caches as identifier
+ return 0x1FFFFF;
+ }
+
+ public setFromCharData(value: CharData): void {
+ throw new Error('not implemented');
+ }
+
+ public getAsCharData(): CharData {
+ return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
+ }
+}
diff --git a/addons/xterm-addon-webgl/src/atlas/CharAtlasCache.ts b/addons/xterm-addon-webgl/src/atlas/CharAtlasCache.ts
index 5046006f..41114de0 100644
--- a/addons/xterm-addon-webgl/src/atlas/CharAtlasCache.ts
+++ b/addons/xterm-addon-webgl/src/atlas/CharAtlasCache.ts
@@ -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++) {
diff --git a/addons/xterm-addon-webgl/src/atlas/CharAtlasUtils.ts b/addons/xterm-addon-webgl/src/atlas/CharAtlasUtils.ts
index 5496a500..962eb7b3 100644
--- a/addons/xterm-addon-webgl/src/atlas/CharAtlasUtils.ts
+++ b/addons/xterm-addon-webgl/src/atlas/CharAtlasUtils.ts
@@ -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 &&
diff --git a/addons/xterm-addon-webgl/src/atlas/Types.d.ts b/addons/xterm-addon-webgl/src/atlas/Types.d.ts
index cd73393c..8d2870cd 100644
--- a/addons/xterm-addon-webgl/src/atlas/Types.d.ts
+++ b/addons/xterm-addon-webgl/src/atlas/Types.d.ts
@@ -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;
diff --git a/addons/xterm-addon-webgl/src/atlas/WebglCharAtlas.ts b/addons/xterm-addon-webgl/src/atlas/WebglCharAtlas.ts
index 223ec16a..6128c836 100644
--- a/addons/xterm-addon-webgl/src/atlas/WebglCharAtlas.ts
+++ b/addons/xterm-addon-webgl/src/atlas/WebglCharAtlas.ts
@@ -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.
@@ -80,12 +81,12 @@ export class WebglCharAtlas implements IDisposable {
// The canvas needs alpha because we use clearColor to convert the background color to alpha.
// It might also contain some characters with transparent backgrounds if allowTransparency is
// set.
- this._cacheCtx = throwIfFalsy(this.cacheCanvas.getContext('2d', {alpha: true}));
+ this._cacheCtx = throwIfFalsy(this.cacheCanvas.getContext('2d', { alpha: true }));
this._tmpCanvas = document.createElement('canvas');
- this._tmpCanvas.width = this._config.scaledCharWidth * 2 + TMP_CANVAS_GLYPH_PADDING * 2;
- this._tmpCanvas.height = this._config.scaledCharHeight + TMP_CANVAS_GLYPH_PADDING * 2;
- this._tmpCtx = throwIfFalsy(this._tmpCanvas.getContext('2d', {alpha: this._config.allowTransparency}));
+ 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 }));
}
public dispose(): void {
@@ -317,6 +318,13 @@ export class WebglCharAtlas implements IDisposable {
this.hasCanvasChanged = true;
+ // Allow 1 cell width per character, with a minimum of 2 (CJK), plus some padding. This is used
+ // to draw the glyph to the canvas as well as to restrict the bounding box search to ensure
+ // giant ligatures (eg. =====>) don't impact overall performance.
+ const allowedWidth = this._config.scaledCharWidth * Math.max(chars.length, 2) + TMP_CANVAS_GLYPH_PADDING * 2;
+ if (this._tmpCanvas.width < allowedWidth) {
+ this._tmpCanvas.width = allowedWidth;
+ }
this._tmpCtx.save();
this._workAttributeData.fg = fg;
@@ -331,6 +339,8 @@ export class WebglCharAtlas implements IDisposable {
const inverse = !!this._workAttributeData.isInverse();
const dim = !!this._workAttributeData.isDim();
const italic = !!this._workAttributeData.isItalic();
+ const underline = !!this._workAttributeData.isUnderline();
+ const strikethrough = !!this._workAttributeData.isStrikethrough();
let fgColor = this._workAttributeData.getFgColor();
let fgColorMode = this._workAttributeData.getFgColorMode();
let bgColor = this._workAttributeData.getBgColor();
@@ -358,7 +368,7 @@ export class WebglCharAtlas implements IDisposable {
const fontStyle = italic ? 'italic' : '';
this._tmpCtx.font =
`${fontStyle} ${fontWeight} ${this._config.fontSize * this._config.devicePixelRatio}px ${this._config.fontFamily}`;
- this._tmpCtx.textBaseline = 'middle';
+ this._tmpCtx.textBaseline = 'ideographic';
this._tmpCtx.fillStyle = this._getForegroundCss(bg, bgColorMode, bgColor, fg, fgColorMode, fgColor, inverse, bold);
@@ -367,8 +377,66 @@ export class WebglCharAtlas implements IDisposable {
this._tmpCtx.globalAlpha = DIM_OPACITY;
}
+ // Check if the char is a powerline glyph, these will be restricted to a single cell glyph, no
+ // padding on either side that are allowed for other glyphs since they are designed to be pixel
+ // perfect but may render with "bad" anti-aliasing
+ let isPowerlineGlyph = false;
+ if (chars.length === 1) {
+ const code = chars.charCodeAt(0);
+ if (code >= 0xE0A0 && code <= 0xE0D6) {
+ isPowerlineGlyph = true;
+ }
+ }
+
+ // 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, TMP_CANVAS_GLYPH_PADDING, TMP_CANVAS_GLYPH_PADDING + this._config.scaledCharHeight / 2);
+ 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) {
+ const lineWidth = Math.max(1, Math.floor(this._config.fontSize / 10));
+ const yOffset = this._tmpCtx.lineWidth % 2 === 1 ? 0.5 : 0; // When the width is odd, draw at 0.5 position
+ this._tmpCtx.lineWidth = lineWidth;
+ this._tmpCtx.strokeStyle = this._tmpCtx.fillStyle;
+ this._tmpCtx.beginPath();
+ if (underline) {
+ this._tmpCtx.moveTo(padding, padding + this._config.scaledCharHeight - yOffset);
+ this._tmpCtx.lineTo(padding + this._config.scaledCharWidth, padding + this._config.scaledCharHeight - yOffset);
+ }
+ if (strikethrough) {
+ this._tmpCtx.moveTo(padding, padding + Math.floor(this._config.scaledCharHeight / 2) - yOffset);
+ this._tmpCtx.lineTo(padding + this._config.scaledCharWidth, padding + Math.floor(this._config.scaledCharHeight / 2) - yOffset);
+ }
+ this._tmpCtx.stroke();
+ this._tmpCtx.closePath();
+ }
+
this._tmpCtx.restore();
// clear the background from the character to avoid issues with drawing over the previous
@@ -391,7 +459,7 @@ export class WebglCharAtlas implements IDisposable {
return NULL_RASTERIZED_GLYPH;
}
- const rasterizedGlyph = this._findGlyphBoundingBox(imageData, this._workBoundingBox);
+ 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
@@ -424,11 +492,13 @@ 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): 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;
let found = false;
- for (let y = 0; y < this._tmpCanvas.height; y++) {
- for (let x = 0; x < this._tmpCanvas.width; x++) {
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
if (imageData.data[alphaOffset] !== 0) {
boundingBox.top = y;
@@ -442,8 +512,8 @@ export class WebglCharAtlas implements IDisposable {
}
boundingBox.left = 0;
found = false;
- for (let x = 0; x < this._tmpCanvas.width; x++) {
- for (let y = 0; y < this._tmpCanvas.height; y++) {
+ for (let x = 0; x < width; x++) {
+ for (let y = 0; y < height; y++) {
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
if (imageData.data[alphaOffset] !== 0) {
boundingBox.left = x;
@@ -455,10 +525,10 @@ export class WebglCharAtlas implements IDisposable {
break;
}
}
- boundingBox.right = this._tmpCanvas.width;
+ boundingBox.right = width;
found = false;
- for (let x = this._tmpCanvas.width - 1; x >= 0; x--) {
- for (let y = 0; y < this._tmpCanvas.height; y++) {
+ for (let x = width - 1; x >= 0; x--) {
+ for (let y = 0; y < height; y++) {
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
if (imageData.data[alphaOffset] !== 0) {
boundingBox.right = x;
@@ -470,10 +540,10 @@ export class WebglCharAtlas implements IDisposable {
break;
}
}
- boundingBox.bottom = this._tmpCanvas.height;
+ boundingBox.bottom = height;
found = false;
- for (let y = this._tmpCanvas.height - 1; y >= 0; y--) {
- for (let x = 0; x < this._tmpCanvas.width; x++) {
+ for (let y = height - 1; y >= 0; y--) {
+ for (let x = 0; x < width; x++) {
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
if (imageData.data[alphaOffset] !== 0) {
boundingBox.bottom = y;
@@ -497,8 +567,8 @@ export class WebglCharAtlas implements IDisposable {
y: (boundingBox.bottom - boundingBox.top + 1) / TEXTURE_HEIGHT
},
offset: {
- x: -boundingBox.left + TMP_CANVAS_GLYPH_PADDING,
- y: -boundingBox.top + 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)
}
};
}
diff --git a/addons/xterm-addon-webgl/src/renderLayer/BaseRenderLayer.ts b/addons/xterm-addon-webgl/src/renderLayer/BaseRenderLayer.ts
index da3b4d41..532836ee 100644
--- a/addons/xterm-addon-webgl/src/renderLayer/BaseRenderLayer.ts
+++ b/addons/xterm-addon-webgl/src/renderLayer/BaseRenderLayer.ts
@@ -46,7 +46,7 @@ export abstract class BaseRenderLayer implements IRenderLayer {
}
private _initCanvas(): void {
- this._ctx = throwIfFalsy(this._canvas.getContext('2d', {alpha: this._alpha}));
+ this._ctx = throwIfFalsy(this._canvas.getContext('2d', { alpha: this._alpha }));
// Draw the background if this is an opaque layer
if (!this._alpha) {
this._clearAll();
@@ -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();
}
@@ -224,12 +224,12 @@ export abstract class BaseRenderLayer implements IRenderLayer {
*/
protected _fillCharTrueColor(terminal: Terminal, cell: CellData, x: number, y: number): void {
this._ctx.font = this._getFont(terminal, false, false);
- this._ctx.textBaseline = 'middle';
+ this._ctx.textBaseline = 'ideographic';
this._clipRow(terminal, y);
this._ctx.fillText(
cell.getChars(),
x * this._scaledCellWidth + this._scaledCharLeft,
- y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);
+ y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight);
}
/**
diff --git a/addons/xterm-addon-webgl/src/renderLayer/CursorRenderLayer.ts b/addons/xterm-addon-webgl/src/renderLayer/CursorRenderLayer.ts
index b2e834d3..912c23c9 100644
--- a/addons/xterm-addon-webgl/src/renderLayer/CursorRenderLayer.ts
+++ b/addons/xterm-addon-webgl/src/renderLayer/CursorRenderLayer.ts
@@ -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
) {
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;
}
@@ -193,7 +194,12 @@ export class CursorRenderLayer extends BaseRenderLayer {
private _clearCursor(): void {
if (this._state) {
- this._clearCells(this._state.x, this._state.y, this._state.width, 1);
+ // Avoid potential rounding errors when device pixel ratio is less than 1
+ if (window.devicePixelRatio < 1) {
+ this._clearAll();
+ } else {
+ this._clearCells(this._state.x, this._state.y, this._state.width, 1);
+ }
this._state = {
x: 0,
y: 0,
diff --git a/addons/xterm-addon-webgl/test/WebglRenderer.api.ts b/addons/xterm-addon-webgl/test/WebglRenderer.api.ts
index 558605e2..e6942d1c 100644
--- a/addons/xterm-addon-webgl/test/WebglRenderer.api.ts
+++ b/addons/xterm-addon-webgl/test/WebglRenderer.api.ts
@@ -3,13 +3,13 @@
* @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, launchBrowser, openTerminal, pollFor, writeSync } from '../../../out-test/api/TestUtils';
+import { ITerminalOptions } from '../../../src/common/Types';
-const APP = 'http://127.0.0.1:3000/test';
+const APP = 'http://127.0.0.1:3001/test';
let browser: Browser;
let page: Page;
@@ -18,7 +18,7 @@ const height = 600;
describe('WebGL Renderer Integration Tests', async () => {
const browserType = getBrowserType();
- const isHeadless = process.argv.indexOf('--headless') !== -1;
+ const isHeadless = process.argv.includes('--headless');
// Firefox works only in non-headless mode https://github.com/microsoft/playwright/issues/1032
const areTestsEnabled = browserType.name() === 'chromium' || (browserType.name() === 'firefox' && !isHeadless);
const itWebgl = areTestsEnabled ? it : it.skip;
@@ -890,11 +890,22 @@ async function getCellColor(col: number, row: number): Promise {
return await page.evaluate(`Array.from(window.result)`);
}
+async function getCellPixels(col: number, row: number): Promise {
+ 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 {
- const browserType = getBrowserType();
- browser = await browserType.launch({
- headless: process.argv.indexOf('--headless') !== -1
- });
+ browser = await launchBrowser();
page = await (await browser.newContext()).newPage();
await page.setViewportSize({ width, height });
await page.goto(APP);
diff --git a/addons/xterm-addon-webgl/typings/xterm-addon-webgl.d.ts b/addons/xterm-addon-webgl/typings/xterm-addon-webgl.d.ts
index 5c15aa17..ee390d8a 100644
--- a/addons/xterm-addon-webgl/typings/xterm-addon-webgl.d.ts
+++ b/addons/xterm-addon-webgl/typings/xterm-addon-webgl.d.ts
@@ -3,7 +3,7 @@
* @license MIT
*/
-import { Terminal, ITerminalAddon } from 'xterm';
+import { Terminal, ITerminalAddon, IEvent } from 'xterm';
declare module 'xterm-addon-webgl' {
/**
@@ -29,5 +29,10 @@ declare module 'xterm-addon-webgl' {
* Clears the terminal's texture atlas and triggers a redraw.
*/
public clearTextureAtlas(): void;
+
+ /**
+ * Fired when the WebglRenderer loses context
+ */
+ public get onContextLoss(): IEvent;
}
}
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 4b2c5f73..5d4e9918 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -10,7 +10,7 @@ jobs:
steps:
- task: NodeTool@0
inputs:
- versionSpec: '10.x'
+ versionSpec: '14.x'
displayName: 'Install Node.js'
- task: YarnInstaller@3
inputs:
@@ -43,7 +43,7 @@ jobs:
steps:
- task: NodeTool@0
inputs:
- versionSpec: '10.x'
+ versionSpec: '14.x'
displayName: 'Install Node.js'
- task: CacheBeta@1
inputs:
@@ -63,7 +63,7 @@ jobs:
steps:
- task: NodeTool@0
inputs:
- versionSpec: '10.x'
+ versionSpec: '14.x'
displayName: 'Install Node.js'
- task: CacheBeta@1
inputs:
@@ -92,7 +92,7 @@ jobs:
displayName: Install required packages
- task: NodeTool@0
inputs:
- versionSpec: '10.x'
+ versionSpec: '14.x'
displayName: 'Install Node.js'
- task: YarnInstaller@3
inputs:
@@ -100,10 +100,6 @@ jobs:
displayName: 'Install Yarn'
- script: yarn --frozen-lockfile
displayName: 'Install dependencies and build'
- - script: |
- yarn start &
- sleep 10
- displayName: 'Start test server'
- script: yarn test-api-chromium --headless --forbid-only
displayName: 'Integration tests (Chromium)'
- script: xvfb-run --auto-servernum -- bash -c "yarn test-api-firefox --headless --forbid-only"
@@ -115,14 +111,10 @@ jobs:
steps:
- task: NodeTool@0
inputs:
- versionSpec: '10.x'
+ versionSpec: '14.x'
displayName: 'Install Node.js'
- script: yarn --frozen-lockfile
displayName: 'Install dependencies and build'
- - script: |
- yarn start &
- sleep 10
- displayName: 'Start test server'
- script: yarn test-api-chromium --headless --forbid-only
displayName: 'Integration tests (Chromium)'
- script: yarn test-api-firefox --headless --forbid-only
@@ -130,6 +122,21 @@ jobs:
- script: yarn test-api-webkit --headless --forbid-only
displayName: 'Integration tests (Webkit)'
+- job: Windows_IntegrationTests
+ pool:
+ vmImage: 'vs2017-win2016'
+ steps:
+ - task: NodeTool@0
+ inputs:
+ versionSpec: '14.x'
+ displayName: 'Install Node.js'
+ - script: yarn --frozen-lockfile
+ displayName: 'Install dependencies and build'
+ - script: yarn test-api-chromium --headless --forbid-only
+ displayName: 'Integration tests (Chromium)'
+ - script: yarn test-api-firefox --headless --forbid-only
+ displayName: 'Integration tests (Firefox)'
+
- job: Release
dependsOn:
- Linux
@@ -137,13 +144,14 @@ jobs:
- Windows
- Linux_IntegrationTests
- macOS_IntegrationTests
+ - Windows_IntegrationTests
condition: and(succeeded(), or(eq(variables['Build.SourceBranch'], 'refs/heads/master'), eq(variables['FORCE_RELEASE'], 'true')))
pool:
vmImage: 'ubuntu-16.04'
steps:
- task: NodeTool@0
inputs:
- versionSpec: '10.x'
+ versionSpec: '14.x'
displayName: 'Install Node.js'
- task: YarnInstaller@3
inputs:
@@ -156,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'
diff --git a/bin/package_headless.js b/bin/package_headless.js
new file mode 100644
index 00000000..d002a95e
--- /dev/null
+++ b/bin/package_headless.js
@@ -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}`);
+});
diff --git a/bin/publish.js b/bin/publish.js
index 64336fdc..3c729f6c 100644
--- a/bin/publish.js
+++ b/bin/publish.js
@@ -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
diff --git a/bin/test_api.js b/bin/test_api.js
index 7afb34bc..f173b417 100644
--- a/bin/test_api.js
+++ b/bin/test_api.js
@@ -34,19 +34,37 @@ if (process.argv.length > 2) {
env.DEBUG = flagArgs.indexOf('--debug') >= 0 ? 'debug' : '';
+env.PORT = 3001;
-const run = cp.spawnSync(
- npmBinScript('mocha'),
- [...testFiles, ...flagArgs],
- {
- cwd: path.resolve(__dirname, '..'),
- env,
- stdio: 'inherit'
+const server = cp.spawn('node', ['demo/start'], {
+ cwd: path.resolve(__dirname, '..'),
+ env,
+ stdio: 'pipe'
+})
+
+server.stdout.on('data', (data) => {
+ // await for the server to fully start
+ if (data.indexOf("successfully") !== -1) {
+ const run = cp.spawnSync(
+ npmBinScript('mocha'),
+ [...testFiles, ...flagArgs], {
+ cwd: path.resolve(__dirname, '..'),
+ env,
+ stdio: 'inherit'
+ }
+ );
+
+ function npmBinScript(script) {
+ return path.resolve(__dirname, `../node_modules/.bin/` + (process.platform === 'win32' ?
+ `${script}.cmd` : script));
+ }
+
+ server.kill();
+
+ process.exit(run.status);
}
-);
+});
-function npmBinScript(script) {
- return path.resolve(__dirname, `../node_modules/.bin/` + (process.platform === 'win32' ? `${script}.cmd` : script));
-}
-
-process.exit(run.status);
+server.stderr.on('data', (data) => {
+ console.error(data.toString());
+});
diff --git a/css/xterm.css b/css/xterm.css
index 7ddcc2d0..3fab18bd 100644
--- a/css/xterm.css
+++ b/css/xterm.css
@@ -36,7 +36,6 @@
*/
.xterm {
- font-feature-settings: "liga" 0;
position: relative;
user-select: none;
-ms-user-select: none;
@@ -169,3 +168,7 @@
.xterm-underline {
text-decoration: underline;
}
+
+.xterm-strikethrough {
+ text-decoration: line-through;
+}
diff --git a/demo/client.ts b/demo/client.ts
index 93b7c26c..a5ac8bb5 100644
--- a/demo/client.ts
+++ b/demo/client.ts
@@ -16,6 +16,7 @@ import { SerializeAddon } from '../addons/xterm-addon-serialize/out/SerializeAdd
import { WebLinksAddon } from '../addons/xterm-addon-web-links/out/WebLinksAddon';
import { WebglAddon } from '../addons/xterm-addon-webgl/out/WebglAddon';
import { Unicode11Addon } from '../addons/xterm-addon-unicode11/out/Unicode11Addon';
+import { LigaturesAddon } from '../addons/xterm-addon-ligatures/out/LigaturesAddon';
// Use webpacked version (yarn package)
// import { Terminal } from '../lib/xterm';
@@ -26,6 +27,7 @@ import { Unicode11Addon } from '../addons/xterm-addon-unicode11/out/Unicode11Add
// import { WebLinksAddon } from 'xterm-addon-web-links';
// import { WebglAddon } from 'xterm-addon-webgl';
// import { Unicode11Addon } from 'xterm-addon-unicode11';
+// import { LigaturesAddon } from 'xterm-addon-ligatures';
// Pulling in the module's types relies on the above, it's looks a
// little weird here as we're importing "this" module
@@ -41,6 +43,7 @@ export interface IWindowWithTerminal extends Window {
WebLinksAddon?: typeof WebLinksAddon;
WebglAddon?: typeof WebglAddon;
Unicode11Addon?: typeof Unicode11Addon;
+ LigaturesAddon?: typeof LigaturesAddon;
}
declare let window: IWindowWithTerminal;
@@ -50,7 +53,7 @@ let socketURL;
let socket;
let pid;
-type AddonType = 'attach' | 'fit' | 'search' | 'serialize' | 'unicode11' | 'web-links' | 'webgl';
+type AddonType = 'attach' | 'fit' | 'search' | 'serialize' | 'unicode11' | 'web-links' | 'webgl' | 'ligatures';
interface IDemoAddon {
name: T;
@@ -62,8 +65,9 @@ interface IDemoAddon {
T extends 'serialize' ? typeof SerializeAddon :
T extends 'web-links' ? typeof WebLinksAddon :
T extends 'unicode11' ? typeof Unicode11Addon :
+ T extends 'ligatures' ? typeof LigaturesAddon :
typeof WebglAddon;
- instance?:
+ instance?:
T extends 'attach' ? AttachAddon :
T extends 'fit' ? FitAddon :
T extends 'search' ? SearchAddon :
@@ -71,6 +75,7 @@ interface IDemoAddon {
T extends 'web-links' ? WebLinksAddon :
T extends 'webgl' ? WebglAddon :
T extends 'unicode11' ? typeof Unicode11Addon :
+ T extends 'ligatures' ? typeof LigaturesAddon :
never;
}
@@ -81,7 +86,8 @@ const addons: { [T in AddonType]: IDemoAddon} = {
serialize: { name: 'serialize', ctor: SerializeAddon, canChange: true },
'web-links': { name: 'web-links', ctor: WebLinksAddon, canChange: true },
webgl: { name: 'webgl', ctor: WebglAddon, canChange: true },
- unicode11: { name: 'unicode11', ctor: Unicode11Addon, canChange: true }
+ unicode11: { name: 'unicode11', ctor: Unicode11Addon, canChange: true },
+ ligatures: { name: 'ligatures', ctor: LigaturesAddon, canChange: true }
};
const terminalContainer = document.getElementById('terminal-container');
@@ -117,6 +123,7 @@ const disposeRecreateButtonHandler = () => {
addons.search.instance = undefined;
addons.serialize.instance = undefined;
addons.unicode11.instance = undefined;
+ addons.ligatures.instance = undefined;
addons['web-links'].instance = undefined;
addons.webgl.instance = undefined;
document.getElementById('dispose').innerHTML = 'Recreate Terminal';
@@ -133,12 +140,15 @@ if (document.location.pathname === '/test') {
window.SearchAddon = SearchAddon;
window.SerializeAddon = SerializeAddon;
window.Unicode11Addon = Unicode11Addon;
+ window.LigaturesAddon = LigaturesAddon;
window.WebLinksAddon = WebLinksAddon;
window.WebglAddon = WebglAddon;
} else {
createTerminal();
document.getElementById('dispose').addEventListener('click', disposeRecreateButtonHandler);
document.getElementById('serialize').addEventListener('click', serializeButtonHandler);
+ document.getElementById('custom-glyph').addEventListener('click', writeCustomGlyphHandler);
+ document.getElementById('load-test').addEventListener('click', loadTest);
}
function createTerminal(): void {
@@ -149,7 +159,8 @@ function createTerminal(): void {
const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].indexOf(navigator.platform) >= 0;
term = new Terminal({
- windowsMode: isWindows
+ windowsMode: isWindows,
+ fontFamily: 'Fira Code, courier-new, courier, monospace'
} as ITerminalOptions);
// Load addons
@@ -339,6 +350,9 @@ function initOptions(term: TerminalType): void {
} else if (o === 'lineHeight' || o === 'scrollSensitivity') {
term.setOption(o, parseFloat(input.value));
updateTerminalSize();
+ } else if(o === 'scrollback') {
+ term.setOption(o, parseInt(input.value));
+ setTimeout(() => updateTerminalSize(), 5);
} else {
term.setOption(o, parseInt(input.value));
}
@@ -363,6 +377,9 @@ function initAddons(term: TerminalType): void {
if (!addon.canChange) {
checkbox.disabled = true;
}
+ if(name === 'unicode11' && checkbox.checked) {
+ term.unicode.activeVersion = '11';
+ }
addDomListener(checkbox, 'change', () => {
if (checkbox.checked) {
addon.instance = new addon.ctor();
@@ -371,10 +388,14 @@ function initAddons(term: TerminalType): void {
setTimeout(() => {
document.body.appendChild((addon.instance as WebglAddon).textureAtlas);
}, 0);
+ } else if (name === 'unicode11') {
+ term.unicode.activeVersion = '11';
}
} else {
if (name === 'webgl') {
document.body.removeChild((addon.instance as WebglAddon).textureAtlas);
+ } else if (name === 'unicode11') {
+ term.unicode.activeVersion = '6';
}
addon.instance!.dispose();
addon.instance = undefined;
@@ -422,3 +443,82 @@ 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);
+}
+
+function loadTest() {
+ const isWebglEnabled = !!addons.webgl.instance;
+ const testData = [];
+ let byteCount = 0;
+ for (let i = 0; i < 50; i++) {
+ const count = 1 + Math.floor(Math.random() * 79);
+ byteCount += count + 2;
+ const data = new Uint8Array(count + 2);
+ data[0] = 0x0A; // \n
+ for (let i = 1; i < count + 1; i++) {
+ data[i] = 0x61 + Math.floor(Math.random() * (0x7A - 0x61));
+ }
+ // End each line with \r so the cursor remains constant, this is what ls/tree do and improves
+ // performance significantly due to the cursor DOM element not needing to change
+ data[data.length - 1] = 0x0D; // \r
+ testData.push(data);
+ }
+ const start = performance.now();
+ for (let i = 0; i < 1024; i++) {
+ for (const d of testData) {
+ term.write(d);
+ }
+ }
+ // Wait for all data to be parsed before evaluating time
+ term.write('', () => {
+ const time = Math.round(performance.now() - start);
+ const mbs = ((byteCount / 1024) * (1 / (time / 1000))).toFixed(2);
+ term.write(`\n\r\nWrote ${byteCount}kB in ${time}ms (${mbs}MB/s) using the (${isWebglEnabled ? 'webgl' : 'canvas'} renderer)`);
+ // Send ^C to get a new prompt
+ term._core._onData.fire('\x03');
+ });
+}
diff --git a/demo/index.html b/demo/index.html
index ab5b2040..9c86783b 100644
--- a/demo/index.html
+++ b/demo/index.html
@@ -15,41 +15,91 @@
xterm.js: A terminal for the web
-
-
-
Options
-
These options can be set in the Terminal constructor or by using the Terminal.setOption function.
-
-
-
-
-
Style
-
-
-
+
+
+
+
+
+
+
+
+
+
+
Options
+
These options can be set in the Terminal constructor or by using the Terminal.setOption function.
+
+
+
+
+
Style
+
+
+
+
+
+
+
Test
+
+
+
+
+
+
-
-
-
-
+
+
+