clone ligatures addon repo

This commit is contained in:
Labhansh Agrawal
2020-05-01 14:26:03 +05:30
parent 939de5d151
commit 15df03ba09
24 changed files with 3484 additions and 0 deletions
@@ -0,0 +1,14 @@
root = true
[*]
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
[*.{j,t}s]
max_line_length = 100
[*.md]
trim_trailing_whitespace = false
@@ -0,0 +1,18 @@
---
name: Bug report
about: Create a bug report
---
<!-- ⚠️ Please search existing issues to avoid creating duplicates. ⚠️ -->
<!-- Describe the bug here. -->
## Details
- Browser and browser and/or electron version:
- OS version:
- xterm.js version:
- xterm-addon-ligatures version:
### Steps to reproduce
1.
2.
@@ -0,0 +1,7 @@
---
name: Feature request
about: Suggest a feature or enhancement
---
<!-- ⚠️ Please search existing issues to avoid creating duplicates. ⚠️ -->
<!-- Describe the enhancement here. -->
@@ -0,0 +1,8 @@
---
name: Question
about: The issue tracker is not for questions. Please ask questions on https://stackoverflow.com/questions/tagged/xtermjs or https://gitter.im/sourcelair/xterm.js.
---
🛑 The issue tracker is not for questions 🛑
If you have a question, please ask it on https://stackoverflow.com/questions/tagged/xtermjs or https://gitter.im/sourcelair/xterm.js.
+13
View File
@@ -0,0 +1,13 @@
node_modules/
.nyc_output/
coverage/
lib/
fonts/
.env
.vscode/
*.swp
*.tgz
npm-debug.log*
yarn-error.log*
+36
View File
@@ -0,0 +1,36 @@
# Blacklist - exclude everything except npm defaults such as LICENSE, etc
*
!*/
# Whitelist - entries to be included must be negated with "!"
!*.js
!*.json
# Whitelist - lib/
!lib/**/*.d.ts
!lib/**/*.js
!lib/**/*.js.map
# Whitelist - src/
!src/**/*.ts
!src/**/*.d.ts
!src/**/*.js
!src/**/*.js.map
# Whitelist - typings/
!typings/**/*.d.ts
# Blacklist - (normal behavior) these will override any whitelist
*.test.ts
*.test.d.ts
*.test.js
*.test.js.map
docs/
/.idea/
.vscode/
coverage/
.nyc_output/
fonts/
+1
View File
@@ -0,0 +1 @@
Jeff Principe <princjef@gmail.com>
@@ -0,0 +1,73 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
education, socio-economic status, nationality, personal appearance, race,
religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting [@Tyriar](https://twitter.com/Tyriar) or [@pariskasid](https://twitter.com/pariskasid) on Twitter. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
@@ -0,0 +1,51 @@
# How to contribute to xterm-addon-ligatures
- [Opening issues for bug reports or feature requests](#opening-issues)
- [Contributing code](#contributing-code)
## Opening issues
The preferred way to report bugs or request features is to use
[GitHub issues](http://github.com/xtermjs/xterm-addon-ligatures/issues). Before
opening an issue, read these pointers.
### Opening issues effectively
- Include information about **the browser in which the problem occurred**. Even
if you tested several browsers, and the problem occurred in all of them,
mention this fact in the bug report. Also include browser version numbers and
the operating system that you're on.
- Mention which release of xterm.js and xterm-addon-ligatures you're using.
Preferably, try also with the current HEAD of the master branch, to ensure the
problem has not already been fixed.
- Mention precisely what went wrong. What did you expect to happen? What
happened instead? Describe the exact steps a maintainer has to take to make
the problem occur.
- Be polite. Issues with an indignant or belligerent tone tend to be moved to
the bottom of the pile.
## Contributing code
- Make sure you have a [GitHub account](https://github.com/join)
- Fork [xterm-addon-ligatures](https://github.com/xtermjs/xterm-addon-ligatures/)
([how to fork a repo](https://help.github.com/articles/fork-a-repo))
- Make your changes
- If your changes are easy to test or likely to regress, add tests. Tests go into corresponding `.test.ts` files.
- Follow the general code style of the rest of the project (see below).
- Submit a pull request
([how to create a pull request](https://help.github.com/articles/fork-a-repo)).
Don't put more than one feature/fix in a single pull request.
By contributing code to xterm-addon-ligatures you
- agree to license the contributed code under xterm-addon-ligatures's [MIT
license](LICENSE).
- confirm that you have the right to contribute and license the code
in question. (Either you hold all rights on the code, or the rights
holder has explicitly granted the right to use it like this,
through a compatible open source license or through a direct
agreement with you.)
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+98
View File
@@ -0,0 +1,98 @@
# xterm-addon-ligatures
[![Build Status](https://dev.azure.com/xtermjs/xterm-addon-ligatures/_apis/build/status/xtermjs.xterm-addon-ligatures)](https://dev.azure.com/xtermjs/xterm-addon-ligatures/_build/latest?definitionId=4)
[![Coverage Status](https://coveralls.io/repos/github/xtermjs/xterm-addon-ligatures/badge.svg?branch=refs%2Fheads%2Fmaster)](https://coveralls.io/github/xtermjs/xterm-addon-ligatures?branch=refs%2Fheads%2Fmaster)
Add support for programming ligatures to [xterm.js][] when running in
environments with access to [Node.js][] APIs (such as [Electron][]).
## Requirements
* [Node.js][] 8.x or higher (present in [Electron][] 1.8.3 or higher)
* [xterm.js][] 4.0.0 or higher using the default canvas renderer
## Usage
Install in your project by running:
```
npm install xterm-addon-ligatures
```
Then, modify the location where you initialize the terminal to enable ligature
support after opening. If you enable ligatures prior to opening the terminal,
they will not function properly.
Your code should look something like this:
```js
import { Terminal } from 'xterm';
import * as ligatures from 'xterm-addon-ligatures';
Terminal.applyAddon(ligatures);
const terminal = new Terminal();
terminal.open(document.getElementById('terminal-mount'));
terminal.enableLigatures();
```
### Importing in TypeScript
If you use TypeScript, you will need to cast the terminal variable as `any` when
you enable ligatures because TypeScript does not know that the addon is
available on the terminal object. It will look like this:
```ts
(terminal as any).enableLigatures()
```
Alternatively, you can import the addon directly as a function and pass the
terminal as an argument:
```js
import { Terminal } from 'xterm';
import { enableLigatures } from 'xterm-addon-ligatures';
const terminal = new Terminal();
terminal.open(document.getElementById('terminal-mount'));
enableLigatures(terminal);
```
## How It Works
In a browser environment, font ligature information is read directly by the web
browser and used to render text correctly without any intervention from the
developer. As of version 3, xterm.js uses the canvas to render characters
individually, resulting in a significant performance boost. However, this means
that it can no longer lean on the browser to determine when to draw font
ligatures.
This package locates the font file on disk for the font currently in use by the
terminal and parses the ligature information out of it (via the
[font-ligatures][] package). As text is rendered in xterm.js, this package
annotates it with the locations of ligatures, allowing xterm.js to render it
correctly.
Since this package depends on being able to find and resolve a system font from
disk, it has to have system access that isn't available in the web browser. As a
result, this package is mainly useful in environments that combine browser and
Node.js runtimes (such as [Electron][]).
## Fonts
This package makes use of the following fonts for testing:
* [Fira Code][] - [Licensed under the OFL][Fira Code License] by Nikita
Prokopov, Mozilla Foundation with reserved names Fira Code, Fira Mono, and
Fira Sans
* [Iosevka][] - [Licensed under the OFL][Iosevka License] by Belleve Invis with
reserved name Iosevka
[xterm.js]: https://github.com/xtermjs/xterm.js
[Electron]: https://electronjs.org/
[Node.js]: https://nodejs.org/
[font-ligatures]: https://github.com/princjef/font-ligatures
[Fira Code]: https://github.com/tonsky/FiraCode
[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
@@ -0,0 +1,76 @@
# Node.js
# Build a general Node.js application with npm.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://docs.microsoft.com/vsts/pipelines/languages/javascript
jobs:
- job: Linux
pool:
vmImage: 'ubuntu-16.04'
steps:
- task: NodeTool@0
inputs:
versionSpec: '8.x'
displayName: 'Install Node.js'
- task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2
inputs:
versionSpec: "1.9.4"
displayName: 'Install Yarn'
- script: |
yarn
displayName: 'Install dependencies'
- script: |
yarn build
displayName: 'Build'
- script: |
yarn test
displayName: 'Test'
- script: |
yarn lint
displayName: 'Lint'
- script: |
export COVERALLS_GIT_BRANCH=$BUILD_SOURCEBRANCH
yarn coveralls
displayName: 'Publish coverage'
- job: macOS
pool:
vmImage: 'xcode9-macos10.13'
steps:
- task: NodeTool@0
inputs:
versionSpec: '8.x'
displayName: 'Install Node.js'
- script: |
yarn
displayName: 'Install dependencies'
- script: |
yarn build
displayName: 'Build'
- script: |
yarn test
displayName: 'Test'
- script: |
yarn lint
displayName: 'Lint'
- job: Windows
pool:
vmImage: 'vs2017-win2016'
steps:
- task: NodeTool@0
inputs:
versionSpec: '8.x'
displayName: 'Install Node.js'
- script: |
yarn
displayName: 'Install dependencies'
- script: |
yarn build
displayName: 'Build'
- script: |
yarn test
displayName: 'Test'
- script: |
yarn lint
displayName: 'Lint'
@@ -0,0 +1,70 @@
const fs = require('fs');
const path = require('path');
const util = require('util');
const axios = require('axios').default;
const mkdirp = require('mkdirp');
const yauzl = require('yauzl');
const urls = {
fira: 'https://github.com/tonsky/FiraCode/raw/master/distr/otf/FiraCode-Regular.otf',
iosevka: 'https://github.com/be5invis/Iosevka/releases/download/v1.14.3/01-iosevka-1.14.3.zip'
};
const writeFile = util.promisify(fs.writeFile);
const fontsFolder = path.join(__dirname, '../fonts');
async function download() {
await mkdirp(fontsFolder);
await downloadFiraCode();
await downloadIosevka();
console.log('Loaded all fonts for testing')
}
async function downloadFiraCode() {
const file = path.join(fontsFolder, 'firaCode.otf');
if (await util.promisify(fs.exists)(file)) {
console.log('Fira Code already loaded');
} else {
console.log('Downloading Fira Code...');
await writeFile(
file,
(await axios.get(urls.fira, { responseType: 'arraybuffer' })).data
);
}
}
async function downloadIosevka() {
const file = path.join(fontsFolder, 'iosevka.ttf');
if (await util.promisify(fs.exists)(file)) {
console.log('Iosevka already loaded');
} else {
console.log('Downloading Iosevka...');
const iosevkaContents = (await axios.get(urls.iosevka, { responseType: 'arraybuffer' })).data;
const iosevkaZipfile = await util.promisify(yauzl.fromBuffer)(iosevkaContents);
await new Promise((resolve, reject) => {
iosevkaZipfile.on('entry', entry => {
if (entry.fileName === 'ttf/iosevka-regular.ttf') {
iosevkaZipfile.openReadStream(entry, (err, stream) => {
if (err) {
return reject(err);
}
const writeStream = fs.createWriteStream(file);
stream.pipe(writeStream);
writeStream.on('close', () => resolve());
});
}
});
});
}
}
download();
process.on('unhandledRejection', e => {
console.error(e);
process.exit(1);
});
+79
View File
@@ -0,0 +1,79 @@
{
"name": "xterm-addon-ligatures",
"version": "0.2.1",
"description": "Add support for programming ligatures to xterm.js",
"homepage": "https://github.com/xtermjs/xterm-addon-ligatures#readme",
"repository": {
"type": "git",
"url": "https://github.com/xtermjs/xterm-addon-ligatures.git"
},
"bugs": {
"url": "https://github.com/xtermjs/xterm-addon-ligatures/issues"
},
"engines": {
"node": ">8.0.0"
},
"main": "lib/LigaturesAddon.js",
"types": "typings/xterm-addon-ligatures.d.ts",
"scripts": {
"prepare": "node bin/download-fonts.js",
"lint": "tslint --project tsconfig.json --fix",
"prebuild": "npm run lint",
"build": "tsc",
"watch": "tsc -w",
"pretest": "npm run build",
"test": "nyc mocha lib/**/*.test.js",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"prepublish": "npm run build"
},
"keywords": [
"font",
"ligature",
"xterm",
"xterm.js",
"terminal"
],
"license": "MIT",
"dependencies": {
"font-finder": "^1.0.4",
"font-ligatures": "^1.3.2"
},
"devDependencies": {
"@types/chai": "^4.1.3",
"@types/mocha": "^5.2.0",
"@types/node": "^8.10.10",
"@types/sinon": "^5.0.1",
"axios": "^0.18.0",
"chai": "^4.1.2",
"coveralls": "^3.0.2",
"mkdirp": "^0.5.1",
"mocha": "^5.2.0",
"nyc": "^12.0.2",
"sinon": "^6.1.3",
"tslint": "^5.9.1",
"tslint-consistent-codestyle": "^1.13.0",
"typescript": "^2.8.3",
"xterm": "^3.6.0",
"yauzl": "^2.10.0"
},
"peerDependencies": {
"xterm": "^4.0.0"
},
"nyc": {
"sourceMap": true,
"reporter": [
"text",
"html",
"json"
],
"include": [
"lib/**/*.js"
],
"exclude": [
"lib/**/*.test.*",
"lib/**/*.integration.*",
"lib/**/*.d.ts",
"lib/**/*.map*"
]
}
}
@@ -0,0 +1,23 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { Terminal } from 'xterm';
import { enableLigatures } from '.';
export interface ITerminalAddon {
activate(terminal: Terminal): void;
dispose(): void;
}
export class LigaturesAddon implements ITerminalAddon {
constructor() {}
public activate(terminal: Terminal): void {
enableLigatures(terminal);
}
public dispose(): void {}
}
+48
View File
@@ -0,0 +1,48 @@
import * as fontFinder from 'font-finder';
import * as fontLigatures from 'font-ligatures';
import parse from './parse';
let fontsPromise: Promise<fontFinder.FontList> | undefined = undefined;
/**
* Loads the font ligature wrapper for the specified font family if it could be
* resolved, throwing if it is unable to find a suitable match.
* @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<fontLigatures.Font | undefined> {
if (!fontsPromise) {
fontsPromise = fontFinder.list();
}
const fonts = await fontsPromise;
for (const family of parse(fontFamily)) {
// If we reach one of the generic font families, the font resolution
// will end for the browser and we can't determine the specific font
// used. Throw.
if (genericFontFamilies.includes(family)) {
return undefined;
}
if (fonts.hasOwnProperty(family) && fonts[family].length > 0) {
return await fontLigatures.loadFile(fonts[family][0].path, { cacheSize });
}
}
// If none of the fonts could resolve, throw an error
return undefined;
}
// https://drafts.csswg.org/css-fonts-4/#generic-font-families
const genericFontFamilies = [
'serif',
'sans-serif',
'cursive',
'fantasy',
'monospace',
'system-ui',
'emoji',
'math',
'fangsong'
];
@@ -0,0 +1,220 @@
import * as path from 'path';
import * as sinon from 'sinon';
import { assert } from 'chai';
import * as fontFinder from 'font-finder';
import * as fontLigatures from 'font-ligatures';
import * as ligatureSupport from '.';
describe('xterm-addon-ligatures', () => {
let onRefresh: sinon.SinonStub;
let term: MockTerminal;
// -> forms a ligature in Fira Code and Iosevka, but www only forms a ligature
// in Fira Code
const input = 'a -> b www c';
before(() => {
sinon.stub(fontFinder, 'list').returns(Promise.resolve({
'Fira Code': [{
path: path.join(__dirname, '../fonts/firaCode.otf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
'Iosevka': [{
path: path.join(__dirname, '../fonts/iosevka.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
'Nonexistant Font': [{
path: path.join(__dirname, '../fonts/nonexistant.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}]
} as fontFinder.FontList));
});
beforeEach(() => {
MockTerminal.applyAddon(ligatureSupport);
onRefresh = sinon.stub();
term = new MockTerminal(onRefresh);
(term as any).enableLigatures();
});
it('registers itself correctly', () => {
MockTerminal.applyAddon(ligatureSupport);
const term = new MockTerminal(sinon.spy());
assert.isUndefined(term.joiner);
(term as any).enableLigatures();
assert.isFunction(term.joiner);
});
it('registers itself correctly when called directly', () => {
const term = new MockTerminal(sinon.spy());
assert.isUndefined(term.joiner);
ligatureSupport.enableLigatures(term as any);
assert.isFunction(term.joiner);
});
it('returns an empty set of ranges on the first call while the font is loading', () => {
assert.deepEqual(term.joiner!(input), []);
});
it('returns the correct set of ranges once the font has loaded', done => {
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
it('handles quoted font names', done => {
term.setOption('fontFamily', '"Fira Code", monospace');
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
it('falls back to later fonts if earlier ones are not present', done => {
term.setOption('fontFamily', 'notinstalled, Fira Code, monospace');
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
it('uses the current font value', done => {
// The first three calls are all synchronous so that we don't allow time for
// any fonts to load while we're switching things around
term.setOption('fontFamily', 'Fira Code');
assert.deepEqual(term.joiner!(input), []);
term.setOption('fontFamily', 'notinstalled');
assert.deepEqual(term.joiner!(input), []);
term.setOption('fontFamily', 'Iosevka');
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4]]);
// And switch it back to Fira Code for good measure
term.setOption('fontFamily', 'Fira Code');
// At this point, we haven't loaded the new font, so the result reverts
// back to empty until that happens
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
});
it('allows multiple terminal instances that use different fonts', done => {
const onRefresh2 = sinon.stub();
const term2 = new MockTerminal(onRefresh2);
term2.setOption('fontFamily', 'Iosevka');
(term2 as any).enableLigatures();
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
assert.deepEqual(term2.joiner!(input), []);
onRefresh2.callsFake(() => {
assert.deepEqual(term2.joiner!(input), [[2, 4]]);
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
});
it('fails if it finds but cannot load the font', async () => {
term.setOption('fontFamily', 'Nonexistant Font, monospace');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.throws(() => term.joiner!(input));
});
it('returns nothing if the font is not present on the system', async () => {
term.setOption('fontFamily', 'notinstalled');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.deepEqual(term.joiner!(input), []);
});
it('returns nothing if no specific font is specified', async () => {
term.setOption('fontFamily', 'monospace');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.deepEqual(term.joiner!(input), []);
});
it('returns nothing if no fonts are provided', async () => {
term.setOption('fontFamily', '');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.deepEqual(term.joiner!(input), []);
});
it('fails when given malformed inputs', async () => {
term.setOption('fontFamily', {} as any);
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.throws(() => term.joiner!(input));
});
it('ensures no empty errors are thrown', async () => {
sinon.stub(fontLigatures, 'loadFile').callsFake(async () => { throw undefined; });
term.setOption('fontFamily', 'Iosevka');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.throws(() => term.joiner!(input), 'Failure while loading font');
(fontLigatures.loadFile as sinon.SinonStub).restore();
});
});
class MockTerminal {
static applyAddon(addon: any): void {
addon.apply(MockTerminal);
}
private _options: { [name: string]: string | number; } = {
fontFamily: 'Fira Code, monospace',
rows: 50
};
joiner?: (text: string) => [number, number][];
refresh: (start: number, end: number) => void;
constructor(onRefresh: (start: number, end: number) => void) {
this.refresh = onRefresh;
}
registerCharacterJoiner(handler: (text: string) => [number, number][]): number {
this.joiner = handler;
return 1;
}
deregisterCharacterJoiner(id: number): void {
this.joiner = undefined;
}
setOption(name: string, value: string | number): void {
this._options[name] = value;
}
getOption(name: string): string | number {
return this._options[name];
}
}
function delay(delayMs: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, delayMs));
}
+92
View File
@@ -0,0 +1,92 @@
import { Terminal } from 'xterm';
import { Font } from 'font-ligatures';
import load from './font';
const enum LoadingState {
UNLOADED,
LOADING,
LOADED,
FAILED
}
// Caches 100K characters worth of ligatures. In practice this works out to
// about 650 KB worth of cache, when a moderate number of ligatures are present.
const CACHE_SIZE = 100000;
/**
* Enable ligature support for the provided Terminal instance. To function
* properly, this must be called after `open()` is called on the therminal. If
* the font currently in use supports ligatures, the terminal will automatically
* start to render them.
* @param term Terminal instance from xterm.js
*/
export function enableLigatures(term: Terminal): void {
let currentFontName: string | undefined = undefined;
let font: Font | undefined = undefined;
let loadingState: LoadingState = LoadingState.UNLOADED;
let loadError: any | undefined = undefined;
term.registerCharacterJoiner((text: string): [number, number][] => {
// If the font hasn't been loaded yet, load it and return an empty result
const termFont = term.getOption('fontFamily');
if (
termFont &&
(loadingState === LoadingState.UNLOADED || currentFontName !== termFont)
) {
font = undefined;
loadingState = LoadingState.LOADING;
currentFontName = termFont;
const currentCallFontName = currentFontName;
load(currentCallFontName, CACHE_SIZE)
.then(f => {
// Another request may have come in while we were waiting, so make
// sure our font is still vaild.
if (currentCallFontName === term.getOption('fontFamily')) {
loadingState = LoadingState.LOADED;
font = f;
// Only refresh things if we actually found a font
if (f) {
term.refresh(0, term.getOption('rows') - 1);
}
}
})
.catch(e => {
// Another request may have come in while we were waiting, so make
// sure our font is still vaild.
if (currentCallFontName === term.getOption('fontFamily')) {
loadingState = LoadingState.FAILED;
font = undefined;
loadError = e;
}
});
}
if (font && loadingState === LoadingState.LOADED) {
// We clone the entries to avoid the internal cache of the ligature finder
// getting messed up.
return font.findLigatureRanges(text).map<[number, number]>(
range => [range[0], range[1]]
);
} else if (loadingState === LoadingState.FAILED) {
throw loadError || new Error('Failure while loading font');
}
return [];
});
}
/**
* Add capabilities to the provided terminal class for enabling ligature
* support. After calling this function, an `enableLigatures()` method is
* available on the terminal class, which will enable ligature support when
* called.
* @param terminalConstructor Terminal class from xterm.js
*/
export function apply(terminalConstructor: typeof Terminal): void {
(<any>terminalConstructor.prototype).enableLigatures = function (): void {
enableLigatures(this);
};
}
@@ -0,0 +1,70 @@
import { assert } from 'chai';
import parse from './parse';
// TODO: integrate tests from http://test.csswg.org/suites/css-fonts-4_dev/nightly-unstable/
describe('parse', () => {
it('parses individual families', () => {
assert.deepEqual(parse('monospace'), ['monospace']);
});
it('parses multiple families', () => {
assert.deepEqual(parse('Arial, Verdana, serif'), ['Arial', 'Verdana', 'serif']);
});
it('parses quoted families', () => {
assert.deepEqual(parse('"Times New Roman", serif'), ['Times New Roman', 'serif']);
});
it('parses single quoted families', () => {
assert.deepEqual(parse('\'Times New Roman\', serif'), ['Times New Roman', 'serif']);
});
it('parses families with spaces in their names', () => {
assert.deepEqual(parse('Times New Roman, serif'), ['Times New Roman', 'serif']);
});
it('collapses multiple spaces together in identifiers', () => {
assert.deepEqual(parse('Times New Roman, serif'), ['Times New Roman', 'serif']);
});
it('does not collapse multiple spaces together in quoted strings', () => {
assert.deepEqual(parse('"Times New Roman", serif'), ['Times New Roman', 'serif']);
});
it('handles escaped characters in strings', () => {
assert.deepEqual(parse('"quote \\" slash \\\\ slashquote \\\\\\"", serif'), ['quote " slash \\ slashquote \\"', 'serif']);
});
it('fails if a family has an unterminated string', () => {
assert.throws(() => parse('"Unterminated, serif'));
});
it('handles unicode escape sequences', () => {
assert.deepEqual(parse('"space\\20 between", serif'), ['space between', 'serif']);
});
it('swallows only the first space after a unicode escape', () => {
assert.deepEqual(parse('"two-space\\20 between", serif'), ['two-space between', 'serif']);
});
it('automatically ends the unicode escape after six digits', () => {
assert.deepEqual(parse('space\\000020between, serif'), ['space between', 'serif']);
});
it('handles unicode escapes at the end of the family', () => {
assert.deepEqual(parse('endswithbrace \\7b, serif'), ['endswithbrace {', 'serif']);
});
it('handles unicode escapes at the end of the input', () => {
assert.deepEqual(parse('endswithbrace \\7b'), ['endswithbrace {']);
});
it('handles other escaped characters in identifiers', () => {
assert.deepEqual(parse('has\\,comma'), ['has,comma']);
});
it('swallows escaped newlines in strings', () => {
assert.deepEqual(parse('"multi \\\nline", serif'), ['multi line', 'serif']);
});
});
+174
View File
@@ -0,0 +1,174 @@
interface IParseContext {
input: string;
offset: number;
}
/**
* Parses a CSS font family value, returning the component font families
* contained within.
*
* @param family The CSS font family input string to parse
*/
export default function parse(family: string): string[] {
if (typeof family !== 'string') {
throw new Error('Font family must be a string');
}
const context: IParseContext = {
input: family,
offset: 0
};
const families = [];
let currentFamily = '';
// Work through the input character by character until there are none left.
// This lexing and parsing in one pass.
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
switch (char) {
// String
case '\'':
case '"':
currentFamily += parseString(context, char);
break;
// End of family
case ',':
families.push(currentFamily);
currentFamily = '';
break;
default:
// Identifiers (whitespace between families is swallowed)
if (!/\s/.test(char)) {
context.offset--;
currentFamily += parseIdentifier(context);
families.push(currentFamily);
currentFamily = '';
}
}
}
return families;
}
/**
* Parse a CSS string.
*
* @param context Parsing input and offset
* @param quoteChar The quote character for the string (' or ")
*/
function parseString(context: IParseContext, quoteChar: '\'' | '"'): string {
let str = '';
let escaped = false;
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (escaped) {
if (/[0-9a-fA-F]/.test(char)) {
// Unicode escape
context.offset--;
str += parseUnicode(context);
} else if (char !== '\n') {
// Newlines are ignored if escaped. Other characters are used as is.
str += char;
}
escaped = false;
} else {
switch (char) {
// Terminated quote
case quoteChar:
return str;
// Begin escape
case '\\':
escaped = true;
break;
// Add character to string
default:
str += char;
}
}
}
throw new Error('Unterminated string');
}
/**
* Parse a CSS custom identifier.
*
* @param context Parsing input and offset
*/
function parseIdentifier(context: IParseContext): string {
let str = '';
let escaped = false;
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (escaped) {
if (/[0-9a-fA-F]/.test(char)) {
// Unicode escape
context.offset--;
str += parseUnicode(context);
} else {
// Everything else is used as is
str += char;
}
escaped = false;
} else {
switch (char) {
// Begin escape
case '\\':
escaped = true;
break;
// Terminate identifier
case ',':
return str;
default:
if (/\s/.test(char)) {
// Whitespace is collapsed into a single space within an identifier
if (!str.endsWith(' ')) {
str += ' ';
}
} else {
// Add other characters directly
str += char;
}
}
}
}
return str;
}
/**
* Parse a CSS unicode escape.
*
* @param context Parsing input and offset
*/
function parseUnicode(context: IParseContext): string {
let str = '';
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (/\s/.test(char)) {
// The first whitespace character after a unicode escape indicates the end
// of the escape and is swallowed.
return unicodeToString(str);
} else if (str.length >= 6 || !/[0-9a-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--;
return unicodeToString(str);
}
// Otherwise, just add it to the escape
str += char;
}
return unicodeToString(str);
}
/**
* Convert a unicode code point from a hex string to a utf8 string.
*
* @param codePoint Unicode code point represented as a hex string
*/
function unicodeToString(codePoint: string): string {
return String.fromCodePoint(parseInt(codePoint, 16));
}

Some files were not shown because too many files have changed in this diff Show More