Restructure common into layered folders (issue #5963)

Reorganize src/common into platform (base, encoding, data, buffer,
parser, input), integration (services, terminal), and public API layers.

- Move core utilities to common/base/
- Move TextDecoder to common/encoding/
- Move Types, CircularList, Color, TaskQueue, SortedList to common/services/
- Move CoreTerminal, InputHandler, WindowsMode to common/terminal/
- Define ICharset in common/data/Charsets.ts (re-exported from Types)
- Update imports across src/, addons/, and test/
- Add per-layer tsconfig.json files and REARCHITECTURE.md
- Root common/tsconfig.json remains the composite build entry

Co-authored-by: Daniel Imms <Tyriar@users.noreply.github.com>
This commit is contained in:
Cursor Agent
2026-05-30 16:12:18 +00:00
co-authored by Daniel Imms
parent 43e8365f0e
commit 1d125ac715
207 changed files with 2505 additions and 288 deletions
+3 -3
View File
@@ -3,12 +3,12 @@
* @license MIT
*/
import { Disposable } from 'common/Lifecycle';
import { IAttributeData, IBufferLine } from 'common/Types';
import { Disposable } from 'common/base/Lifecycle';
import { IAttributeData, IBufferLine } from 'common/services/Types';
import { BufferSet } from 'common/buffer/BufferSet';
import { IBuffer, IBufferSet } from 'common/buffer/Types';
import { IBufferService, ILogService, IOptionsService, type IBufferResizeEvent } from 'common/services/Services';
import { Emitter } from 'common/Event';
import { Emitter } from 'common/base/Event';
export const enum BufferServiceConstants {
MINIMUM_COLS = 2, // Less than 2 can mess with wide chars
+1 -1
View File
@@ -4,7 +4,7 @@
*/
import { ICharsetService } from 'common/services/Services';
import { ICharset } from 'common/Types';
import { ICharset } from 'common/services/Types';
export class CharsetService implements ICharsetService {
public serviceBrand: any;
+39
View File
@@ -0,0 +1,39 @@
import { ICircularList } from 'common/services/Types';
import { Disposable } from 'common/base/Lifecycle';
import { Emitter } from 'common/base/Event';
export interface IInsertEvent {
index: number;
amount: number;
}
export interface IDeleteEvent {
index: number;
amount: number;
}
export declare class CircularList<T> extends Disposable implements ICircularList<T> {
private _maxLength;
protected _array: (T | undefined)[];
private _startIndex;
private _length;
readonly onDeleteEmitter: Emitter<IDeleteEvent>;
readonly onDelete: import("common/base/Event").IEvent<IDeleteEvent>;
readonly onInsertEmitter: Emitter<IInsertEvent>;
readonly onInsert: import("common/base/Event").IEvent<IInsertEvent>;
readonly onTrimEmitter: Emitter<number>;
readonly onTrim: import("common/base/Event").IEvent<number>;
constructor(_maxLength: number);
get maxLength(): number;
set maxLength(newMaxLength: number);
get length(): number;
set length(newLength: number);
get(index: number): T | undefined;
set(index: number, value: T | undefined): void;
push(value: T): void;
recycle(): T;
get isFull(): boolean;
pop(): T | undefined;
splice(start: number, deleteCount: number, ...items: T[]): void;
trimStart(count: number): void;
shiftElements(start: number, count: number, offset: number): void;
private _getCyclicIndex;
}
//# sourceMappingURL=CircularList.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"CircularList.d.ts","sourceRoot":"","sources":["CircularList.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAE5C,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAMD,qBAAa,YAAY,CAAC,CAAC,CAAE,SAAQ,UAAW,YAAW,aAAa,CAAC,CAAC,CAAC;IAavE,OAAO,CAAC,UAAU;IAZpB,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,SAAS,CAAC,EAAE,CAAC;IACpC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,OAAO,CAAS;IAExB,SAAgB,eAAe,wBAA+C;IAC9E,SAAgB,QAAQ,mDAA8B;IACtD,SAAgB,eAAe,wBAA+C;IAC9E,SAAgB,QAAQ,mDAA8B;IACtD,SAAgB,aAAa,kBAAyC;IACtE,SAAgB,MAAM,6CAA4B;IAElD,YACU,UAAU,EAAE,MAAM,EAM3B;IAED,IAAW,SAAS,IAAI,MAAM,CAE7B;IAED,IAAW,SAAS,CAAC,YAAY,EAAE,MAAM,EAexC;IAED,IAAW,MAAM,IAAI,MAAM,CAE1B;IAED,IAAW,MAAM,CAAC,SAAS,EAAE,MAAM,EAOlC;IAUM,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAEvC;IAUM,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,SAAS,GAAG,IAAI,CAEpD;IAOM,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAQ1B;IAOM,OAAO,IAAI,CAAC,CAOlB;IAKD,IAAW,MAAM,IAAI,OAAO,CAE3B;IAMM,GAAG,IAAI,CAAC,GAAG,SAAS,CAE1B;IAWM,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,CAAC,EAAE,GAAG,IAAI,CA8BrE;IAMM,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAOpC;IAEM,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CA6BvE;IAQD,OAAO,CAAC,eAAe;CAGxB"}
+146
View File
@@ -0,0 +1,146 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CircularList = void 0;
const Lifecycle_1 = require("common/base/Lifecycle");
const Event_1 = require("common/base/Event");
class CircularList extends Lifecycle_1.Disposable {
constructor(_maxLength) {
super();
this._maxLength = _maxLength;
this.onDeleteEmitter = this._register(new Event_1.Emitter());
this.onDelete = this.onDeleteEmitter.event;
this.onInsertEmitter = this._register(new Event_1.Emitter());
this.onInsert = this.onInsertEmitter.event;
this.onTrimEmitter = this._register(new Event_1.Emitter());
this.onTrim = this.onTrimEmitter.event;
this._array = new Array(this._maxLength);
this._startIndex = 0;
this._length = 0;
}
get maxLength() {
return this._maxLength;
}
set maxLength(newMaxLength) {
if (this._maxLength === newMaxLength) {
return;
}
const newArray = new Array(newMaxLength);
for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {
newArray[i] = this._array[this._getCyclicIndex(i)];
}
this._array = newArray;
this._maxLength = newMaxLength;
this._startIndex = 0;
}
get length() {
return this._length;
}
set length(newLength) {
if (newLength > this._length) {
for (let i = this._length; i < newLength; i++) {
this._array[i] = undefined;
}
}
this._length = newLength;
}
get(index) {
return this._array[this._getCyclicIndex(index)];
}
set(index, value) {
this._array[this._getCyclicIndex(index)] = value;
}
push(value) {
this._array[this._getCyclicIndex(this._length)] = value;
if (this._length === this._maxLength) {
this._startIndex = ++this._startIndex % this._maxLength;
this.onTrimEmitter.fire(1);
}
else {
this._length++;
}
}
recycle() {
if (this._length !== this._maxLength) {
throw new Error('Can only recycle when the buffer is full');
}
this._startIndex = ++this._startIndex % this._maxLength;
this.onTrimEmitter.fire(1);
return this._array[this._getCyclicIndex(this._length - 1)];
}
get isFull() {
return this._length === this._maxLength;
}
pop() {
return this._array[this._getCyclicIndex(this._length-- - 1)];
}
splice(start, deleteCount, ...items) {
if (deleteCount) {
for (let i = start; i < this._length - deleteCount; i++) {
this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];
}
this._length -= deleteCount;
this.onDeleteEmitter.fire({ index: start, amount: deleteCount });
}
for (let i = this._length - 1; i >= start; i--) {
this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];
}
for (let i = 0; i < items.length; i++) {
this._array[this._getCyclicIndex(start + i)] = items[i];
}
if (items.length) {
this.onInsertEmitter.fire({ index: start, amount: items.length });
}
if (this._length + items.length > this._maxLength) {
const countToTrim = (this._length + items.length) - this._maxLength;
this._startIndex += countToTrim;
this._length = this._maxLength;
this.onTrimEmitter.fire(countToTrim);
}
else {
this._length += items.length;
}
}
trimStart(count) {
if (count > this._length) {
count = this._length;
}
this._startIndex += count;
this._length -= count;
this.onTrimEmitter.fire(count);
}
shiftElements(start, count, offset) {
if (count <= 0) {
return;
}
if (start < 0 || start >= this._length) {
throw new Error('start argument out of range');
}
if (start + offset < 0) {
throw new Error('Cannot shift elements in list beyond index 0');
}
if (offset > 0) {
for (let i = count - 1; i >= 0; i--) {
this.set(start + i + offset, this.get(start + i));
}
const expandListBy = (start + count + offset) - this._length;
if (expandListBy > 0) {
this._length += expandListBy;
while (this._length > this._maxLength) {
this._length--;
this._startIndex++;
this.onTrimEmitter.fire(1);
}
}
}
else {
for (let i = 0; i < count; i++) {
this.set(start + i + offset, this.get(start + i));
}
}
}
_getCyclicIndex(index) {
return (this._startIndex + index) % this._maxLength;
}
}
exports.CircularList = CircularList;
//# sourceMappingURL=CircularList.js.map
File diff suppressed because one or more lines are too long
+260
View File
@@ -0,0 +1,260 @@
/**
* Copyright (c) 2016 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import { CircularList } from 'common/services/CircularList';
describe('CircularList', () => {
describe('push', () => {
it('should push values onto the array', () => {
const list = new CircularList<string>(5);
list.push('1');
list.push('2');
list.push('3');
list.push('4');
list.push('5');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
assert.equal(list.get(2), '3');
assert.equal(list.get(3), '4');
assert.equal(list.get(4), '5');
});
it('should push old values from the start out of the array when max length is reached', () => {
const list = new CircularList<string>(2);
list.push('1');
list.push('2');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
list.push('3');
assert.equal(list.get(0), '2');
assert.equal(list.get(1), '3');
list.push('4');
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '4');
});
});
describe('maxLength', () => {
it('should increase the size of the list', () => {
const list = new CircularList<string>(2);
list.push('1');
list.push('2');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
list.maxLength = 4;
list.push('3');
list.push('4');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
assert.equal(list.get(2), '3');
assert.equal(list.get(3), '4');
list.push('wrapped');
assert.equal(list.get(0), '2');
assert.equal(list.get(1), '3');
assert.equal(list.get(2), '4');
assert.equal(list.get(3), 'wrapped');
});
it('should return the maximum length of the list', () => {
const list = new CircularList<string>(2);
assert.equal(list.maxLength, 2);
list.push('1');
list.push('2');
assert.equal(list.maxLength, 2);
list.push('3');
assert.equal(list.maxLength, 2);
list.maxLength = 4;
assert.equal(list.maxLength, 4);
});
});
describe('length', () => {
it('should return the current length of the list, capped at the maximum length', () => {
const list = new CircularList<string>(2);
assert.equal(list.length, 0);
list.push('1');
assert.equal(list.length, 1);
list.push('2');
assert.equal(list.length, 2);
list.push('3');
assert.equal(list.length, 2);
});
});
describe('splice', () => {
it('should delete items', () => {
const list = new CircularList<string>(2);
list.push('1');
list.push('2');
list.splice(0, 1);
assert.equal(list.length, 1);
assert.equal(list.get(0), '2');
list.push('3');
list.splice(1, 1);
assert.equal(list.length, 1);
assert.equal(list.get(0), '2');
});
it('should insert items', () => {
const list = new CircularList<string>(2);
list.push('1');
list.splice(0, 0, '2');
assert.equal(list.length, 2);
assert.equal(list.get(0), '2');
assert.equal(list.get(1), '1');
list.splice(1, 0, '3');
assert.equal(list.length, 2);
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '1');
});
it('should delete items then insert items', () => {
const list = new CircularList<string>(3);
list.push('1');
list.push('2');
list.splice(0, 1, '3', '4');
assert.equal(list.length, 3);
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '4');
assert.equal(list.get(2), '2');
});
it('should wrap the array correctly when more items are inserted than deleted', () => {
const list = new CircularList<string>(3);
list.push('1');
list.push('2');
list.splice(1, 0, '3', '4');
assert.equal(list.length, 3);
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '4');
assert.equal(list.get(2), '2');
});
});
describe('trimStart', () => {
it('should remove items from the beginning of the list', () => {
const list = new CircularList<string>(5);
list.push('1');
list.push('2');
list.push('3');
list.push('4');
list.push('5');
list.trimStart(1);
assert.equal(list.length, 4);
assert.deepEqual(list.get(0), '2');
assert.deepEqual(list.get(1), '3');
assert.deepEqual(list.get(2), '4');
assert.deepEqual(list.get(3), '5');
list.trimStart(2);
assert.equal(list.length, 2);
assert.deepEqual(list.get(0), '4');
assert.deepEqual(list.get(1), '5');
});
it('should remove all items if the requested trim amount is larger than the list\'s length', () => {
const list = new CircularList<string>(5);
list.push('1');
list.trimStart(2);
assert.equal(list.length, 0);
});
});
describe('shiftElements', () => {
it('should not mutate the list when count is 0', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(0, 0, 1);
assert.equal(list.length, 2);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 2);
});
it('should throw for invalid args', () => {
const list = new CircularList<number>(5);
list.push(1);
assert.throws(() => list.shiftElements(-1, 1, 1), 'start argument out of range');
assert.throws(() => list.shiftElements(1, 1, 1), 'start argument out of range');
assert.throws(() => list.shiftElements(0, 1, -1), 'Cannot shift elements in list beyond index 0');
});
it('should shift an element forward', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(0, 1, 1);
assert.equal(list.length, 2);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 1);
});
it('should shift elements forward', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.shiftElements(0, 2, 2);
assert.equal(list.length, 4);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 2);
assert.equal(list.get(2), 1);
assert.equal(list.get(3), 2);
});
it('should shift elements forward, expanding the list if needed', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(0, 2, 2);
assert.equal(list.length, 4);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 2);
assert.equal(list.get(2), 1);
assert.equal(list.get(3), 2);
});
it('should shift elements forward, wrapping the list if needed', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.push(5);
list.shiftElements(2, 2, 3);
assert.equal(list.length, 5);
assert.equal(list.get(0), 3);
assert.equal(list.get(1), 4);
assert.equal(list.get(2), 5);
assert.equal(list.get(3), 3);
assert.equal(list.get(4), 4);
});
it('should shift an element backwards', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(1, 1, -1);
assert.equal(list.length, 2);
assert.equal(list.get(0), 2);
assert.equal(list.get(1), 2);
});
it('should shift elements backwards', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.shiftElements(2, 2, -2);
assert.equal(list.length, 4);
assert.equal(list.get(0), 3);
assert.equal(list.get(1), 4);
assert.equal(list.get(2), 3);
assert.equal(list.get(3), 4);
});
});
});
+241
View File
@@ -0,0 +1,241 @@
/**
* Copyright (c) 2016 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { ICircularList } from 'common/services/Types';
import { Disposable } from 'common/base/Lifecycle';
import { Emitter } from 'common/base/Event';
export interface IInsertEvent {
index: number;
amount: number;
}
export interface IDeleteEvent {
index: number;
amount: number;
}
/**
* Represents a circular list; a list with a maximum size that wraps around when push is called,
* overriding values at the start of the list.
*/
export class CircularList<T> extends Disposable implements ICircularList<T> {
protected _array: (T | undefined)[];
private _startIndex: number;
private _length: number;
public readonly onDeleteEmitter = this._register(new Emitter<IDeleteEvent>());
public readonly onDelete = this.onDeleteEmitter.event;
public readonly onInsertEmitter = this._register(new Emitter<IInsertEvent>());
public readonly onInsert = this.onInsertEmitter.event;
public readonly onTrimEmitter = this._register(new Emitter<number>());
public readonly onTrim = this.onTrimEmitter.event;
constructor(
private _maxLength: number
) {
super();
this._array = new Array<T>(this._maxLength);
this._startIndex = 0;
this._length = 0;
}
public get maxLength(): number {
return this._maxLength;
}
public set maxLength(newMaxLength: number) {
// There was no change in maxLength, return early.
if (this._maxLength === newMaxLength) {
return;
}
// Reconstruct array, starting at index 0. Only transfer values from the
// indexes 0 to length.
const newArray = new Array<T | undefined>(newMaxLength);
for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {
newArray[i] = this._array[this._getCyclicIndex(i)];
}
this._array = newArray;
this._maxLength = newMaxLength;
this._startIndex = 0;
}
public get length(): number {
return this._length;
}
public set length(newLength: number) {
if (newLength > this._length) {
for (let i = this._length; i < newLength; i++) {
this._array[i] = undefined;
}
}
this._length = newLength;
}
/**
* Gets the value at an index.
*
* Note that for performance reasons there is no bounds checking here, the index reference is
* circular so this should always return a value and never throw.
* @param index The index of the value to get.
* @returns The value corresponding to the index.
*/
public get(index: number): T | undefined {
return this._array[this._getCyclicIndex(index)];
}
/**
* Sets the value at an index.
*
* Note that for performance reasons there is no bounds checking here, the index reference is
* circular so this should always return a value and never throw.
* @param index The index to set.
* @param value The value to set.
*/
public set(index: number, value: T | undefined): void {
this._array[this._getCyclicIndex(index)] = value;
}
/**
* Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0
* if the maximum length is reached.
* @param value The value to push onto the list.
*/
public push(value: T): void {
this._array[this._getCyclicIndex(this._length)] = value;
if (this._length === this._maxLength) {
this._startIndex = ++this._startIndex % this._maxLength;
this.onTrimEmitter.fire(1);
} else {
this._length++;
}
}
/**
* Advance ringbuffer index and return current element for recycling.
* Note: The buffer must be full for this method to work.
* @throws When the buffer is not full.
*/
public recycle(): T {
if (this._length !== this._maxLength) {
throw new Error('Can only recycle when the buffer is full');
}
this._startIndex = ++this._startIndex % this._maxLength;
this.onTrimEmitter.fire(1);
return this._array[this._getCyclicIndex(this._length - 1)]!;
}
/**
* Ringbuffer is at max length.
*/
public get isFull(): boolean {
return this._length === this._maxLength;
}
/**
* Removes and returns the last value on the list.
* @returns The popped value.
*/
public pop(): T | undefined {
return this._array[this._getCyclicIndex(this._length-- - 1)];
}
/**
* Deletes and/or inserts items at a particular index (in that order). Unlike
* Array.prototype.splice, this operation does not return the deleted items as a new array in
* order to save creating a new array. Note that this operation may shift all values in the list
* in the worst case.
* @param start The index to delete and/or insert.
* @param deleteCount The number of elements to delete.
* @param items The items to insert.
*/
public splice(start: number, deleteCount: number, ...items: T[]): void {
// Delete items
if (deleteCount) {
for (let i = start; i < this._length - deleteCount; i++) {
this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];
}
this._length -= deleteCount;
this.onDeleteEmitter.fire({ index: start, amount: deleteCount });
}
// Add items
for (let i = this._length - 1; i >= start; i--) {
this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];
}
for (let i = 0; i < items.length; i++) {
this._array[this._getCyclicIndex(start + i)] = items[i];
}
if (items.length) {
this.onInsertEmitter.fire({ index: start, amount: items.length });
}
// Adjust length as needed
if (this._length + items.length > this._maxLength) {
const countToTrim = (this._length + items.length) - this._maxLength;
this._startIndex += countToTrim;
this._length = this._maxLength;
this.onTrimEmitter.fire(countToTrim);
} else {
this._length += items.length;
}
}
/**
* Trims a number of items from the start of the list.
* @param count The number of items to remove.
*/
public trimStart(count: number): void {
if (count > this._length) {
count = this._length;
}
this._startIndex += count;
this._length -= count;
this.onTrimEmitter.fire(count);
}
public shiftElements(start: number, count: number, offset: number): void {
if (count <= 0) {
return;
}
if (start < 0 || start >= this._length) {
throw new Error('start argument out of range');
}
if (start + offset < 0) {
throw new Error('Cannot shift elements in list beyond index 0');
}
if (offset > 0) {
for (let i = count - 1; i >= 0; i--) {
this.set(start + i + offset, this.get(start + i));
}
const expandListBy = (start + count + offset) - this._length;
if (expandListBy > 0) {
this._length += expandListBy;
while (this._length > this._maxLength) {
this._length--;
this._startIndex++;
this.onTrimEmitter.fire(1);
}
}
} else {
for (let i = 0; i < count; i++) {
this.set(start + i + offset, this.get(start + i));
}
}
}
/**
* Gets the cyclic index for the specified regular index. The cyclic index can then be used on the
* backing array to get the element associated with the regular index.
* @param index The regular index.
* @returns The cyclic index.
*/
private _getCyclicIndex(index: number): number {
return (this._startIndex + index) % this._maxLength;
}
}
+467
View File
@@ -0,0 +1,467 @@
/**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import { channels, color, css, rgb, rgba, toPaddedHex, contrastRatio } from 'common/services/Color';
describe('Color', () => {
describe('channels', () => {
describe('toCss', () => {
it('should convert an rgb array to css hex string', () => {
assert.equal(channels.toCss(0x00, 0x00, 0x00), '#000000');
assert.equal(channels.toCss(0x10, 0x10, 0x10), '#101010');
assert.equal(channels.toCss(0x20, 0x20, 0x20), '#202020');
assert.equal(channels.toCss(0x30, 0x30, 0x30), '#303030');
assert.equal(channels.toCss(0x40, 0x40, 0x40), '#404040');
assert.equal(channels.toCss(0x50, 0x50, 0x50), '#505050');
assert.equal(channels.toCss(0x60, 0x60, 0x60), '#606060');
assert.equal(channels.toCss(0x70, 0x70, 0x70), '#707070');
assert.equal(channels.toCss(0x80, 0x80, 0x80), '#808080');
assert.equal(channels.toCss(0x90, 0x90, 0x90), '#909090');
assert.equal(channels.toCss(0xa0, 0xa0, 0xa0), '#a0a0a0');
assert.equal(channels.toCss(0xb0, 0xb0, 0xb0), '#b0b0b0');
assert.equal(channels.toCss(0xc0, 0xc0, 0xc0), '#c0c0c0');
assert.equal(channels.toCss(0xd0, 0xd0, 0xd0), '#d0d0d0');
assert.equal(channels.toCss(0xe0, 0xe0, 0xe0), '#e0e0e0');
assert.equal(channels.toCss(0xf0, 0xf0, 0xf0), '#f0f0f0');
assert.equal(channels.toCss(0xff, 0xff, 0xff), '#ffffff');
});
it('should convert an rgba array to css hex string', () => {
assert.equal(channels.toCss(0x00, 0x00, 0x00, 0x00), '#00000000');
assert.equal(channels.toCss(0x10, 0x10, 0x10, 0x10), '#10101010');
assert.equal(channels.toCss(0x20, 0x20, 0x20, 0x20), '#20202020');
assert.equal(channels.toCss(0x30, 0x30, 0x30, 0x30), '#30303030');
assert.equal(channels.toCss(0x40, 0x40, 0x40, 0x40), '#40404040');
assert.equal(channels.toCss(0x50, 0x50, 0x50, 0x50), '#50505050');
assert.equal(channels.toCss(0x60, 0x60, 0x60, 0x60), '#60606060');
assert.equal(channels.toCss(0x70, 0x70, 0x70, 0x70), '#70707070');
assert.equal(channels.toCss(0x80, 0x80, 0x80, 0x80), '#80808080');
assert.equal(channels.toCss(0x90, 0x90, 0x90, 0x90), '#90909090');
assert.equal(channels.toCss(0xa0, 0xa0, 0xa0, 0xa0), '#a0a0a0a0');
assert.equal(channels.toCss(0xb0, 0xb0, 0xb0, 0xb0), '#b0b0b0b0');
assert.equal(channels.toCss(0xc0, 0xc0, 0xc0, 0xc0), '#c0c0c0c0');
assert.equal(channels.toCss(0xd0, 0xd0, 0xd0, 0xd0), '#d0d0d0d0');
assert.equal(channels.toCss(0xe0, 0xe0, 0xe0, 0xe0), '#e0e0e0e0');
assert.equal(channels.toCss(0xf0, 0xf0, 0xf0, 0xf0), '#f0f0f0f0');
assert.equal(channels.toCss(0xff, 0xff, 0xff, 0xff), '#ffffffff');
});
});
describe('toRgba', () => {
it('should convert an rgb array to an rgba number', () => {
assert.equal(channels.toRgba(0x00, 0x00, 0x00), 0x000000FF);
assert.equal(channels.toRgba(0x10, 0x10, 0x10), 0x101010FF);
assert.equal(channels.toRgba(0x20, 0x20, 0x20), 0x202020FF);
assert.equal(channels.toRgba(0x30, 0x30, 0x30), 0x303030FF);
assert.equal(channels.toRgba(0x40, 0x40, 0x40), 0x404040FF);
assert.equal(channels.toRgba(0x50, 0x50, 0x50), 0x505050FF);
assert.equal(channels.toRgba(0x60, 0x60, 0x60), 0x606060FF);
assert.equal(channels.toRgba(0x70, 0x70, 0x70), 0x707070FF);
assert.equal(channels.toRgba(0x80, 0x80, 0x80), 0x808080FF);
assert.equal(channels.toRgba(0x90, 0x90, 0x90), 0x909090FF);
assert.equal(channels.toRgba(0xa0, 0xa0, 0xa0), 0xa0a0a0FF);
assert.equal(channels.toRgba(0xb0, 0xb0, 0xb0), 0xb0b0b0FF);
assert.equal(channels.toRgba(0xc0, 0xc0, 0xc0), 0xc0c0c0FF);
assert.equal(channels.toRgba(0xd0, 0xd0, 0xd0), 0xd0d0d0FF);
assert.equal(channels.toRgba(0xe0, 0xe0, 0xe0), 0xe0e0e0FF);
assert.equal(channels.toRgba(0xf0, 0xf0, 0xf0), 0xf0f0f0FF);
assert.equal(channels.toRgba(0xff, 0xff, 0xff), 0xffffffFF);
});
it('should convert an rgba array to an rgba number', () => {
assert.equal(channels.toRgba(0x00, 0x00, 0x00, 0x00), 0x00000000);
assert.equal(channels.toRgba(0x10, 0x10, 0x10, 0x10), 0x10101010);
assert.equal(channels.toRgba(0x20, 0x20, 0x20, 0x20), 0x20202020);
assert.equal(channels.toRgba(0x30, 0x30, 0x30, 0x30), 0x30303030);
assert.equal(channels.toRgba(0x40, 0x40, 0x40, 0x40), 0x40404040);
assert.equal(channels.toRgba(0x50, 0x50, 0x50, 0x50), 0x50505050);
assert.equal(channels.toRgba(0x60, 0x60, 0x60, 0x60), 0x60606060);
assert.equal(channels.toRgba(0x70, 0x70, 0x70, 0x70), 0x70707070);
assert.equal(channels.toRgba(0x80, 0x80, 0x80, 0x80), 0x80808080);
assert.equal(channels.toRgba(0x90, 0x90, 0x90, 0x90), 0x90909090);
assert.equal(channels.toRgba(0xa0, 0xa0, 0xa0, 0xa0), 0xa0a0a0a0);
assert.equal(channels.toRgba(0xb0, 0xb0, 0xb0, 0xb0), 0xb0b0b0b0);
assert.equal(channels.toRgba(0xc0, 0xc0, 0xc0, 0xc0), 0xc0c0c0c0);
assert.equal(channels.toRgba(0xd0, 0xd0, 0xd0, 0xd0), 0xd0d0d0d0);
assert.equal(channels.toRgba(0xe0, 0xe0, 0xe0, 0xe0), 0xe0e0e0e0);
assert.equal(channels.toRgba(0xf0, 0xf0, 0xf0, 0xf0), 0xf0f0f0f0);
assert.equal(channels.toRgba(0xff, 0xff, 0xff, 0xff), 0xffffffff);
});
});
describe('toColor', () => {
it('should convert an rgb array to an IColor', () => {
assert.deepStrictEqual(channels.toColor(0x00, 0x00, 0x00), { css: '#000000', rgba: 0x000000FF });
assert.deepStrictEqual(channels.toColor(0x10, 0x10, 0x10), { css: '#101010', rgba: 0x101010FF });
assert.deepStrictEqual(channels.toColor(0x20, 0x20, 0x20), { css: '#202020', rgba: 0x202020FF });
assert.deepStrictEqual(channels.toColor(0x30, 0x30, 0x30), { css: '#303030', rgba: 0x303030FF });
assert.deepStrictEqual(channels.toColor(0x40, 0x40, 0x40), { css: '#404040', rgba: 0x404040FF });
assert.deepStrictEqual(channels.toColor(0x50, 0x50, 0x50), { css: '#505050', rgba: 0x505050FF });
assert.deepStrictEqual(channels.toColor(0x60, 0x60, 0x60), { css: '#606060', rgba: 0x606060FF });
assert.deepStrictEqual(channels.toColor(0x70, 0x70, 0x70), { css: '#707070', rgba: 0x707070FF });
assert.deepStrictEqual(channels.toColor(0x80, 0x80, 0x80), { css: '#808080', rgba: 0x808080FF });
assert.deepStrictEqual(channels.toColor(0x90, 0x90, 0x90), { css: '#909090', rgba: 0x909090FF });
assert.deepStrictEqual(channels.toColor(0xa0, 0xa0, 0xa0), { css: '#a0a0a0', rgba: 0xa0a0a0FF });
assert.deepStrictEqual(channels.toColor(0xb0, 0xb0, 0xb0), { css: '#b0b0b0', rgba: 0xb0b0b0FF });
assert.deepStrictEqual(channels.toColor(0xc0, 0xc0, 0xc0), { css: '#c0c0c0', rgba: 0xc0c0c0FF });
assert.deepStrictEqual(channels.toColor(0xd0, 0xd0, 0xd0), { css: '#d0d0d0', rgba: 0xd0d0d0FF });
assert.deepStrictEqual(channels.toColor(0xe0, 0xe0, 0xe0), { css: '#e0e0e0', rgba: 0xe0e0e0FF });
assert.deepStrictEqual(channels.toColor(0xf0, 0xf0, 0xf0), { css: '#f0f0f0', rgba: 0xf0f0f0FF });
assert.deepStrictEqual(channels.toColor(0xff, 0xff, 0xff), { css: '#ffffff', rgba: 0xffffffFF });
});
it('should convert an rgba array to an IColor', () => {
assert.deepStrictEqual(channels.toColor(0x00, 0x00, 0x00, 0x00), { css: '#00000000', rgba: 0x00000000 });
assert.deepStrictEqual(channels.toColor(0x10, 0x10, 0x10, 0x10), { css: '#10101010', rgba: 0x10101010 });
assert.deepStrictEqual(channels.toColor(0x20, 0x20, 0x20, 0x20), { css: '#20202020', rgba: 0x20202020 });
assert.deepStrictEqual(channels.toColor(0x30, 0x30, 0x30, 0x30), { css: '#30303030', rgba: 0x30303030 });
assert.deepStrictEqual(channels.toColor(0x40, 0x40, 0x40, 0x40), { css: '#40404040', rgba: 0x40404040 });
assert.deepStrictEqual(channels.toColor(0x50, 0x50, 0x50, 0x50), { css: '#50505050', rgba: 0x50505050 });
assert.deepStrictEqual(channels.toColor(0x60, 0x60, 0x60, 0x60), { css: '#60606060', rgba: 0x60606060 });
assert.deepStrictEqual(channels.toColor(0x70, 0x70, 0x70, 0x70), { css: '#70707070', rgba: 0x70707070 });
assert.deepStrictEqual(channels.toColor(0x80, 0x80, 0x80, 0x80), { css: '#80808080', rgba: 0x80808080 });
assert.deepStrictEqual(channels.toColor(0x90, 0x90, 0x90, 0x90), { css: '#90909090', rgba: 0x90909090 });
assert.deepStrictEqual(channels.toColor(0xa0, 0xa0, 0xa0, 0xa0), { css: '#a0a0a0a0', rgba: 0xa0a0a0a0 });
assert.deepStrictEqual(channels.toColor(0xb0, 0xb0, 0xb0, 0xb0), { css: '#b0b0b0b0', rgba: 0xb0b0b0b0 });
assert.deepStrictEqual(channels.toColor(0xc0, 0xc0, 0xc0, 0xc0), { css: '#c0c0c0c0', rgba: 0xc0c0c0c0 });
assert.deepStrictEqual(channels.toColor(0xd0, 0xd0, 0xd0, 0xd0), { css: '#d0d0d0d0', rgba: 0xd0d0d0d0 });
assert.deepStrictEqual(channels.toColor(0xe0, 0xe0, 0xe0, 0xe0), { css: '#e0e0e0e0', rgba: 0xe0e0e0e0 });
assert.deepStrictEqual(channels.toColor(0xf0, 0xf0, 0xf0, 0xf0), { css: '#f0f0f0f0', rgba: 0xf0f0f0f0 });
assert.deepStrictEqual(channels.toColor(0xff, 0xff, 0xff, 0xff), { css: '#ffffffff', rgba: 0xffffffff });
});
});
});
describe('color', () => {
describe('blend', () => {
it('should blend colors based on the alpha channel', () => {
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF00', rgba: 0xFFFFFF00 }), { css: '#000000', rgba: 0x000000FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF10', rgba: 0xFFFFFF10 }), { css: '#101010', rgba: 0x101010FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF20', rgba: 0xFFFFFF20 }), { css: '#202020', rgba: 0x202020FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF30', rgba: 0xFFFFFF30 }), { css: '#303030', rgba: 0x303030FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF40', rgba: 0xFFFFFF40 }), { css: '#404040', rgba: 0x404040FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF50', rgba: 0xFFFFFF50 }), { css: '#505050', rgba: 0x505050FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF60', rgba: 0xFFFFFF60 }), { css: '#606060', rgba: 0x606060FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF70', rgba: 0xFFFFFF70 }), { css: '#707070', rgba: 0x707070FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF80', rgba: 0xFFFFFF80 }), { css: '#808080', rgba: 0x808080FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFF90', rgba: 0xFFFFFF90 }), { css: '#909090', rgba: 0x909090FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFFA0', rgba: 0xFFFFFFA0 }), { css: '#a0a0a0', rgba: 0xA0A0A0FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFFB0', rgba: 0xFFFFFFB0 }), { css: '#b0b0b0', rgba: 0xB0B0B0FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFFC0', rgba: 0xFFFFFFC0 }), { css: '#c0c0c0', rgba: 0xC0C0C0FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFFD0', rgba: 0xFFFFFFD0 }), { css: '#d0d0d0', rgba: 0xD0D0D0FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFFE0', rgba: 0xFFFFFFE0 }), { css: '#e0e0e0', rgba: 0xE0E0E0FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFFF0', rgba: 0xFFFFFFF0 }), { css: '#f0f0f0', rgba: 0xF0F0F0FF });
assert.deepEqual(color.blend({ css: '#000000', rgba: 0x000000FF }, { css: '#FFFFFFFF', rgba: 0xFFFFFFFF }), { css: '#FFFFFFFF', rgba: 0xFFFFFFFF });
});
});
describe('opaque', () => {
it('should make the color opaque', () => {
assert.deepEqual(color.opaque({ css: '#00000000', rgba: 0x00000000 }), { css: '#000000', rgba: 0x000000FF });
assert.deepEqual(color.opaque({ css: '#10101010', rgba: 0x10101010 }), { css: '#101010', rgba: 0x101010FF });
assert.deepEqual(color.opaque({ css: '#20202020', rgba: 0x20202020 }), { css: '#202020', rgba: 0x202020FF });
assert.deepEqual(color.opaque({ css: '#30303030', rgba: 0x30303030 }), { css: '#303030', rgba: 0x303030FF });
assert.deepEqual(color.opaque({ css: '#40404040', rgba: 0x40404040 }), { css: '#404040', rgba: 0x404040FF });
assert.deepEqual(color.opaque({ css: '#50505050', rgba: 0x50505050 }), { css: '#505050', rgba: 0x505050FF });
assert.deepEqual(color.opaque({ css: '#60606060', rgba: 0x60606060 }), { css: '#606060', rgba: 0x606060FF });
assert.deepEqual(color.opaque({ css: '#70707070', rgba: 0x70707070 }), { css: '#707070', rgba: 0x707070FF });
assert.deepEqual(color.opaque({ css: '#80808080', rgba: 0x80808080 }), { css: '#808080', rgba: 0x808080FF });
assert.deepEqual(color.opaque({ css: '#90909090', rgba: 0x90909090 }), { css: '#909090', rgba: 0x909090FF });
assert.deepEqual(color.opaque({ css: '#a0a0a0a0', rgba: 0xa0a0a0a0 }), { css: '#a0a0a0', rgba: 0xa0a0a0FF });
assert.deepEqual(color.opaque({ css: '#b0b0b0b0', rgba: 0xb0b0b0b0 }), { css: '#b0b0b0', rgba: 0xb0b0b0FF });
assert.deepEqual(color.opaque({ css: '#c0c0c0c0', rgba: 0xc0c0c0c0 }), { css: '#c0c0c0', rgba: 0xc0c0c0FF });
assert.deepEqual(color.opaque({ css: '#d0d0d0d0', rgba: 0xd0d0d0d0 }), { css: '#d0d0d0', rgba: 0xd0d0d0FF });
assert.deepEqual(color.opaque({ css: '#e0e0e0e0', rgba: 0xe0e0e0e0 }), { css: '#e0e0e0', rgba: 0xe0e0e0FF });
assert.deepEqual(color.opaque({ css: '#f0f0f0f0', rgba: 0xf0f0f0f0 }), { css: '#f0f0f0', rgba: 0xf0f0f0FF });
assert.deepEqual(color.opaque({ css: '#ffffffff', rgba: 0xffffffff }), { css: '#ffffff', rgba: 0xffffffFF });
});
});
describe('isOpaque', () => {
it('should return true for opaque colors', () => {
assert.ok(color.isOpaque(css.toColor('#000000')));
assert.ok(color.isOpaque(css.toColor('#000000ff')));
assert.ok(color.isOpaque(css.toColor('#808080')));
assert.ok(color.isOpaque(css.toColor('#808080ff')));
assert.ok(color.isOpaque(css.toColor('#ffffff')));
assert.ok(color.isOpaque(css.toColor('#ffffffff')));
});
it('should return false for transparent colors', () => {
assert.ok(!color.isOpaque(css.toColor('#00000000')));
assert.ok(!color.isOpaque(css.toColor('#00000080')));
assert.ok(!color.isOpaque(css.toColor('#000000fe')));
assert.ok(!color.isOpaque(css.toColor('#80808000')));
assert.ok(!color.isOpaque(css.toColor('#80808080')));
assert.ok(!color.isOpaque(css.toColor('#808080fe')));
assert.ok(!color.isOpaque(css.toColor('#ffffff00')));
assert.ok(!color.isOpaque(css.toColor('#ffffff80')));
assert.ok(!color.isOpaque(css.toColor('#fffffffe')));
});
});
describe('opacity', () => {
it('should make the color transparent', () => {
assert.deepEqual(color.opacity(css.toColor('#000000'), 0), { css: '#00000000', rgba: 0x00000000 });
assert.deepEqual(color.opacity(css.toColor('#000000'), 0.25), { css: '#00000040', rgba: 0x00000040 });
assert.deepEqual(color.opacity(css.toColor('#000000'), 0.5), { css: '#00000080', rgba: 0x00000080 });
assert.deepEqual(color.opacity(css.toColor('#000000'), 0.75), { css: '#000000bf', rgba: 0x000000bf });
assert.deepEqual(color.opacity(css.toColor('#000000'), 1), { css: '#000000ff', rgba: 0x000000ff });
});
});
});
describe('css', () => {
describe('toColor', () => {
it('should convert the #rgb format to an IColor', () => {
assert.deepEqual(css.toColor('#000'), { css: '#000000', rgba: 0x000000FF });
assert.deepEqual(css.toColor('#111'), { css: '#111111', rgba: 0x111111FF });
assert.deepEqual(css.toColor('#222'), { css: '#222222', rgba: 0x222222FF });
assert.deepEqual(css.toColor('#333'), { css: '#333333', rgba: 0x333333FF });
assert.deepEqual(css.toColor('#444'), { css: '#444444', rgba: 0x444444FF });
assert.deepEqual(css.toColor('#555'), { css: '#555555', rgba: 0x555555FF });
assert.deepEqual(css.toColor('#666'), { css: '#666666', rgba: 0x666666FF });
assert.deepEqual(css.toColor('#777'), { css: '#777777', rgba: 0x777777FF });
assert.deepEqual(css.toColor('#888'), { css: '#888888', rgba: 0x888888FF });
assert.deepEqual(css.toColor('#999'), { css: '#999999', rgba: 0x999999FF });
assert.deepEqual(css.toColor('#aaa'), { css: '#aaaaaa', rgba: 0xaaaaaaFF });
assert.deepEqual(css.toColor('#bbb'), { css: '#bbbbbb', rgba: 0xbbbbbbFF });
assert.deepEqual(css.toColor('#ccc'), { css: '#cccccc', rgba: 0xccccccFF });
assert.deepEqual(css.toColor('#ddd'), { css: '#dddddd', rgba: 0xddddddFF });
assert.deepEqual(css.toColor('#eee'), { css: '#eeeeee', rgba: 0xeeeeeeFF });
assert.deepEqual(css.toColor('#fff'), { css: '#ffffff', rgba: 0xffffffFF });
assert.deepEqual(css.toColor('#fff'), { css: '#ffffff', rgba: 0xffffffFF });
});
it('should convert the #rgb format to an IColor', () => {
assert.deepEqual(css.toColor('#0000'), { css: '#00000000', rgba: 0x00000000 });
assert.deepEqual(css.toColor('#1111'), { css: '#11111111', rgba: 0x11111111 });
assert.deepEqual(css.toColor('#2222'), { css: '#22222222', rgba: 0x22222222 });
assert.deepEqual(css.toColor('#3333'), { css: '#33333333', rgba: 0x33333333 });
assert.deepEqual(css.toColor('#4444'), { css: '#44444444', rgba: 0x44444444 });
assert.deepEqual(css.toColor('#5555'), { css: '#55555555', rgba: 0x55555555 });
assert.deepEqual(css.toColor('#6666'), { css: '#66666666', rgba: 0x66666666 });
assert.deepEqual(css.toColor('#7777'), { css: '#77777777', rgba: 0x77777777 });
assert.deepEqual(css.toColor('#8888'), { css: '#88888888', rgba: 0x88888888 });
assert.deepEqual(css.toColor('#9999'), { css: '#99999999', rgba: 0x99999999 });
assert.deepEqual(css.toColor('#aaaa'), { css: '#aaaaaaaa', rgba: 0xaaaaaaaa });
assert.deepEqual(css.toColor('#bbbb'), { css: '#bbbbbbbb', rgba: 0xbbbbbbbb });
assert.deepEqual(css.toColor('#cccc'), { css: '#cccccccc', rgba: 0xcccccccc });
assert.deepEqual(css.toColor('#dddd'), { css: '#dddddddd', rgba: 0xdddddddd });
assert.deepEqual(css.toColor('#eeee'), { css: '#eeeeeeee', rgba: 0xeeeeeeee });
assert.deepEqual(css.toColor('#ffff'), { css: '#ffffffff', rgba: 0xffffffff });
assert.deepEqual(css.toColor('#ffff'), { css: '#ffffffff', rgba: 0xffffffff });
});
it('should convert the #rrggbb format to an IColor', () => {
assert.deepEqual(css.toColor('#000000'), { css: '#000000', rgba: 0x000000FF });
assert.deepEqual(css.toColor('#101010'), { css: '#101010', rgba: 0x101010FF });
assert.deepEqual(css.toColor('#202020'), { css: '#202020', rgba: 0x202020FF });
assert.deepEqual(css.toColor('#303030'), { css: '#303030', rgba: 0x303030FF });
assert.deepEqual(css.toColor('#404040'), { css: '#404040', rgba: 0x404040FF });
assert.deepEqual(css.toColor('#505050'), { css: '#505050', rgba: 0x505050FF });
assert.deepEqual(css.toColor('#606060'), { css: '#606060', rgba: 0x606060FF });
assert.deepEqual(css.toColor('#707070'), { css: '#707070', rgba: 0x707070FF });
assert.deepEqual(css.toColor('#808080'), { css: '#808080', rgba: 0x808080FF });
assert.deepEqual(css.toColor('#909090'), { css: '#909090', rgba: 0x909090FF });
assert.deepEqual(css.toColor('#a0a0a0'), { css: '#a0a0a0', rgba: 0xa0a0a0FF });
assert.deepEqual(css.toColor('#b0b0b0'), { css: '#b0b0b0', rgba: 0xb0b0b0FF });
assert.deepEqual(css.toColor('#c0c0c0'), { css: '#c0c0c0', rgba: 0xc0c0c0FF });
assert.deepEqual(css.toColor('#d0d0d0'), { css: '#d0d0d0', rgba: 0xd0d0d0FF });
assert.deepEqual(css.toColor('#e0e0e0'), { css: '#e0e0e0', rgba: 0xe0e0e0FF });
assert.deepEqual(css.toColor('#f0f0f0'), { css: '#f0f0f0', rgba: 0xf0f0f0FF });
assert.deepEqual(css.toColor('#ffffff'), { css: '#ffffff', rgba: 0xffffffFF });
});
it('should convert the #rrggbbaa format to an IColor', () => {
assert.deepEqual(css.toColor('#00000000'), { css: '#00000000', rgba: 0x00000000 });
assert.deepEqual(css.toColor('#10101010'), { css: '#10101010', rgba: 0x10101010 });
assert.deepEqual(css.toColor('#20202020'), { css: '#20202020', rgba: 0x20202020 });
assert.deepEqual(css.toColor('#30303030'), { css: '#30303030', rgba: 0x30303030 });
assert.deepEqual(css.toColor('#40404040'), { css: '#40404040', rgba: 0x40404040 });
assert.deepEqual(css.toColor('#50505050'), { css: '#50505050', rgba: 0x50505050 });
assert.deepEqual(css.toColor('#60606060'), { css: '#60606060', rgba: 0x60606060 });
assert.deepEqual(css.toColor('#70707070'), { css: '#70707070', rgba: 0x70707070 });
assert.deepEqual(css.toColor('#80808080'), { css: '#80808080', rgba: 0x80808080 });
assert.deepEqual(css.toColor('#90909090'), { css: '#90909090', rgba: 0x90909090 });
assert.deepEqual(css.toColor('#a0a0a0a0'), { css: '#a0a0a0a0', rgba: 0xa0a0a0a0 });
assert.deepEqual(css.toColor('#b0b0b0b0'), { css: '#b0b0b0b0', rgba: 0xb0b0b0b0 });
assert.deepEqual(css.toColor('#c0c0c0c0'), { css: '#c0c0c0c0', rgba: 0xc0c0c0c0 });
assert.deepEqual(css.toColor('#d0d0d0d0'), { css: '#d0d0d0d0', rgba: 0xd0d0d0d0 });
assert.deepEqual(css.toColor('#e0e0e0e0'), { css: '#e0e0e0e0', rgba: 0xe0e0e0e0 });
assert.deepEqual(css.toColor('#f0f0f0f0'), { css: '#f0f0f0f0', rgba: 0xf0f0f0f0 });
assert.deepEqual(css.toColor('#ffffffff'), { css: '#ffffffff', rgba: 0xffffffff });
});
it('should convert the rgb() format to an IColor', () => {
assert.deepEqual(css.toColor('rgb(0, 0, 0)'), { css: '#000000ff', rgba: 0x000000ff });
assert.deepEqual(css.toColor('rgb(80, 0, 0)'), { css: '#500000ff', rgba: 0x500000ff });
assert.deepEqual(css.toColor('rgb(0, 80, 0)'), { css: '#005000ff', rgba: 0x005000ff });
assert.deepEqual(css.toColor('rgb(0, 0, 80)'), { css: '#000050ff', rgba: 0x000050ff });
assert.deepEqual(css.toColor('rgb(255, 255, 255)'), { css: '#ffffffff', rgba: 0xffffffff });
});
it('should convert the rgba() format to an IColor', () => {
assert.deepEqual(css.toColor('rgba(0, 0, 0, 0)'), { css: '#00000000', rgba: 0x00000000 });
assert.deepEqual(css.toColor('rgba(80, 0, 0, 0.5)'), { css: '#50000080', rgba: 0x50000080 });
assert.deepEqual(css.toColor('rgba(0, 80, 0, 0.5)'), { css: '#00500080', rgba: 0x00500080 });
assert.deepEqual(css.toColor('rgba(0, 0, 80, 0.5)'), { css: '#00005080', rgba: 0x00005080 });
assert.deepEqual(css.toColor('rgba(255, 255, 255, 1)'), { css: '#ffffffff', rgba: 0xffffffff });
});
it('should convert "transparent" to an IColor', () => {
assert.deepEqual(css.toColor('transparent'), { css: 'transparent', rgba: 0x00000000 });
});
});
});
describe('rgb', () => {
describe('relativeLuminance', () => {
it('should calculate the relative luminance of the color', () => {
assert.equal(rgb.relativeLuminance(0x000000), 0);
assert.equal(rgb.relativeLuminance(0x101010).toFixed(4), '0.0052');
assert.equal(rgb.relativeLuminance(0x202020).toFixed(4), '0.0144');
assert.equal(rgb.relativeLuminance(0x303030).toFixed(4), '0.0296');
assert.equal(rgb.relativeLuminance(0x404040).toFixed(4), '0.0513');
assert.equal(rgb.relativeLuminance(0x505050).toFixed(4), '0.0802');
assert.equal(rgb.relativeLuminance(0x606060).toFixed(4), '0.1170');
assert.equal(rgb.relativeLuminance(0x707070).toFixed(4), '0.1620');
assert.equal(rgb.relativeLuminance(0x808080).toFixed(4), '0.2159');
assert.equal(rgb.relativeLuminance(0x909090).toFixed(4), '0.2789');
assert.equal(rgb.relativeLuminance(0xA0A0A0).toFixed(4), '0.3515');
assert.equal(rgb.relativeLuminance(0xB0B0B0).toFixed(4), '0.4342');
assert.equal(rgb.relativeLuminance(0xC0C0C0).toFixed(4), '0.5271');
assert.equal(rgb.relativeLuminance(0xD0D0D0).toFixed(4), '0.6308');
assert.equal(rgb.relativeLuminance(0xE0E0E0).toFixed(4), '0.7454');
assert.equal(rgb.relativeLuminance(0xF0F0F0).toFixed(4), '0.8714');
assert.equal(rgb.relativeLuminance(0xFFFFFF), 1);
});
});
});
describe('rgba', () => {
describe('blend', () => {
it('should blend colors based on the alpha channel', () => {
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF00), 0x000000FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF10), 0x101010FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF20), 0x202020FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF30), 0x303030FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF40), 0x404040FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF50), 0x505050FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF60), 0x606060FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF70), 0x707070FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF80), 0x808080FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFF90), 0x909090FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFFA0), 0xA0A0A0FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFFB0), 0xB0B0B0FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFFC0), 0xC0C0C0FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFFD0), 0xD0D0D0FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFFE0), 0xE0E0E0FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFFF0), 0xF0F0F0FF);
assert.deepEqual(rgba.blend(0x000000FF, 0xFFFFFFFF), 0xFFFFFFFF);
});
});
describe('ensureContrastRatio', () => {
it('should return undefined if the color already meets the contrast ratio (black bg)', () => {
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 1), undefined);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 2), undefined);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 3), undefined);
});
it('should return a color that meets the contrast ratio (black bg)', () => {
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 4), 0x707070ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 5), 0x7f7f7fff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 6), 0x8c8c8cff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 7), 0x989898ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 8), 0xa3a3a3ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 9), 0xadadadff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 10), 0xb6b6b6ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 11), 0xbebebeff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 12), 0xc5c5c5ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 13), 0xd1d1d1ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 14), 0xd6d6d6ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 15), 0xdbdbdbff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 16), 0xe3e3e3ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 17), 0xe9e9e9ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 18), 0xeeeeeeff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 19), 0xf4f4f4ff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 20), 0xfafafaff);
assert.equal(rgba.ensureContrastRatio(0x000000ff, 0x606060ff, 21), 0xffffffff);
});
it('should return undefined if the color already meets the contrast ratio (white bg)', () => {
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 1), undefined);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 2), undefined);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 3), undefined);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 4), undefined);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 5), undefined);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 6), undefined);
});
it('should return a color that meets the contrast ratio (white bg)', () => {
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 7), 0x565656ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 8), 0x4d4d4dff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 9), 0x454545ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 10), 0x3e3e3eff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 11), 0x373737ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 12), 0x313131ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 13), 0x313131ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 14), 0x272727ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 15), 0x232323ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 16), 0x1f1f1fff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 17), 0x1b1b1bff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 18), 0x151515ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 19), 0x101010ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 20), 0x080808ff);
assert.equal(rgba.ensureContrastRatio(0xffffffff, 0x606060ff, 21), 0x000000ff);
});
});
describe('toChannels', () => {
it('should convert an rgba number to an rgba array', () => {
assert.deepEqual(rgba.toChannels(0x00000000), [0x00, 0x00, 0x00, 0x00]);
assert.deepEqual(rgba.toChannels(0x10101010), [0x10, 0x10, 0x10, 0x10]);
assert.deepEqual(rgba.toChannels(0x20202020), [0x20, 0x20, 0x20, 0x20]);
assert.deepEqual(rgba.toChannels(0x30303030), [0x30, 0x30, 0x30, 0x30]);
assert.deepEqual(rgba.toChannels(0x40404040), [0x40, 0x40, 0x40, 0x40]);
assert.deepEqual(rgba.toChannels(0x50505050), [0x50, 0x50, 0x50, 0x50]);
assert.deepEqual(rgba.toChannels(0x60606060), [0x60, 0x60, 0x60, 0x60]);
assert.deepEqual(rgba.toChannels(0x70707070), [0x70, 0x70, 0x70, 0x70]);
assert.deepEqual(rgba.toChannels(0x80808080), [0x80, 0x80, 0x80, 0x80]);
assert.deepEqual(rgba.toChannels(0x90909090), [0x90, 0x90, 0x90, 0x90]);
assert.deepEqual(rgba.toChannels(0xa0a0a0a0), [0xa0, 0xa0, 0xa0, 0xa0]);
assert.deepEqual(rgba.toChannels(0xb0b0b0b0), [0xb0, 0xb0, 0xb0, 0xb0]);
assert.deepEqual(rgba.toChannels(0xc0c0c0c0), [0xc0, 0xc0, 0xc0, 0xc0]);
assert.deepEqual(rgba.toChannels(0xd0d0d0d0), [0xd0, 0xd0, 0xd0, 0xd0]);
assert.deepEqual(rgba.toChannels(0xe0e0e0e0), [0xe0, 0xe0, 0xe0, 0xe0]);
assert.deepEqual(rgba.toChannels(0xf0f0f0f0), [0xf0, 0xf0, 0xf0, 0xf0]);
assert.deepEqual(rgba.toChannels(0xffffffff), [0xff, 0xff, 0xff, 0xff]);
});
});
});
describe('toPaddedHex', () => {
it('should convert numbers to 2-digit hex values', () => {
assert.equal(toPaddedHex(0x00), '00');
assert.equal(toPaddedHex(0x10), '10');
assert.equal(toPaddedHex(0x20), '20');
assert.equal(toPaddedHex(0x30), '30');
assert.equal(toPaddedHex(0x40), '40');
assert.equal(toPaddedHex(0x50), '50');
assert.equal(toPaddedHex(0x60), '60');
assert.equal(toPaddedHex(0x70), '70');
assert.equal(toPaddedHex(0x80), '80');
assert.equal(toPaddedHex(0x90), '90');
assert.equal(toPaddedHex(0xa0), 'a0');
assert.equal(toPaddedHex(0xb0), 'b0');
assert.equal(toPaddedHex(0xc0), 'c0');
assert.equal(toPaddedHex(0xd0), 'd0');
assert.equal(toPaddedHex(0xe0), 'e0');
assert.equal(toPaddedHex(0xf0), 'f0');
assert.equal(toPaddedHex(0xff), 'ff');
});
});
describe('contrastRatio', () => {
it('should calculate the relative luminance of the color', () => {
assert.equal(contrastRatio(0, 0), 1);
assert.equal(contrastRatio(0, 0.5), 11);
assert.equal(contrastRatio(0, 1), 21);
});
it('should work regardless of the parameter order', () => {
assert.equal(contrastRatio(0, 1), 21);
assert.equal(contrastRatio(1, 0), 21);
});
});
});
+384
View File
@@ -0,0 +1,384 @@
/**
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { IColor, IColorRGB } from 'common/services/Types';
let $r = 0;
let $g = 0;
let $b = 0;
let $a = 0;
export const NULL_COLOR: IColor = {
css: '#00000000',
rgba: 0
};
/**
* Helper functions where the source type is "channels" (individual color channels as numbers).
*/
export namespace channels {
export function toCss(r: number, g: number, b: number, a?: number): string {
if (a !== undefined) {
return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}${toPaddedHex(a)}`;
}
return `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`;
}
export function toRgba(r: number, g: number, b: number, a: number = 0xFF): number {
// Note: The aggregated number is RGBA32 (BE), thus needs to be converted to ABGR32
// on LE systems, before it can be used for direct 32-bit buffer writes.
// >>> 0 forces an unsigned int
return (r << 24 | g << 16 | b << 8 | a) >>> 0;
}
export function toColor(r: number, g: number, b: number, a?: number): IColor {
return {
css: channels.toCss(r, g, b, a),
rgba: channels.toRgba(r, g, b, a)
};
}
}
/**
* Helper functions where the source type is `IColor`.
*/
export namespace color {
export function blend(bg: IColor, fg: IColor): IColor {
$a = (fg.rgba & 0xFF) / 255;
if ($a === 1) {
return {
css: fg.css,
rgba: fg.rgba
};
}
const fgR = (fg.rgba >> 24) & 0xFF;
const fgG = (fg.rgba >> 16) & 0xFF;
const fgB = (fg.rgba >> 8) & 0xFF;
const bgR = (bg.rgba >> 24) & 0xFF;
const bgG = (bg.rgba >> 16) & 0xFF;
const bgB = (bg.rgba >> 8) & 0xFF;
$r = bgR + Math.round((fgR - bgR) * $a);
$g = bgG + Math.round((fgG - bgG) * $a);
$b = bgB + Math.round((fgB - bgB) * $a);
const css = channels.toCss($r, $g, $b);
const rgba = channels.toRgba($r, $g, $b);
return { css, rgba };
}
export function isOpaque(color: IColor): boolean {
return (color.rgba & 0xFF) === 0xFF;
}
export function ensureContrastRatio(bg: IColor, fg: IColor, ratio: number): IColor | undefined {
const result = rgba.ensureContrastRatio(bg.rgba, fg.rgba, ratio);
if (!result) {
return undefined;
}
return channels.toColor(
(result >> 24 & 0xFF),
(result >> 16 & 0xFF),
(result >> 8 & 0xFF)
);
}
export function opaque(color: IColor): IColor {
const rgbaColor = (color.rgba | 0xFF) >>> 0;
[$r, $g, $b] = rgba.toChannels(rgbaColor);
return {
css: channels.toCss($r, $g, $b),
rgba: rgbaColor
};
}
export function opacity(color: IColor, opacity: number): IColor {
$a = Math.round(opacity * 0xFF);
[$r, $g, $b] = rgba.toChannels(color.rgba);
return {
css: channels.toCss($r, $g, $b, $a),
rgba: channels.toRgba($r, $g, $b, $a)
};
}
export function multiplyOpacity(color: IColor, factor: number): IColor {
$a = color.rgba & 0xFF;
return opacity(color, ($a * factor) / 0xFF);
}
export function toColorRGB(color: IColor): IColorRGB {
return [(color.rgba >> 24) & 0xFF, (color.rgba >> 16) & 0xFF, (color.rgba >> 8) & 0xFF];
}
}
/**
* Helper functions where the source type is "css" (string: '#rgb', '#rgba', '#rrggbb',
* '#rrggbbaa').
*/
export namespace css {
// Attempt to set get the shared canvas context
let $ctx: CanvasRenderingContext2D | undefined;
let $litmusColor: CanvasGradient | undefined;
try {
// This is guaranteed to run in the first window, so document should be correct
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
const ctx = canvas.getContext('2d', {
willReadFrequently: true
});
if (ctx) {
$ctx = ctx;
$ctx.globalCompositeOperation = 'copy';
$litmusColor = $ctx.createLinearGradient(0, 0, 1, 1);
}
}
catch {
// noop
}
/**
* Converts a css string to an IColor, this should handle all valid CSS color strings and will
* throw if it's invalid. The ideal format to use is `#rrggbb[aa]` as it's the fastest to parse.
*
* Only `#rgb[a]`, `#rrggbb[aa]`, `rgb()` and `rgba()` formats are supported when run in a Node
* environment.
*/
export function toColor(css: string): IColor {
// Formats: #rgb[a] and #rrggbb[aa]
if (css.match(/#[\da-f]{3,8}/i)) {
switch (css.length) {
case 4: { // #rgb
$r = parseInt(css.slice(1, 2).repeat(2), 16);
$g = parseInt(css.slice(2, 3).repeat(2), 16);
$b = parseInt(css.slice(3, 4).repeat(2), 16);
return channels.toColor($r, $g, $b);
}
case 5: { // #rgba
$r = parseInt(css.slice(1, 2).repeat(2), 16);
$g = parseInt(css.slice(2, 3).repeat(2), 16);
$b = parseInt(css.slice(3, 4).repeat(2), 16);
$a = parseInt(css.slice(4, 5).repeat(2), 16);
return channels.toColor($r, $g, $b, $a);
}
case 7: // #rrggbb
return {
css,
rgba: (parseInt(css.slice(1), 16) << 8 | 0xFF) >>> 0
};
case 9: // #rrggbbaa
return {
css,
rgba: parseInt(css.slice(1), 16) >>> 0
};
}
}
// Formats: rgb() or rgba()
const rgbaMatch = css.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);
if (rgbaMatch) {
$r = parseInt(rgbaMatch[1]);
$g = parseInt(rgbaMatch[2]);
$b = parseInt(rgbaMatch[3]);
$a = Math.round((rgbaMatch[5] === undefined ? 1 : parseFloat(rgbaMatch[5])) * 0xFF);
return channels.toColor($r, $g, $b, $a);
}
// Handle the "transparent" keyword
if (css === 'transparent') {
return {
css: 'transparent',
rgba: 0x00000000
};
}
// Validate the context is available for canvas-based color parsing
if (!$ctx || !$litmusColor) {
throw new Error('css.toColor: Unsupported css format');
}
// Validate the color using canvas fillStyle
// See https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles
$ctx.fillStyle = $litmusColor;
$ctx.fillStyle = css;
if (typeof $ctx.fillStyle !== 'string') {
throw new Error('css.toColor: Unsupported css format');
}
$ctx.fillRect(0, 0, 1, 1);
[$r, $g, $b, $a] = $ctx.getImageData(0, 0, 1, 1).data;
// Validate the color is non-transparent as color hue gets lost when drawn to the canvas
if ($a !== 0xFF) {
throw new Error('css.toColor: Unsupported css format');
}
// Extract the color from the canvas' fillStyle property which exposes the color value in rgba()
// format
// See https://html.spec.whatwg.org/multipage/canvas.html#serialisation-of-a-color
return {
rgba: channels.toRgba($r, $g, $b, $a),
css
};
}
}
/**
* Helper functions where the source type is "rgb" (number: 0xrrggbb).
*/
export namespace rgb {
/**
* Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio
* between two colors.
* @param rgb The color to use.
* @see https://www.w3.org/TR/WCAG20/#relativeluminancedef
*/
export function relativeLuminance(rgb: number): number {
return relativeLuminance2(
(rgb >> 16) & 0xFF,
(rgb >> 8 ) & 0xFF,
(rgb ) & 0xFF);
}
/**
* Gets the relative luminance of an RGB color, this is useful in determining the contrast ratio
* between two colors.
* @param r The red channel (0x00 to 0xFF).
* @param g The green channel (0x00 to 0xFF).
* @param b The blue channel (0x00 to 0xFF).
* @see https://www.w3.org/TR/WCAG20/#relativeluminancedef
*/
export function relativeLuminance2(r: number, g: number, b: number): number {
const rs = r / 255;
const gs = g / 255;
const bs = b / 255;
const rr = rs <= 0.03928 ? rs / 12.92 : Math.pow((rs + 0.055) / 1.055, 2.4);
const rg = gs <= 0.03928 ? gs / 12.92 : Math.pow((gs + 0.055) / 1.055, 2.4);
const rb = bs <= 0.03928 ? bs / 12.92 : Math.pow((bs + 0.055) / 1.055, 2.4);
return rr * 0.2126 + rg * 0.7152 + rb * 0.0722;
}
}
/**
* Helper functions where the source type is "rgba" (number: 0xrrggbbaa).
*/
export namespace rgba {
export function blend(bg: number, fg: number): number {
$a = (fg & 0xFF) / 0xFF;
if ($a === 1) {
return fg;
}
const fgR = (fg >> 24) & 0xFF;
const fgG = (fg >> 16) & 0xFF;
const fgB = (fg >> 8) & 0xFF;
const bgR = (bg >> 24) & 0xFF;
const bgG = (bg >> 16) & 0xFF;
const bgB = (bg >> 8) & 0xFF;
$r = bgR + Math.round((fgR - bgR) * $a);
$g = bgG + Math.round((fgG - bgG) * $a);
$b = bgB + Math.round((fgB - bgB) * $a);
return channels.toRgba($r, $g, $b);
}
/**
* Given a foreground color and a background color, either increase or reduce the luminance of the
* foreground color until the specified contrast ratio is met. If pure white or black is hit
* without the contrast ratio being met, go the other direction using the background color as the
* foreground color and take either the first or second result depending on which has the higher
* contrast ratio.
*
* `undefined` will be returned if the contrast ratio is already met.
*
* @param bgRgba The background color in rgba format.
* @param fgRgba The foreground color in rgba format.
* @param ratio The contrast ratio to achieve.
*/
export function ensureContrastRatio(bgRgba: number, fgRgba: number, ratio: number): number | undefined {
const bgL = rgb.relativeLuminance(bgRgba >> 8);
const fgL = rgb.relativeLuminance(fgRgba >> 8);
const cr = contrastRatio(bgL, fgL);
if (cr < ratio) {
if (fgL < bgL) {
const resultA = reduceLuminance(bgRgba, fgRgba, ratio);
const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8));
if (resultARatio < ratio) {
const resultB = increaseLuminance(bgRgba, fgRgba, ratio);
const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8));
return resultARatio > resultBRatio ? resultA : resultB;
}
return resultA;
}
const resultA = increaseLuminance(bgRgba, fgRgba, ratio);
const resultARatio = contrastRatio(bgL, rgb.relativeLuminance(resultA >> 8));
if (resultARatio < ratio) {
const resultB = reduceLuminance(bgRgba, fgRgba, ratio);
const resultBRatio = contrastRatio(bgL, rgb.relativeLuminance(resultB >> 8));
return resultARatio > resultBRatio ? resultA : resultB;
}
return resultA;
}
return undefined;
}
export function reduceLuminance(bgRgba: number, fgRgba: number, ratio: number): number {
// This is a naive but fast approach to reducing luminance as converting to
// HSL and back is expensive
const bgR = (bgRgba >> 24) & 0xFF;
const bgG = (bgRgba >> 16) & 0xFF;
const bgB = (bgRgba >> 8) & 0xFF;
let fgR = (fgRgba >> 24) & 0xFF;
let fgG = (fgRgba >> 16) & 0xFF;
let fgB = (fgRgba >> 8) & 0xFF;
let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));
while (cr < ratio && (fgR > 0 || fgG > 0 || fgB > 0)) {
// Reduce by 10% until the ratio is hit
fgR -= Math.max(0, Math.ceil(fgR * 0.1));
fgG -= Math.max(0, Math.ceil(fgG * 0.1));
fgB -= Math.max(0, Math.ceil(fgB * 0.1));
cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));
}
return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0;
}
export function increaseLuminance(bgRgba: number, fgRgba: number, ratio: number): number {
// This is a naive but fast approach to increasing luminance as converting to
// HSL and back is expensive
const bgR = (bgRgba >> 24) & 0xFF;
const bgG = (bgRgba >> 16) & 0xFF;
const bgB = (bgRgba >> 8) & 0xFF;
let fgR = (fgRgba >> 24) & 0xFF;
let fgG = (fgRgba >> 16) & 0xFF;
let fgB = (fgRgba >> 8) & 0xFF;
let cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));
while (cr < ratio && (fgR < 0xFF || fgG < 0xFF || fgB < 0xFF)) {
// Increase by 10% until the ratio is hit
fgR = Math.min(0xFF, fgR + Math.ceil((255 - fgR) * 0.1));
fgG = Math.min(0xFF, fgG + Math.ceil((255 - fgG) * 0.1));
fgB = Math.min(0xFF, fgB + Math.ceil((255 - fgB) * 0.1));
cr = contrastRatio(rgb.relativeLuminance2(fgR, fgG, fgB), rgb.relativeLuminance2(bgR, bgG, bgB));
}
return (fgR << 24 | fgG << 16 | fgB << 8 | 0xFF) >>> 0;
}
export function toChannels(value: number): [number, number, number, number] {
return [(value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF];
}
}
export function toPaddedHex(c: number): string {
const s = c.toString(16);
return s.length < 2 ? '0' + s : s;
}
/**
* Gets the contrast ratio between two relative luminance values.
* @param l1 The first relative luminance.
* @param l2 The first relative luminance.
* @see https://www.w3.org/TR/WCAG20/#contrast-ratiodef
*/
export function contrastRatio(l1: number, l2: number): number {
if (l1 < l2) {
return (l2 + 0.05) / (l1 + 0.05);
}
return (l1 + 0.05) / (l2 + 0.05);
}
+1 -1
View File
@@ -5,7 +5,7 @@
import { ICoreService } from 'common/services/Services';
import { CoreService } from 'common/services/CoreService';
import { MockBufferService, MockLogService, MockOptionsService } from 'common/TestUtils.test';
import { MockBufferService, MockLogService, MockOptionsService } from 'common/terminal/TestUtils.test';
import { assert } from 'chai';
describe('CoreService', () => {
+3 -3
View File
@@ -3,10 +3,10 @@
* @license MIT
*/
import { Disposable } from 'common/Lifecycle';
import { IDecPrivateModes, IKittyKeyboardState, IModes } from 'common/Types';
import { Disposable } from 'common/base/Lifecycle';
import { IDecPrivateModes, IKittyKeyboardState, IModes } from 'common/services/Types';
import { IBufferService, ICoreService, ILogService, IOptionsService } from 'common/services/Services';
import { Emitter } from 'common/Event';
import { Emitter } from 'common/base/Event';
const DEFAULT_MODES: IModes = Object.freeze({
insertMode: false
@@ -5,10 +5,10 @@
import { assert } from 'chai';
import { DecorationLineCache, DecorationService } from './DecorationService';
import { IMarker } from 'common/Types';
import { Disposable } from 'common/Lifecycle';
import { Emitter } from 'common/Event';
import { MockLogService, MockBufferService, MockOptionsService } from 'common/TestUtils.test';
import { IMarker } from 'common/services/Types';
import { Disposable } from 'common/base/Lifecycle';
import { Emitter } from 'common/base/Event';
import { MockLogService, MockBufferService, MockOptionsService } from 'common/terminal/TestUtils.test';
import { Buffer } from 'common/buffer/Buffer';
import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
+7 -7
View File
@@ -3,15 +3,15 @@
* @license MIT
*/
import type { IDeleteEvent, IInsertEvent } from 'common/CircularList';
import { MicrotaskTimer } from 'common/Async';
import { css } from 'common/Color';
import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'common/Lifecycle';
import type { IDeleteEvent, IInsertEvent } from 'common/services/CircularList';
import { MicrotaskTimer } from 'common/base/Async';
import { css } from 'common/services/Color';
import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'common/base/Lifecycle';
import { IBufferService, IDecorationService, IInternalDecoration, ILogService } from 'common/services/Services';
import { SortedList } from 'common/SortedList';
import { IColor, ICircularList } from 'common/Types';
import { SortedList } from 'common/services/SortedList';
import { IColor, ICircularList } from 'common/services/Types';
import { IDecoration, IDecorationOptions, IMarker } from '@xterm/xterm';
import { Emitter } from 'common/Event';
import { Emitter } from 'common/base/Event';
// Work variables to avoid garbage collection
let $xmin = 0;
+1 -1
View File
@@ -3,7 +3,7 @@
* @license MIT
*/
import { Disposable } from 'common/Lifecycle';
import { Disposable } from 'common/base/Lifecycle';
import { ILogService, IOptionsService, LogLevelEnum } from 'common/services/Services';
type LogType = (message?: any, ...optionalParams: any[]) => void;
@@ -4,7 +4,7 @@
*/
import { MouseStateService } from 'common/services/MouseStateService';
import { assert } from 'chai';
import { ICoreMouseEvent, CoreMouseEventType } from 'common/Types';
import { ICoreMouseEvent, CoreMouseEventType } from 'common/services/Types';
function toBytes(s: string | undefined): number[] {
if (!s) {
+3 -3
View File
@@ -3,9 +3,9 @@
* @license MIT
*/
import { IMouseStateService } from 'common/services/Services';
import { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';
import { Disposable } from 'common/Lifecycle';
import { Emitter } from 'common/Event';
import { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/services/Types';
import { Disposable } from 'common/base/Lifecycle';
import { Emitter } from 'common/base/Event';
/**
* Supported default protocols.
+17
View File
@@ -0,0 +1,17 @@
import { Disposable } from 'common/base/Lifecycle';
import { IDisposable } from 'common/services/Types';
import { IOptionsService, ITerminalOptions } from 'common/services/Services';
export declare const DEFAULT_OPTIONS: Readonly<Required<ITerminalOptions>>;
export declare class OptionsService extends Disposable implements IOptionsService {
serviceBrand: any;
readonly rawOptions: Required<ITerminalOptions>;
options: Required<ITerminalOptions>;
private readonly _onOptionChange;
readonly onOptionChange: import("common/base/Event").IEvent<keyof ITerminalOptions>;
constructor(options: Partial<ITerminalOptions>);
onSpecificOptionChange<T extends keyof ITerminalOptions>(key: T, listener: (value: ITerminalOptions[T]) => any): IDisposable;
onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable;
private _setupOptions;
private _sanitizeAndValidateOption;
}
//# sourceMappingURL=OptionsService.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"OptionsService.d.ts","sourceRoot":"","sources":["OptionsService.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAgB,MAAM,uBAAuB,CAAC;AAEjE,OAAO,EAAe,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAc,eAAe,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAGzF,eAAO,MAAM,eAAe,EAAE,QAAQ,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAiDhE,CAAC;AAIF,qBAAa,cAAe,SAAQ,UAAW,YAAW,eAAe;IAChE,YAAY,EAAE,GAAG,CAAC;IAEzB,SAAgB,UAAU,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IAChD,OAAO,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IAE3C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAyD;IACzF,SAAgB,cAAc,6DAA8B;IAE5D,YAAY,OAAO,EAAE,OAAO,CAAC,gBAAgB,CAAC,EA0B7C;IAGM,sBAAsB,CAAC,CAAC,SAAS,MAAM,gBAAgB,EAAE,GAAG,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC,CAAC,KAAK,GAAG,GAAG,WAAW,CAMlI;IAGM,sBAAsB,CAAC,IAAI,EAAE,CAAC,MAAM,gBAAgB,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,GAAG,GAAG,WAAW,CAMhG;IAED,OAAO,CAAC,aAAa;IA8BrB,OAAO,CAAC,0BAA0B;CAiEnC"}
+190
View File
@@ -0,0 +1,190 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OptionsService = exports.DEFAULT_OPTIONS = void 0;
const Lifecycle_1 = require("common/base/Lifecycle");
const Platform_1 = require("common/base/Platform");
const Event_1 = require("common/base/Event");
exports.DEFAULT_OPTIONS = {
cols: 80,
rows: 24,
showCursorImmediately: false,
cursorBlink: false,
blinkIntervalDuration: 0,
cursorStyle: 'block',
cursorWidth: 1,
cursorInactiveStyle: 'outline',
drawBoldTextInBrightColors: true,
documentOverride: null,
fastScrollSensitivity: 5,
fontFamily: 'monospace',
fontSize: 15,
fontWeight: 'normal',
fontWeightBold: 'bold',
ignoreBracketedPasteMode: false,
lineHeight: 1.0,
letterSpacing: 0,
linkHandler: null,
logLevel: 'info',
logger: null,
scrollback: 1000,
scrollbar: { showScrollbar: true },
scrollOnEraseInDisplay: false,
scrollOnUserInput: true,
scrollSensitivity: 1,
screenReaderMode: false,
smoothScrollDuration: 0,
macOptionIsMeta: false,
macOptionClickForcesSelection: false,
minimumContrastRatio: 1,
mouseEventsRequireAlt: false,
disableStdin: false,
allowProposedApi: false,
allowTransparency: false,
tabStopWidth: 8,
theme: {},
reflowCursorLine: false,
rescaleOverlappingGlyphs: false,
rightClickSelectsWord: Platform_1.isMac,
windowOptions: {},
windowsPty: {},
wordSeparator: ' ()[]{}\',"`',
altClickMovesCursor: true,
convertEol: false,
termName: 'xterm',
quirks: {},
vtExtensions: {}
};
const FONT_WEIGHT_OPTIONS = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];
class OptionsService extends Lifecycle_1.Disposable {
constructor(options) {
super();
this._onOptionChange = this._register(new Event_1.Emitter());
this.onOptionChange = this._onOptionChange.event;
const defaultOptions = { ...exports.DEFAULT_OPTIONS };
for (const key in options) {
if (key in defaultOptions) {
try {
const newValue = options[key];
defaultOptions[key] = this._sanitizeAndValidateOption(key, newValue);
}
catch (e) {
console.error(e);
}
}
}
this.rawOptions = defaultOptions;
this.options = { ...defaultOptions };
this._setupOptions();
this._register((0, Lifecycle_1.toDisposable)(() => {
this.rawOptions.linkHandler = null;
this.rawOptions.documentOverride = null;
}));
}
onSpecificOptionChange(key, listener) {
return this.onOptionChange(eventKey => {
if (eventKey === key) {
listener(this.rawOptions[key]);
}
});
}
onMultipleOptionChange(keys, listener) {
return this.onOptionChange(eventKey => {
if (keys.indexOf(eventKey) !== -1) {
listener();
}
});
}
_setupOptions() {
const getter = (propName) => {
if (!(propName in exports.DEFAULT_OPTIONS)) {
throw new Error(`No option with key "${propName}"`);
}
return this.rawOptions[propName];
};
const setter = (propName, value) => {
if (!(propName in exports.DEFAULT_OPTIONS)) {
throw new Error(`No option with key "${propName}"`);
}
value = this._sanitizeAndValidateOption(propName, value);
if (this.rawOptions[propName] !== value) {
this.rawOptions[propName] = value;
this._onOptionChange.fire(propName);
}
};
for (const propName in this.rawOptions) {
const desc = {
get: getter.bind(this, propName),
set: setter.bind(this, propName)
};
Object.defineProperty(this.options, propName, desc);
}
}
_sanitizeAndValidateOption(key, value) {
switch (key) {
case 'cursorStyle':
if (!value) {
value = exports.DEFAULT_OPTIONS[key];
}
if (!isCursorStyle(value)) {
throw new Error(`"${value}" is not a valid value for ${key}`);
}
break;
case 'wordSeparator':
if (!value) {
value = exports.DEFAULT_OPTIONS[key];
}
break;
case 'fontWeight':
case 'fontWeightBold':
if (typeof value === 'number' && 1 <= value && value <= 1000) {
break;
}
value = FONT_WEIGHT_OPTIONS.includes(value) ? value : exports.DEFAULT_OPTIONS[key];
break;
case 'blinkIntervalDuration':
value = Math.floor(value);
if (value < 0) {
throw new Error(`${key} cannot be less than 0, value: ${value}`);
}
break;
case 'cursorWidth':
value = Math.floor(value);
case 'lineHeight':
case 'tabStopWidth':
if (value < 1) {
throw new Error(`${key} cannot be less than 1, value: ${value}`);
}
break;
case 'minimumContrastRatio':
value = Math.max(1, Math.min(21, Math.round(value * 10) / 10));
break;
case 'scrollback':
value = Math.min(value, 4294967295);
if (value < 0) {
throw new Error(`${key} cannot be less than 0, value: ${value}`);
}
break;
case 'fastScrollSensitivity':
case 'scrollSensitivity':
if (value <= 0) {
throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`);
}
break;
case 'rows':
case 'cols':
if (!value && value !== 0) {
throw new Error(`${key} must be numeric, value: ${value}`);
}
break;
case 'windowsPty':
value = value ?? {};
break;
}
return value;
}
}
exports.OptionsService = OptionsService;
function isCursorStyle(value) {
return value === 'block' || value === 'underline' || value === 'bar';
}
//# sourceMappingURL=OptionsService.js.map
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -5,7 +5,7 @@
import { assert } from 'chai';
import { OptionsService, DEFAULT_OPTIONS } from 'common/services/OptionsService';
import { IDisposable } from 'common/Types';
import { IDisposable } from 'common/services/Types';
describe('OptionsService', () => {
describe('constructor', () => {
+4 -4
View File
@@ -3,11 +3,11 @@
* @license MIT
*/
import { Disposable, toDisposable } from 'common/Lifecycle';
import { isMac } from 'common/Platform';
import { CursorStyle, IDisposable } from 'common/Types';
import { Disposable, toDisposable } from 'common/base/Lifecycle';
import { isMac } from 'common/base/Platform';
import { CursorStyle, IDisposable } from 'common/services/Types';
import { FontWeight, IOptionsService, ITerminalOptions } from 'common/services/Services';
import { Emitter } from 'common/Event';
import { Emitter } from 'common/base/Event';
export const DEFAULT_OPTIONS: Readonly<Required<ITerminalOptions>> = {
cols: 80,
+1 -1
View File
@@ -9,7 +9,7 @@ import { BufferService } from 'common/services/BufferService';
import { OptionsService } from 'common/services/OptionsService';
import { OscLinkService } from 'common/services/OscLinkService';
import { IBufferService, IOptionsService, IOscLinkService } from 'common/services/Services';
import { MockLogService } from 'common/TestUtils.test';
import { MockLogService } from 'common/terminal/TestUtils.test';
describe('OscLinkService', () => {
describe('constructor', () => {
+1 -1
View File
@@ -3,7 +3,7 @@
* @license MIT
*/
import { IBufferService, IOscLinkService } from 'common/services/Services';
import { IMarker, IOscLinkData } from 'common/Types';
import { IMarker, IOscLinkData } from 'common/services/Types';
export class OscLinkService implements IOscLinkService {
public serviceBrand: any;
+9
View File
@@ -0,0 +1,9 @@
import { IServiceIdentifier } from 'common/services/Services';
export declare const serviceRegistry: Map<string, IServiceIdentifier<any>>;
export declare function getServiceDependencies(ctor: any): {
id: IServiceIdentifier<any>;
index: number;
optional: boolean;
}[];
export declare function createDecorator<T>(id: string): IServiceIdentifier<T>;
//# sourceMappingURL=ServiceRegistry.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"ServiceRegistry.d.ts","sourceRoot":"","sources":["ServiceRegistry.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAO9D,eAAO,MAAM,eAAe,EAAE,GAAG,CAAC,MAAM,EAAE,kBAAkB,CAAC,GAAG,CAAC,CAAa,CAAC;AAE/E,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,GAAG,GAAG;IAAE,EAAE,EAAE,kBAAkB,CAAC,GAAG,CAAC,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,EAAE,CAErH;AAED,wBAAgB,eAAe,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,kBAAkB,CAAC,CAAC,CAAC,CAiBpE"}
+33
View File
@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceRegistry = void 0;
exports.getServiceDependencies = getServiceDependencies;
exports.createDecorator = createDecorator;
exports.serviceRegistry = new Map();
function getServiceDependencies(ctor) {
return ctor["di$dependencies"] || [];
}
function createDecorator(id) {
if (exports.serviceRegistry.has(id)) {
return exports.serviceRegistry.get(id);
}
const decorator = function (target, key, index) {
if (arguments.length !== 3) {
throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
}
storeServiceDependency(decorator, target, index);
};
decorator._id = id;
exports.serviceRegistry.set(id, decorator);
return decorator;
}
function storeServiceDependency(id, target, index) {
if (target["di$target"] === target) {
target["di$dependencies"].push({ id, index });
}
else {
target["di$dependencies"] = [{ id, index }];
target["di$target"] = target;
}
}
//# sourceMappingURL=ServiceRegistry.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ServiceRegistry.js","sourceRoot":"","sources":["ServiceRegistry.ts"],"names":[],"mappings":";;;;;AAkBa,QAAA,eAAe,GAAyC,IAAI,GAAG,EAAE,CAAC;AAE/E,gCAAuC,IAAS;IAC9C,OAAO,IAAI,mBAA2B,IAAI,EAAE,CAAC;AAC/C,CAAC;AAED,yBAAmC,EAAU;IAC3C,IAAI,QAAA,eAAe,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;QAC5B,OAAO,QAAA,eAAe,CAAC,GAAG,CAAC,EAAE,CAAE,CAAC;IAClC,CAAC;IAED,MAAM,SAAS,GAAQ,UAAU,MAAgB,EAAE,GAAW,EAAE,KAAa;QAC3E,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC3B,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;QACtF,CAAC;QAED,sBAAsB,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACnD,CAAC,CAAC;IAEF,SAAS,CAAC,GAAG,GAAG,EAAE,CAAC;IAEnB,QAAA,eAAe,CAAC,GAAG,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC;IACnC,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,sBAAsB,CAAC,EAAY,EAAE,MAAgB,EAAE,KAAa;IAC3E,IAAK,MAAc,aAAqB,KAAK,MAAM,EAAE,CAAC;QACnD,MAAc,mBAA2B,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IACjE,CAAC;SAAM,CAAC;QACL,MAAc,mBAA2B,GAAG,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5D,MAAc,aAAqB,GAAG,MAAM,CAAC;IAChD,CAAC;AACH,CAAC"}
+253
View File
@@ -0,0 +1,253 @@
import type { IDecoration, IDecorationOptions, ILinkHandler, ILogger, IWindowsPty, IOverviewRulerOptions } from '@xterm/xterm';
import { CoreMouseEncoding, CoreMouseEventType, CursorInactiveStyle, CursorStyle, IAttributeData, ICharset, IColor, ICoreMouseEvent, ICoreMouseProtocol, IDecPrivateModes, IDisposable, IKittyKeyboardState, IModes, IOscLinkData, IWindowOptions } from 'common/services/Types';
import { IBuffer, IBufferSet } from 'common/buffer/Types';
import type { Emitter, IEvent } from 'common/base/Event';
export declare const IBufferService: IServiceIdentifier<IBufferService>;
export interface IBufferService {
serviceBrand: undefined;
readonly cols: number;
readonly rows: number;
readonly buffer: IBuffer;
readonly buffers: IBufferSet;
isUserScrolling: boolean;
onResize: IEvent<IBufferResizeEvent>;
onScroll: IEvent<number>;
scroll(eraseAttr: IAttributeData, isWrapped?: boolean): void;
scrollLines(disp: number, suppressScrollEvent?: boolean): void;
resize(cols: number, rows: number): void;
reset(): void;
}
export interface IBufferResizeEvent {
cols: number;
rows: number;
colsChanged: boolean;
rowsChanged: boolean;
}
export declare const IMouseStateService: IServiceIdentifier<IMouseStateService>;
export interface IMouseStateService {
serviceBrand: undefined;
activeProtocol: string;
activeEncoding: string;
areMouseEventsActive: boolean;
addProtocol(name: string, protocol: ICoreMouseProtocol): void;
addEncoding(name: string, encoding: CoreMouseEncoding): void;
reset(): void;
setCustomWheelEventHandler(customWheelEventHandler: ((event: WheelEvent) => boolean) | undefined): void;
allowCustomWheelEvent(ev: WheelEvent): boolean;
onProtocolChange: IEvent<CoreMouseEventType>;
restrictMouseEvent(event: ICoreMouseEvent): boolean;
encodeMouseEvent(event: ICoreMouseEvent): string;
readonly isDefaultEncoding: boolean;
readonly isPixelEncoding: boolean;
}
export declare const ICoreService: IServiceIdentifier<ICoreService>;
export interface ICoreService {
serviceBrand: undefined;
isCursorInitialized: boolean;
isCursorHidden: boolean;
readonly modes: IModes;
readonly decPrivateModes: IDecPrivateModes;
readonly kittyKeyboard: IKittyKeyboardState;
readonly onData: IEvent<string>;
readonly onUserInput: IEvent<void>;
readonly onBinary: IEvent<string>;
readonly onRequestScrollToBottom: IEvent<void>;
reset(): void;
triggerDataEvent(data: string, wasUserInput?: boolean): void;
triggerBinaryEvent(data: string): void;
}
export declare const ICharsetService: IServiceIdentifier<ICharsetService>;
export interface ICharsetService {
serviceBrand: undefined;
charset: ICharset | undefined;
readonly glevel: number;
readonly charsets: (ICharset | undefined)[];
reset(): void;
setgLevel(g: number): void;
setgCharset(g: number, charset: ICharset | undefined): void;
}
export interface IServiceIdentifier<T> {
(...args: any[]): void;
type: T;
_id: string;
}
export interface IBrandedService {
serviceBrand: undefined;
}
type GetLeadingNonServiceArgs<TArgs extends any[]> = TArgs extends [] ? [] : TArgs extends [...infer TFirst, infer TLast] ? TLast extends IBrandedService ? GetLeadingNonServiceArgs<TFirst> : TArgs : never;
export declare const IInstantiationService: IServiceIdentifier<IInstantiationService>;
export interface IInstantiationService {
serviceBrand: undefined;
setService<T>(id: IServiceIdentifier<T>, instance: T): void;
getService<T>(id: IServiceIdentifier<T>): T | undefined;
createInstance<Ctor extends new (...args: any[]) => any, R extends InstanceType<Ctor>>(t: Ctor, ...args: GetLeadingNonServiceArgs<ConstructorParameters<Ctor>>): R;
}
export declare enum LogLevelEnum {
TRACE = 0,
DEBUG = 1,
INFO = 2,
WARN = 3,
ERROR = 4,
OFF = 5
}
export declare const ILogService: IServiceIdentifier<ILogService>;
export interface ILogService {
serviceBrand: undefined;
readonly logLevel: LogLevelEnum;
trace(message: any, ...optionalParams: any[]): void;
debug(message: any, ...optionalParams: any[]): void;
info(message: any, ...optionalParams: any[]): void;
warn(message: any, ...optionalParams: any[]): void;
error(message: any, ...optionalParams: any[]): void;
}
export declare const IOptionsService: IServiceIdentifier<IOptionsService>;
export interface IOptionsService {
serviceBrand: undefined;
readonly rawOptions: Required<ITerminalOptions>;
readonly options: Required<ITerminalOptions>;
readonly onOptionChange: IEvent<keyof ITerminalOptions>;
onSpecificOptionChange<T extends keyof ITerminalOptions>(key: T, listener: (arg1: Required<ITerminalOptions>[T]) => any): IDisposable;
onMultipleOptionChange(keys: (keyof ITerminalOptions)[], listener: () => any): IDisposable;
}
export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | number;
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'off';
export interface ITerminalOptions {
allowProposedApi?: boolean;
allowTransparency?: boolean;
altClickMovesCursor?: boolean;
cols?: number;
convertEol?: boolean;
cursorBlink?: boolean;
blinkIntervalDuration?: number;
cursorStyle?: CursorStyle;
cursorWidth?: number;
cursorInactiveStyle?: CursorInactiveStyle;
disableStdin?: boolean;
documentOverride?: any | null;
drawBoldTextInBrightColors?: boolean;
fastScrollSensitivity?: number;
fontSize?: number;
fontFamily?: string;
fontWeight?: FontWeight;
fontWeightBold?: FontWeight;
ignoreBracketedPasteMode?: boolean;
letterSpacing?: number;
lineHeight?: number;
linkHandler?: ILinkHandler | null;
logLevel?: LogLevel;
logger?: ILogger | null;
macOptionIsMeta?: boolean;
macOptionClickForcesSelection?: boolean;
minimumContrastRatio?: number;
mouseEventsRequireAlt?: boolean;
reflowCursorLine?: boolean;
rescaleOverlappingGlyphs?: boolean;
rightClickSelectsWord?: boolean;
rows?: number;
showCursorImmediately?: boolean;
screenReaderMode?: boolean;
scrollback?: number;
scrollOnUserInput?: boolean;
scrollSensitivity?: number;
smoothScrollDuration?: number;
tabStopWidth?: number;
theme?: ITheme;
windowsPty?: IWindowsPty;
windowOptions?: IWindowOptions;
wordSeparator?: string;
quirks?: ITerminalQuirks;
scrollbar?: IScrollbarOptions;
scrollOnEraseInDisplay?: boolean;
vtExtensions?: IVtExtensions;
[key: string]: any;
termName: string;
}
export interface ITheme {
foreground?: string;
background?: string;
cursor?: string;
cursorAccent?: string;
selectionForeground?: string;
selectionBackground?: string;
selectionInactiveBackground?: string;
scrollbarSliderBackground?: string;
scrollbarSliderHoverBackground?: string;
scrollbarSliderActiveBackground?: string;
overviewRulerBorder?: string;
black?: string;
red?: string;
green?: string;
yellow?: string;
blue?: string;
magenta?: string;
cyan?: string;
white?: string;
brightBlack?: string;
brightRed?: string;
brightGreen?: string;
brightYellow?: string;
brightBlue?: string;
brightMagenta?: string;
brightCyan?: string;
brightWhite?: string;
extendedAnsi?: string[];
}
export interface ITerminalQuirks {
allowSetCursorBlink?: boolean;
}
export interface IScrollbarOptions {
showScrollbar?: boolean;
showArrows?: boolean;
width?: number;
overviewRuler?: IOverviewRulerOptions;
}
export interface IVtExtensions {
kittyKeyboard?: boolean;
kittySgrBoldFaintControl?: boolean;
win32InputMode?: boolean;
colorSchemeQuery?: boolean;
}
export declare const IOscLinkService: IServiceIdentifier<IOscLinkService>;
export interface IOscLinkService {
serviceBrand: undefined;
registerLink(linkData: IOscLinkData): number;
addLineToLink(linkId: number, y: number): void;
getLinkData(linkId: number): IOscLinkData | undefined;
}
export type UnicodeCharProperties = number;
export type UnicodeCharWidth = 0 | 1 | 2;
export declare const IUnicodeService: IServiceIdentifier<IUnicodeService>;
export interface IUnicodeService {
serviceBrand: undefined;
register(provider: IUnicodeVersionProvider): void;
readonly versions: string[];
activeVersion: string;
readonly onChange: IEvent<string>;
wcwidth(codepoint: number): UnicodeCharWidth;
getStringCellWidth(s: string): number;
charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties;
}
export interface IUnicodeVersionProvider {
readonly version: string;
wcwidth(ucs: number): UnicodeCharWidth;
charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties;
}
export declare const IDecorationService: IServiceIdentifier<IDecorationService>;
export interface IDecorationService extends IDisposable {
serviceBrand: undefined;
readonly decorations: IterableIterator<IInternalDecoration>;
readonly onDecorationRegistered: IEvent<IInternalDecoration>;
readonly onDecorationRemoved: IEvent<IInternalDecoration>;
registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined;
reset(): void;
forEachDecorationAtCell(x: number, line: number, layer: 'bottom' | 'top' | undefined, callback: (decoration: IInternalDecoration) => void): void;
}
export interface IInternalDecoration extends IDecoration {
readonly options: IDecorationOptions;
readonly backgroundColorRGB: IColor | undefined;
readonly foregroundColorRGB: IColor | undefined;
readonly onRenderEmitter: Emitter<HTMLElement>;
_indexedStartLine: number;
}
export {};
//# sourceMappingURL=Services.d.ts.map
File diff suppressed because one or more lines are too long
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IDecorationService = exports.IUnicodeService = exports.IOscLinkService = exports.IOptionsService = exports.ILogService = exports.LogLevelEnum = exports.IInstantiationService = exports.ICharsetService = exports.ICoreService = exports.IMouseStateService = exports.IBufferService = void 0;
const ServiceRegistry_1 = require("common/services/ServiceRegistry");
exports.IBufferService = (0, ServiceRegistry_1.createDecorator)('BufferService');
exports.IMouseStateService = (0, ServiceRegistry_1.createDecorator)('MouseStateService');
exports.ICoreService = (0, ServiceRegistry_1.createDecorator)('CoreService');
exports.ICharsetService = (0, ServiceRegistry_1.createDecorator)('CharsetService');
exports.IInstantiationService = (0, ServiceRegistry_1.createDecorator)('InstantiationService');
var LogLevelEnum;
(function (LogLevelEnum) {
LogLevelEnum[LogLevelEnum["TRACE"] = 0] = "TRACE";
LogLevelEnum[LogLevelEnum["DEBUG"] = 1] = "DEBUG";
LogLevelEnum[LogLevelEnum["INFO"] = 2] = "INFO";
LogLevelEnum[LogLevelEnum["WARN"] = 3] = "WARN";
LogLevelEnum[LogLevelEnum["ERROR"] = 4] = "ERROR";
LogLevelEnum[LogLevelEnum["OFF"] = 5] = "OFF";
})(LogLevelEnum || (exports.LogLevelEnum = LogLevelEnum = {}));
exports.ILogService = (0, ServiceRegistry_1.createDecorator)('LogService');
exports.IOptionsService = (0, ServiceRegistry_1.createDecorator)('OptionsService');
exports.IOscLinkService = (0, ServiceRegistry_1.createDecorator)('OscLinkService');
exports.IUnicodeService = (0, ServiceRegistry_1.createDecorator)('UnicodeService');
exports.IDecorationService = (0, ServiceRegistry_1.createDecorator)('DecorationService');
//# sourceMappingURL=Services.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Services.js","sourceRoot":"","sources":["Services.ts"],"names":[],"mappings":";;;AAQA,qEAAkE;AAGrD,QAAA,cAAc,GAAG,IAAA,iCAAe,EAAiB,eAAe,CAAC,CAAC;AAwBlE,QAAA,kBAAkB,GAAG,IAAA,iCAAe,EAAqB,mBAAmB,CAAC,CAAC;AAuB9E,QAAA,YAAY,GAAG,IAAA,iCAAe,EAAe,aAAa,CAAC,CAAC;AAuC5D,QAAA,eAAe,GAAG,IAAA,iCAAe,EAAkB,gBAAgB,CAAC,CAAC;AAsCrE,QAAA,qBAAqB,GAAG,IAAA,iCAAe,EAAwB,sBAAsB,CAAC,CAAC;AASpG,IAAY,YAOX;AAPD,WAAY,YAAY;IACtB,iDAAS,CAAA;IACT,iDAAS,CAAA;IACT,+CAAQ,CAAA;IACR,+CAAQ,CAAA;IACR,iDAAS,CAAA;IACT,6CAAO,CAAA;AACT,CAAC,EAPW,YAAY,aAAZ,YAAY,GAAZ,YAAY,QAOvB;AAEY,QAAA,WAAW,GAAG,IAAA,iCAAe,EAAc,YAAY,CAAC,CAAC;AAazD,QAAA,eAAe,GAAG,IAAA,iCAAe,EAAkB,gBAAgB,CAAC,CAAC;AAgJrE,QAAA,eAAe,GAAG,IAAA,iCAAe,EAAkB,gBAAgB,CAAC,CAAC;AAuCrE,QAAA,eAAe,GAAG,IAAA,iCAAe,EAAkB,gBAAgB,CAAC,CAAC;AA+BrE,QAAA,kBAAkB,GAAG,IAAA,iCAAe,EAAqB,mBAAmB,CAAC,CAAC"}
+2 -2
View File
@@ -4,10 +4,10 @@
*/
import type { IDecoration, IDecorationOptions, ILinkHandler, ILogger, IWindowsPty, IOverviewRulerOptions } from '@xterm/xterm';
import { CoreMouseEncoding, CoreMouseEventType, CursorInactiveStyle, CursorStyle, IAttributeData, ICharset, IColor, ICoreMouseEvent, ICoreMouseProtocol, IDecPrivateModes, IDisposable, IKittyKeyboardState, IModes, IOscLinkData, IWindowOptions } from 'common/Types';
import { CoreMouseEncoding, CoreMouseEventType, CursorInactiveStyle, CursorStyle, IAttributeData, ICharset, IColor, ICoreMouseEvent, ICoreMouseProtocol, IDecPrivateModes, IDisposable, IKittyKeyboardState, IModes, IOscLinkData, IWindowOptions } from 'common/services/Types';
import { IBuffer, IBufferSet } from 'common/buffer/Types';
import { createDecorator } from 'common/services/ServiceRegistry';
import type { Emitter, IEvent } from 'common/Event';
import type { Emitter, IEvent } from 'common/base/Event';
export const IBufferService = createDecorator<IBufferService>('BufferService');
export interface IBufferService {
+122
View File
@@ -0,0 +1,122 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import { SortedList } from 'common/services/SortedList';
import { MockLogService } from 'common/terminal/TestUtils.test';
const deepStrictEqual = assert.deepStrictEqual;
describe('SortedList', () => {
let list: SortedList<number>;
function assertList(expected: number[]): void {
deepStrictEqual(Array.from(list.values()), expected);
}
beforeEach(() => {
list = new SortedList<number>(e => e, new MockLogService());
});
describe('insert', () => {
it('should maintain sorted values', () => {
list.insert(10);
assertList([10]);
list.insert(8);
assertList([8, 10]);
list.insert(15);
assertList([8, 10, 15]);
list.insert(2);
assertList([2, 8, 10, 15]);
list.insert(1);
assertList([1, 2, 8, 10, 15]);
list.insert(6);
assertList([1, 2, 6, 8, 10, 15]);
});
it('should allow duplicates of the same key', () => {
list.insert(5);
assertList([5]);
list.insert(5);
assertList([5, 5]);
list.insert(8);
assertList([5, 5, 8]);
list.insert(5);
assertList([5, 5, 5, 8]);
list.insert(8);
assertList([5, 5, 5, 8, 8]);
list.insert(6);
assertList([5, 5, 5, 6, 8, 8]);
});
});
it('delete', () => {
list.insert(1);
list.insert(2);
list.insert(4);
list.insert(3);
list.insert(5);
assertList([1, 2, 3, 4, 5]);
list.delete(1);
assertList([2, 3, 4, 5]);
list.delete(3);
assertList([2, 4, 5]);
list.delete(4);
assertList([2, 5]);
list.delete(5);
assertList([2]);
list.delete(2);
assertList([]);
});
it('getKeyIterator', () => {
list.insert(5);
list.insert(5);
list.insert(8);
list.insert(5);
list.insert(8);
list.insert(6);
assertList([5, 5, 5, 6, 8, 8]);
deepStrictEqual(Array.from(list.getKeyIterator(1)), []);
deepStrictEqual(Array.from(list.getKeyIterator(5)), [5, 5, 5]);
deepStrictEqual(Array.from(list.getKeyIterator(6)), [6]);
deepStrictEqual(Array.from(list.getKeyIterator(8)), [8, 8]);
deepStrictEqual(Array.from(list.getKeyIterator(9)), []);
});
it('clear', () => {
list.insert(1);
list.insert(2);
list.insert(4);
list.insert(3);
list.insert(5);
list.clear();
assertList([]);
});
it('custom key', () => {
const customList = new SortedList<{ key: number }>(e => e.key, new MockLogService());
customList.insert({ key: 5 });
customList.insert({ key: 2 });
customList.insert({ key: 10 });
customList.insert({ key: 5 });
customList.insert({ key: 6 });
deepStrictEqual(Array.from(customList.values()), [
{ key: 2 },
{ key: 5 },
{ key: 5 },
{ key: 6 },
{ key: 10 }
]);
});
describe('values', () => {
it('should iterate correctly when list items change during iteration', () => {
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
const visited: number[] = [];
for (const item of list.values()) {
visited.push(item);
list.delete(item);
}
deepStrictEqual(visited, [1, 2, 3, 4]);
});
});
});
+198
View File
@@ -0,0 +1,198 @@
/**
* Copyright (c) 2022 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { IdleTaskQueue } from 'common/services/TaskQueue';
import type { ILogService } from 'common/services/Services';
// Work variables to avoid garbage collection.
let i = 0;
/**
* A generic list that is maintained in sorted order and allows values with duplicate keys. Deferred
* batch insertion and deletion is used to significantly reduce the time it takes to insert and
* delete a large amount of items in succession. This list is based on binary search and as such
* locating a key will take O(log n) amortized, this includes the by key iterator.
*/
export class SortedList<T> {
private _array: T[] = [];
private readonly _insertedValues: T[] = [];
private readonly _flushInsertedTask: InstanceType<typeof IdleTaskQueue>;
private _isFlushingInserted = false;
private readonly _deletedIndices: number[] = [];
private readonly _flushDeletedTask: InstanceType<typeof IdleTaskQueue>;
private _isFlushingDeleted = false;
constructor(
private readonly _getKey: (value: T) => number,
logService: ILogService
) {
this._flushInsertedTask = new IdleTaskQueue(logService);
this._flushDeletedTask = new IdleTaskQueue(logService);
}
public clear(): void {
this._array.length = 0;
this._insertedValues.length = 0;
this._flushInsertedTask.clear();
this._isFlushingInserted = false;
this._deletedIndices.length = 0;
this._flushDeletedTask.clear();
this._isFlushingDeleted = false;
}
public insert(value: T): void {
this._flushCleanupDeleted();
if (this._insertedValues.length === 0) {
this._flushInsertedTask.enqueue(() => this._flushInserted());
}
this._insertedValues.push(value);
}
private _flushInserted(): void {
const sortedAddedValues = this._insertedValues.sort((a, b) => this._getKey(a) - this._getKey(b));
let sortedAddedValuesIndex = 0;
let arrayIndex = 0;
const newArray = new Array(this._array.length + this._insertedValues.length);
for (let newArrayIndex = 0; newArrayIndex < newArray.length; newArrayIndex++) {
if (arrayIndex >= this._array.length || this._getKey(sortedAddedValues[sortedAddedValuesIndex]) <= this._getKey(this._array[arrayIndex])) {
newArray[newArrayIndex] = sortedAddedValues[sortedAddedValuesIndex];
sortedAddedValuesIndex++;
} else {
newArray[newArrayIndex] = this._array[arrayIndex++];
}
}
this._array = newArray;
this._insertedValues.length = 0;
}
private _flushCleanupInserted(): void {
if (!this._isFlushingInserted && this._insertedValues.length > 0) {
this._flushInsertedTask.flush();
}
}
public delete(value: T): boolean {
this._flushCleanupInserted();
if (this._array.length === 0) {
return false;
}
const key = this._getKey(value);
if (key === undefined) {
return false;
}
i = this._search(key);
if (i === -1) {
return false;
}
if (this._getKey(this._array[i]) !== key) {
return false;
}
do {
if (this._array[i] === value) {
if (this._deletedIndices.length === 0) {
this._flushDeletedTask.enqueue(() => this._flushDeleted());
}
this._deletedIndices.push(i);
return true;
}
} while (++i < this._array.length && this._getKey(this._array[i]) === key);
return false;
}
private _flushDeleted(): void {
this._isFlushingDeleted = true;
const sortedDeletedIndices = this._deletedIndices.sort((a, b) => a - b);
let sortedDeletedIndicesIndex = 0;
const newArray = new Array(this._array.length - sortedDeletedIndices.length);
let newArrayIndex = 0;
for (let i = 0; i < this._array.length; i++) {
if (sortedDeletedIndices[sortedDeletedIndicesIndex] === i) {
sortedDeletedIndicesIndex++;
} else {
newArray[newArrayIndex++] = this._array[i];
}
}
this._array = newArray;
this._deletedIndices.length = 0;
this._isFlushingDeleted = false;
}
private _flushCleanupDeleted(): void {
if (!this._isFlushingDeleted && this._deletedIndices.length > 0) {
this._flushDeletedTask.flush();
}
}
public *getKeyIterator(key: number): IterableIterator<T> {
this._flushCleanupInserted();
this._flushCleanupDeleted();
if (this._array.length === 0) {
return;
}
i = this._search(key);
if (i < 0 || i >= this._array.length) {
return;
}
if (this._getKey(this._array[i]) !== key) {
return;
}
do {
yield this._array[i];
} while (++i < this._array.length && this._getKey(this._array[i]) === key);
}
public forEachByKey(key: number, callback: (value: T) => void): void {
this._flushCleanupInserted();
this._flushCleanupDeleted();
if (this._array.length === 0) {
return;
}
i = this._search(key);
if (i < 0 || i >= this._array.length) {
return;
}
if (this._getKey(this._array[i]) !== key) {
return;
}
do {
callback(this._array[i]);
} while (++i < this._array.length && this._getKey(this._array[i]) === key);
}
public values(): IterableIterator<T> {
this._flushCleanupInserted();
this._flushCleanupDeleted();
// Duplicate the array to avoid issues when _array changes while iterating
return [...this._array].values();
}
private _search(key: number): number {
let min = 0;
let max = this._array.length - 1;
while (max >= min) {
let mid = (min + max) >> 1;
const midKey = this._getKey(this._array[mid]);
if (midKey > key) {
max = mid - 1;
} else if (midKey < key) {
min = mid + 1;
} else {
// key in list, walk to lowest duplicate
while (mid > 0 && this._getKey(this._array[mid - 1]) === key) {
mid--;
}
return mid;
}
}
// key not in list
// still return closest min (also used as insert position)
return min;
}
}
+43
View File
@@ -0,0 +1,43 @@
import type { ILogService } from 'common/services/Services';
interface ITaskQueue {
enqueue(task: () => boolean | void): void;
flush(): void;
clear(): void;
}
interface ITaskDeadline {
timeRemaining(): number;
}
type CallbackWithDeadline = (deadline: ITaskDeadline) => void;
declare abstract class TaskQueue implements ITaskQueue {
private _tasks;
private _idleCallback?;
private _i;
protected readonly _logService: ILogService;
constructor(logService: ILogService);
protected abstract _requestCallback(callback: CallbackWithDeadline): number;
protected abstract _cancelCallback(identifier: number): void;
enqueue(task: () => boolean | void): void;
flush(): void;
clear(): void;
private _start;
private _process;
}
export declare class PriorityTaskQueue extends TaskQueue {
protected _requestCallback(callback: CallbackWithDeadline): number;
protected _cancelCallback(identifier: number): void;
private _createDeadline;
}
declare class IdleTaskQueueInternal extends TaskQueue {
protected _requestCallback(callback: IdleRequestCallback): number;
protected _cancelCallback(identifier: number): void;
}
export declare const IdleTaskQueue: typeof PriorityTaskQueue | typeof IdleTaskQueueInternal;
export declare class DebouncedIdleTask {
private _queue;
constructor(logService: ILogService);
set(task: () => boolean | void): void;
flush(): void;
dispose(): void;
}
export {};
//# sourceMappingURL=TaskQueue.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"TaskQueue.d.ts","sourceRoot":"","sources":["TaskQueue.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAE5D,UAAU,UAAU;IAOlB,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,GAAG,IAAI,GAAG,IAAI,CAAC;IAK1C,KAAK,IAAI,IAAI,CAAC;IAKd,KAAK,IAAI,IAAI,CAAC;CACf;AAED,UAAU,aAAa;IACrB,aAAa,IAAI,MAAM,CAAC;CACzB;AACD,KAAK,oBAAoB,GAAG,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,CAAC;AAE9D,uBAAe,SAAU,YAAW,UAAU;IAC5C,OAAO,CAAC,MAAM,CAAgC;IAC9C,OAAO,CAAC,aAAa,CAAC,CAAS;IAC/B,OAAO,CAAC,EAAE,CAAK;IACf,SAAS,CAAC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAE5C,YAAY,UAAU,EAAE,WAAW,EAElC;IAED,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,CAAC;IAC5E,SAAS,CAAC,QAAQ,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAEtD,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,GAAG,IAAI,GAAG,IAAI,CAG/C;IAEM,KAAK,IAAI,IAAI,CAOnB;IAEM,KAAK,IAAI,IAAI,CAOnB;IAED,OAAO,CAAC,MAAM;IAMd,OAAO,CAAC,QAAQ;CAgCjB;AAOD,qBAAa,iBAAkB,SAAQ,SAAS;IAC9C,SAAS,CAAC,gBAAgB,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,CAEjE;IAED,SAAS,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAElD;IAED,OAAO,CAAC,eAAe;CAMxB;AAED,cAAM,qBAAsB,SAAQ,SAAS;IAC3C,SAAS,CAAC,gBAAgB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,MAAM,CAEhE;IAED,SAAS,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAElD;CACF;AAWD,eAAO,MAAM,aAAa,yDAAoF,CAAC;AAM/G,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,MAAM,CAAa;IAE3B,YAAY,UAAU,EAAE,WAAW,EAElC;IAEM,GAAG,CAAC,IAAI,EAAE,MAAM,OAAO,GAAG,IAAI,GAAG,IAAI,CAG3C;IAEM,KAAK,IAAI,IAAI,CAEnB;IAEM,OAAO,IAAI,IAAI,CAErB;CACF"}
+101
View File
@@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DebouncedIdleTask = exports.IdleTaskQueue = exports.PriorityTaskQueue = void 0;
class TaskQueue {
constructor(logService) {
this._tasks = [];
this._i = 0;
this._logService = logService;
}
enqueue(task) {
this._tasks.push(task);
this._start();
}
flush() {
while (this._i < this._tasks.length) {
if (!this._tasks[this._i]()) {
this._i++;
}
}
this.clear();
}
clear() {
if (this._idleCallback) {
this._cancelCallback(this._idleCallback);
this._idleCallback = undefined;
}
this._i = 0;
this._tasks.length = 0;
}
_start() {
if (!this._idleCallback) {
this._idleCallback = this._requestCallback(this._process.bind(this));
}
}
_process(deadline) {
this._idleCallback = undefined;
let taskDuration;
let longestTask = 0;
let lastDeadlineRemaining = deadline.timeRemaining();
let deadlineRemaining;
while (this._i < this._tasks.length) {
taskDuration = performance.now();
if (!this._tasks[this._i]()) {
this._i++;
}
taskDuration = Math.max(1, performance.now() - taskDuration);
longestTask = Math.max(taskDuration, longestTask);
deadlineRemaining = deadline.timeRemaining();
if (longestTask * 1.5 > deadlineRemaining) {
if (lastDeadlineRemaining - taskDuration < -20) {
this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(lastDeadlineRemaining - taskDuration))}ms`);
}
this._start();
return;
}
lastDeadlineRemaining = deadlineRemaining;
}
this.clear();
}
}
class PriorityTaskQueue extends TaskQueue {
_requestCallback(callback) {
return setTimeout(() => callback(this._createDeadline(16)));
}
_cancelCallback(identifier) {
clearTimeout(identifier);
}
_createDeadline(duration) {
const end = performance.now() + duration;
return {
timeRemaining: () => Math.max(0, end - performance.now())
};
}
}
exports.PriorityTaskQueue = PriorityTaskQueue;
class IdleTaskQueueInternal extends TaskQueue {
_requestCallback(callback) {
return requestIdleCallback(callback);
}
_cancelCallback(identifier) {
cancelIdleCallback(identifier);
}
}
exports.IdleTaskQueue = ('requestIdleCallback' in globalThis) ? IdleTaskQueueInternal : PriorityTaskQueue;
class DebouncedIdleTask {
constructor(logService) {
this._queue = new exports.IdleTaskQueue(logService);
}
set(task) {
this._queue.clear();
this._queue.enqueue(task);
}
flush() {
this._queue.flush();
}
dispose() {
this._queue.clear();
}
}
exports.DebouncedIdleTask = DebouncedIdleTask;
//# sourceMappingURL=TaskQueue.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"TaskQueue.js","sourceRoot":"","sources":["TaskQueue.ts"],"names":[],"mappings":";;;AAgCA,MAAe,SAAS;IAMtB,YAAY,UAAuB;QAL3B,WAAM,GAA6B,EAAE,CAAC;QAEtC,OAAE,GAAG,CAAC,CAAC;QAIb,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;IAChC,CAAC;IAKM,OAAO,CAAC,IAA0B;QACvC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,MAAM,EAAE,CAAC;IAChB,CAAC;IAEM,KAAK;QACV,OAAO,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;YACpC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC5B,IAAI,CAAC,EAAE,EAAE,CAAC;YACZ,CAAC;QACH,CAAC;QACD,IAAI,CAAC,KAAK,EAAE,CAAC;IACf,CAAC;IAEM,KAAK;QACV,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YACzC,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC;QACjC,CAAC;QACD,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC;QACZ,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;IAEO,MAAM;QACZ,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;IAEO,QAAQ,CAAC,QAAuB;QACtC,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC;QAC/B,IAAI,YAAoB,CAAC;QACzB,IAAI,WAAW,GAAG,CAAC,CAAC;QACpB,IAAI,qBAAqB,GAAG,QAAQ,CAAC,aAAa,EAAE,CAAC;QACrD,IAAI,iBAAyB,CAAC;QAC9B,OAAO,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;YACpC,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC5B,IAAI,CAAC,EAAE,EAAE,CAAC;YACZ,CAAC;YAID,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,YAAY,CAAC,CAAC;YAC7D,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC;YAGlD,iBAAiB,GAAG,QAAQ,CAAC,aAAa,EAAE,CAAC;YAC7C,IAAI,WAAW,GAAG,GAAG,GAAG,iBAAiB,EAAE,CAAC;gBAG1C,IAAI,qBAAqB,GAAG,YAAY,GAAG,CAAC,EAAE,EAAE,CAAC;oBAC/C,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,4CAA4C,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,qBAAqB,GAAG,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC;gBACpI,CAAC;gBACD,IAAI,CAAC,MAAM,EAAE,CAAC;gBACd,OAAO;YACT,CAAC;YACD,qBAAqB,GAAG,iBAAiB,CAAC;QAC5C,CAAC;QACD,IAAI,CAAC,KAAK,EAAE,CAAC;IACf,CAAC;CACF;AAOD,uBAA+B,SAAQ,SAAS;IACpC,gBAAgB,CAAC,QAA8B;QACvD,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC9D,CAAC;IAES,eAAe,CAAC,UAAkB;QAC1C,YAAY,CAAC,UAAU,CAAC,CAAC;IAC3B,CAAC;IAEO,eAAe,CAAC,QAAgB;QACtC,MAAM,GAAG,GAAG,WAAW,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC;QACzC,OAAO;YACL,aAAa,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;SAC1D,CAAC;IACJ,CAAC;CACF;;AAED,MAAM,qBAAsB,SAAQ,SAAS;IACjC,gBAAgB,CAAC,QAA6B;QACtD,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACvC,CAAC;IAES,eAAe,CAAC,UAAkB;QAC1C,kBAAkB,CAAC,UAAU,CAAC,CAAC;IACjC,CAAC;CACF;AAWY,QAAA,aAAa,GAAG,CAAC,qBAAqB,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,iBAAiB,CAAC;AAM/G;IAGE,YAAY,UAAuB;QACjC,IAAI,CAAC,MAAM,GAAG,IAAI,QAAA,aAAa,CAAC,UAAU,CAAC,CAAC;IAC9C,CAAC;IAEM,GAAG,CAAC,IAA0B;QACnC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACpB,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACF"}
+175
View File
@@ -0,0 +1,175 @@
/**
* Copyright (c) 2022 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { ILogService } from 'common/services/Services';
interface ITaskQueue {
/**
* Adds a task to the queue which will run in a future idle callback.
* To avoid perceivable stalls on the mainthread, tasks with heavy workload
* should split their work into smaller pieces and return `true` to get
* called again until the work is done (on falsy return value).
*/
enqueue(task: () => boolean | void): void;
/**
* Flushes the queue, running all remaining tasks synchronously.
*/
flush(): void;
/**
* Clears any remaining tasks from the queue, these will not be run.
*/
clear(): void;
}
interface ITaskDeadline {
timeRemaining(): number;
}
type CallbackWithDeadline = (deadline: ITaskDeadline) => void;
abstract class TaskQueue implements ITaskQueue {
private _tasks: (() => boolean | void)[] = [];
private _idleCallback?: number;
private _i = 0;
protected readonly _logService: ILogService;
constructor(logService: ILogService) {
this._logService = logService;
}
protected abstract _requestCallback(callback: CallbackWithDeadline): number;
protected abstract _cancelCallback(identifier: number): void;
public enqueue(task: () => boolean | void): void {
this._tasks.push(task);
this._start();
}
public flush(): void {
while (this._i < this._tasks.length) {
if (!this._tasks[this._i]()) {
this._i++;
}
}
this.clear();
}
public clear(): void {
if (this._idleCallback) {
this._cancelCallback(this._idleCallback);
this._idleCallback = undefined;
}
this._i = 0;
this._tasks.length = 0;
}
private _start(): void {
if (!this._idleCallback) {
this._idleCallback = this._requestCallback(this._process.bind(this));
}
}
private _process(deadline: ITaskDeadline): void {
this._idleCallback = undefined;
let taskDuration: number;
let longestTask = 0;
let lastDeadlineRemaining = deadline.timeRemaining();
let deadlineRemaining: number;
while (this._i < this._tasks.length) {
taskDuration = performance.now();
if (!this._tasks[this._i]()) {
this._i++;
}
// other than performance.now, performance.now might not be stable (changes on wall clock
// changes), this is not an issue here as a clock change during a short running task is very
// unlikely in case it still happened and leads to negative duration, simply assume 1 msec
taskDuration = Math.max(1, performance.now() - taskDuration);
longestTask = Math.max(taskDuration, longestTask);
// Guess the following task will take a similar time to the longest task in this batch, allow
// additional room to try avoid exceeding the deadline
deadlineRemaining = deadline.timeRemaining();
if (longestTask * 1.5 > deadlineRemaining) {
// Warn when the time exceeding the deadline is over 20ms, if this happens in practice the
// task should be split into sub-tasks to ensure the UI remains responsive.
if (lastDeadlineRemaining - taskDuration < -20) {
this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(lastDeadlineRemaining - taskDuration))}ms`);
}
this._start();
return;
}
lastDeadlineRemaining = deadlineRemaining;
}
this.clear();
}
}
/**
* A queue of that runs tasks over several tasks via setTimeout, trying to maintain above 60 frames
* per second. The tasks will run in the order they are enqueued, but they will run some time later,
* and care should be taken to ensure they're non-urgent and will not introduce race conditions.
*/
export class PriorityTaskQueue extends TaskQueue {
protected _requestCallback(callback: CallbackWithDeadline): number {
return setTimeout(() => callback(this._createDeadline(16)));
}
protected _cancelCallback(identifier: number): void {
clearTimeout(identifier);
}
private _createDeadline(duration: number): ITaskDeadline {
const end = performance.now() + duration;
return {
timeRemaining: () => Math.max(0, end - performance.now())
};
}
}
class IdleTaskQueueInternal extends TaskQueue {
protected _requestCallback(callback: IdleRequestCallback): number {
return requestIdleCallback(callback);
}
protected _cancelCallback(identifier: number): void {
cancelIdleCallback(identifier);
}
}
/**
* A queue of that runs tasks over several idle callbacks, trying to respect the idle callback's
* deadline given by the environment. The tasks will run in the order they are enqueued, but they
* will run some time later, and care should be taken to ensure they're non-urgent and will not
* introduce race conditions.
*
* This reverts to a {@link PriorityTaskQueue} if the environment does not support idle callbacks.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export const IdleTaskQueue = ('requestIdleCallback' in globalThis) ? IdleTaskQueueInternal : PriorityTaskQueue;
/**
* An object that tracks a single debounced task that will run on the next idle frame. When called
* multiple times, only the last set task will run.
*/
export class DebouncedIdleTask {
private _queue: ITaskQueue;
constructor(logService: ILogService) {
this._queue = new IdleTaskQueue(logService);
}
public set(task: () => boolean | void): void {
this._queue.clear();
this._queue.enqueue(task);
}
public flush(): void {
this._queue.flush();
}
public dispose(): void {
this._queue.clear();
}
}
+387
View File
@@ -0,0 +1,387 @@
import type { IDeleteEvent, IInsertEvent } from 'common/services/CircularList';
import type { UnderlineStyle } from 'common/buffer/Constants';
import type { IBufferSet } from 'common/buffer/Types';
import type { IParams } from 'common/parser/Types';
import type { IMouseStateService, ICoreService, IOptionsService, IUnicodeService } from 'common/services/Services';
import { IFunctionIdentifier, ITerminalOptions as IPublicTerminalOptions } from '@xterm/xterm';
import type { Emitter, IEvent } from 'common/base/Event';
export type { ICharset } from 'common/data/Charsets';
export interface ICoreTerminal {
mouseStateService: IMouseStateService;
coreService: ICoreService;
optionsService: IOptionsService;
unicodeService: IUnicodeService;
buffers: IBufferSet;
options: Required<ITerminalOptions>;
registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable;
registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable;
registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable;
registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
registerApcHandler(id: IFunctionIdentifier, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
}
export interface IDisposable {
dispose(): void;
}
export interface ITerminalOptions extends IPublicTerminalOptions {
[key: string]: any;
convertEol?: boolean;
termName?: string;
}
export type CursorStyle = 'block' | 'underline' | 'bar';
export type CursorInactiveStyle = 'outline' | 'block' | 'bar' | 'underline' | 'none';
export type XtermListener = (...args: any[]) => void;
export interface IKeyboardEvent {
altKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
metaKey: boolean;
keyCode: number;
key: string;
type: string;
code: string;
}
export interface IScrollEvent {
position: number;
}
export interface ICircularList<T> {
length: number;
maxLength: number;
isFull: boolean;
onDeleteEmitter: Emitter<IDeleteEvent>;
onDelete: IEvent<IDeleteEvent>;
onInsertEmitter: Emitter<IInsertEvent>;
onInsert: IEvent<IInsertEvent>;
onTrimEmitter: Emitter<number>;
onTrim: IEvent<number>;
get(index: number): T | undefined;
set(index: number, value: T): void;
push(value: T): void;
recycle(): T;
pop(): T | undefined;
splice(start: number, deleteCount: number, ...items: T[]): void;
trimStart(count: number): void;
shiftElements(start: number, count: number, offset: number): void;
}
export declare const enum KeyboardResultType {
SEND_KEY = 0,
SELECT_ALL = 1,
PAGE_UP = 2,
PAGE_DOWN = 3
}
export interface IKeyboardResult {
type: KeyboardResultType;
cancel: boolean;
key: string | undefined;
}
export type CharData = [attr: number, char: string, width: number, code: number];
export interface IColor {
readonly css: string;
readonly rgba: number;
}
export type IColorRGB = [red: number, green: number, blue: number];
export interface IExtendedAttrs {
ext: number;
underlineStyle: UnderlineStyle;
underlineColor: number;
underlineVariantOffset: number;
urlId: number;
clone(): IExtendedAttrs;
isEmpty(): boolean;
}
export interface IOscLinkData {
id?: string;
uri: string;
}
export interface IAttributeData {
fg: number;
bg: number;
extended: IExtendedAttrs;
clone(): IAttributeData;
isInverse(): number;
isBold(): number;
isUnderline(): number;
isBlink(): number;
isInvisible(): number;
isItalic(): number;
isDim(): number;
isStrikethrough(): number;
isProtected(): number;
isOverline(): number;
getFgColorMode(): number;
getBgColorMode(): number;
isFgRGB(): boolean;
isBgRGB(): boolean;
isFgPalette(): boolean;
isBgPalette(): boolean;
isFgDefault(): boolean;
isBgDefault(): boolean;
isAttributeDefault(): boolean;
getFgColor(): number;
getBgColor(): number;
hasExtendedAttrs(): number;
updateExtended(): void;
getUnderlineColor(): number;
getUnderlineColorMode(): number;
isUnderlineColorRGB(): boolean;
isUnderlineColorPalette(): boolean;
isUnderlineColorDefault(): boolean;
getUnderlineStyle(): number;
getUnderlineVariantOffset(): number;
}
export interface ICellData extends IAttributeData {
content: number;
combinedData: string;
isCombined(): number;
getWidth(): number;
getChars(): string;
getCode(): number;
setFromCharData(value: CharData): void;
getAsCharData(): CharData;
}
export interface IBufferLine {
length: number;
isWrapped: boolean;
get(index: number): CharData;
set(index: number, value: CharData): void;
loadCell(index: number, cell: ICellData): ICellData;
setCell(index: number, cell: ICellData): void;
setCellFromCodepoint(index: number, codePoint: number, width: number, attrs: IAttributeData): void;
addCodepointToCell(index: number, codePoint: number, width: number): void;
insertCells(pos: number, n: number, ch: ICellData): void;
deleteCells(pos: number, n: number, fill: ICellData): void;
replaceCells(start: number, end: number, fill: ICellData, respectProtect?: boolean): void;
resize(cols: number, fill: ICellData): boolean;
cleanupMemory(): number;
fill(fillCellData: ICellData, respectProtect?: boolean): void;
copyFrom(line: IBufferLine): void;
clone(): IBufferLine;
getTrimmedLength(): number;
getNoBgTrimmedLength(): number;
translateToString(trimRight?: boolean, startCol?: number, endCol?: number, outColumns?: number[]): string;
getWidth(index: number): number;
hasWidth(index: number): number;
getFg(index: number): number;
getBg(index: number): number;
hasContent(index: number): number;
getCodePoint(index: number): number;
isCombined(index: number): number;
getString(index: number): string;
}
export interface IMarker extends IDisposable {
readonly id: number;
readonly isDisposed: boolean;
readonly line: number;
onDispose: IEvent<void>;
}
export interface IModes {
insertMode: boolean;
}
export interface IDecPrivateModes {
applicationCursorKeys: boolean;
applicationKeypad: boolean;
bracketedPasteMode: boolean;
colorSchemeUpdates: boolean;
cursorBlink: boolean | undefined;
cursorStyle: CursorStyle | undefined;
origin: boolean;
reverseWraparound: boolean;
sendFocus: boolean;
synchronizedOutput: boolean;
win32InputMode: boolean;
wraparound: boolean;
}
export interface IKittyKeyboardState {
flags: number;
mainFlags: number;
altFlags: number;
mainStack: number[];
altStack: number[];
}
export interface IRowRange {
start: number;
end: number;
}
export declare const enum CoreMouseButton {
LEFT = 0,
MIDDLE = 1,
RIGHT = 2,
NONE = 3,
WHEEL = 4,
AUX1 = 8,
AUX2 = 9,
AUX3 = 10,
AUX4 = 11,
AUX5 = 12,
AUX6 = 13,
AUX7 = 14,
AUX8 = 15
}
export declare const enum CoreMouseAction {
UP = 0,
DOWN = 1,
LEFT = 2,
RIGHT = 3,
MOVE = 32
}
export interface ICoreMouseEvent {
col: number;
row: number;
x: number;
y: number;
button: CoreMouseButton;
action: CoreMouseAction;
ctrl?: boolean;
alt?: boolean;
shift?: boolean;
}
export declare const enum CoreMouseEventType {
NONE = 0,
DOWN = 1,
UP = 2,
DRAG = 4,
MOVE = 8,
WHEEL = 16
}
export interface ICoreMouseProtocol {
events: CoreMouseEventType;
restrict: (e: ICoreMouseEvent) => boolean;
}
export type CoreMouseEncoding = (event: ICoreMouseEvent) => string;
export interface IWindowOptions {
restoreWin?: boolean;
minimizeWin?: boolean;
setWinPosition?: boolean;
setWinSizePixels?: boolean;
raiseWin?: boolean;
lowerWin?: boolean;
refreshWin?: boolean;
setWinSizeChars?: boolean;
maximizeWin?: boolean;
fullscreenWin?: boolean;
getWinState?: boolean;
getWinPosition?: boolean;
getWinSizePixels?: boolean;
getScreenSizePixels?: boolean;
getCellSizePixels?: boolean;
getWinSizeChars?: boolean;
getScreenSizeChars?: boolean;
getIconTitle?: boolean;
getWinTitle?: boolean;
pushTitle?: boolean;
popTitle?: boolean;
setWinLines?: boolean;
}
export declare const enum ColorRequestType {
REPORT = 0,
SET = 1,
RESTORE = 2
}
type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N ? Acc[number] : Enumerate<N, [...Acc, Acc['length']]>;
type IntRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
export type ColorIndex = IntRange<0, 256>;
export type AllColorIndex = ColorIndex | SpecialColorIndex;
export declare const enum SpecialColorIndex {
FOREGROUND = 256,
BACKGROUND = 257,
CURSOR = 258
}
export interface IColorReportRequest {
type: ColorRequestType.REPORT;
index: AllColorIndex;
}
export interface IColorSetRequest {
type: ColorRequestType.SET;
index: AllColorIndex;
color: IColorRGB;
}
export interface IColorRestoreRequest {
type: ColorRequestType.RESTORE;
index?: AllColorIndex;
}
export type IColorEvent = (IColorReportRequest | IColorSetRequest | IColorRestoreRequest)[];
export interface IInputHandler {
onTitleChange: IEvent<string>;
parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise<boolean>;
print(data: Uint32Array, start: number, end: number): void;
registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable;
registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable;
registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable;
registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
registerApcHandler(id: IFunctionIdentifier, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
bell(): boolean;
lineFeed(): boolean;
carriageReturn(): boolean;
backspace(): boolean;
tab(): boolean;
shiftOut(): boolean;
shiftIn(): boolean;
insertChars(params: IParams): boolean;
scrollLeft(params: IParams): boolean;
cursorUp(params: IParams): boolean;
scrollRight(params: IParams): boolean;
cursorDown(params: IParams): boolean;
cursorForward(params: IParams): boolean;
cursorBackward(params: IParams): boolean;
cursorNextLine(params: IParams): boolean;
cursorPrecedingLine(params: IParams): boolean;
cursorCharAbsolute(params: IParams): boolean;
cursorPosition(params: IParams): boolean;
cursorForwardTab(params: IParams): boolean;
eraseInDisplay(params: IParams): boolean;
eraseInLine(params: IParams): boolean;
insertLines(params: IParams): boolean;
deleteLines(params: IParams): boolean;
deleteChars(params: IParams): boolean;
scrollUp(params: IParams): boolean;
scrollDown(params: IParams, collect?: string): boolean;
eraseChars(params: IParams): boolean;
cursorBackwardTab(params: IParams): boolean;
charPosAbsolute(params: IParams): boolean;
hPositionRelative(params: IParams): boolean;
repeatPrecedingCharacter(params: IParams): boolean;
sendDeviceAttributesPrimary(params: IParams): boolean;
sendDeviceAttributesSecondary(params: IParams): boolean;
linePosAbsolute(params: IParams): boolean;
vPositionRelative(params: IParams): boolean;
hVPosition(params: IParams): boolean;
tabClear(params: IParams): boolean;
setMode(params: IParams, collect?: string): boolean;
resetMode(params: IParams, collect?: string): boolean;
charAttributes(params: IParams): boolean;
deviceStatus(params: IParams, collect?: string): boolean;
softReset(params: IParams, collect?: string): boolean;
setCursorStyle(params: IParams, collect?: string): boolean;
setScrollRegion(params: IParams, collect?: string): boolean;
saveCursor(params: IParams): boolean;
restoreCursor(params: IParams): boolean;
insertColumns(params: IParams): boolean;
deleteColumns(params: IParams): boolean;
setTitle(data: string): boolean;
setOrReportIndexedColor(data: string): boolean;
setOrReportFgColor(data: string): boolean;
setOrReportBgColor(data: string): boolean;
setOrReportCursorColor(data: string): boolean;
restoreIndexedColor(data: string): boolean;
restoreFgColor(data: string): boolean;
restoreBgColor(data: string): boolean;
restoreCursorColor(data: string): boolean;
nextLine(): boolean;
keypadApplicationMode(): boolean;
keypadNumericMode(): boolean;
selectDefaultCharset(): boolean;
selectCharset(collectAndFlag: string): boolean;
index(): boolean;
tabSet(): boolean;
reverseIndex(): boolean;
fullReset(): boolean;
setgLevel(level: number): boolean;
screenAlignmentPattern(): boolean;
}
export interface IParseStack {
paused: boolean;
cursorStartX: number;
cursorStartY: number;
decodedLength: number;
position: number;
}
//# sourceMappingURL=Types.d.ts.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=Types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Types.js","sourceRoot":"","sources":["Types.ts"],"names":[],"mappings":""}
+570
View File
@@ -0,0 +1,570 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { IDeleteEvent, IInsertEvent } from 'common/services/CircularList';
import type { UnderlineStyle } from 'common/buffer/Constants';
import type { IBufferSet } from 'common/buffer/Types';
import type { IParams } from 'common/parser/Types';
import type { IMouseStateService, ICoreService, IOptionsService, IUnicodeService } from 'common/services/Services';
import { IFunctionIdentifier, ITerminalOptions as IPublicTerminalOptions } from '@xterm/xterm';
import type { Emitter, IEvent } from 'common/base/Event';
export type { ICharset } from 'common/data/Charsets';
export interface ICoreTerminal {
mouseStateService: IMouseStateService;
coreService: ICoreService;
optionsService: IOptionsService;
unicodeService: IUnicodeService;
buffers: IBufferSet;
options: Required<ITerminalOptions>;
registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable;
registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable;
registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable;
registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
registerApcHandler(id: IFunctionIdentifier, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
}
export interface IDisposable {
dispose(): void;
}
// TODO: The options that are not in the public API should be reviewed
export interface ITerminalOptions extends IPublicTerminalOptions {
[key: string]: any;
convertEol?: boolean;
termName?: string;
}
export type CursorStyle = 'block' | 'underline' | 'bar';
export type CursorInactiveStyle = 'outline' | 'block' | 'bar' | 'underline' | 'none';
export type XtermListener = (...args: any[]) => void;
/**
* A keyboard event interface which does not depend on the DOM, KeyboardEvent implicitly extends
* this event.
*/
export interface IKeyboardEvent {
altKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
metaKey: boolean;
/** @deprecated See KeyboardEvent.keyCode */
keyCode: number;
key: string;
type: string;
code: string;
}
export interface IScrollEvent {
position: number;
}
export interface ICircularList<T> {
length: number;
maxLength: number;
isFull: boolean;
onDeleteEmitter: Emitter<IDeleteEvent>;
onDelete: IEvent<IDeleteEvent>;
onInsertEmitter: Emitter<IInsertEvent>;
onInsert: IEvent<IInsertEvent>;
onTrimEmitter: Emitter<number>;
onTrim: IEvent<number>;
get(index: number): T | undefined;
set(index: number, value: T): void;
push(value: T): void;
recycle(): T;
pop(): T | undefined;
splice(start: number, deleteCount: number, ...items: T[]): void;
trimStart(count: number): void;
shiftElements(start: number, count: number, offset: number): void;
}
export const enum KeyboardResultType {
SEND_KEY,
SELECT_ALL,
PAGE_UP,
PAGE_DOWN
}
export interface IKeyboardResult {
type: KeyboardResultType;
cancel: boolean;
key: string | undefined;
}
export type CharData = [attr: number, char: string, width: number, code: number];
export interface IColor {
readonly css: string;
readonly rgba: number; // 32-bit int with rgba in each byte
}
export type IColorRGB = [red: number, green: number, blue: number];
export interface IExtendedAttrs {
ext: number;
underlineStyle: UnderlineStyle;
underlineColor: number;
underlineVariantOffset: number;
urlId: number;
clone(): IExtendedAttrs;
isEmpty(): boolean;
}
/**
* Tracks the current hyperlink. Since these are treated as extended attirbutes, these get passed on
* to the linkifier when anything is printed. Doing it this way ensures that even when the cursor
* moves around unexpectedly the link is tracked, as opposed to using a start position and
* finalizing it at the end.
*/
export interface IOscLinkData {
id?: string;
uri: string;
}
/**
* An object that represents all attributes of a cell.
*/
export interface IAttributeData {
/**
* "fg" is a 32-bit unsigned integer that stores the foreground color of the cell in the 24 least
* significant bits and additional flags in the remaining 8 bits.
*/
fg: number;
/**
* "bg" is a 32-bit unsigned integer that stores the background color of the cell in the 24 least
* significant bits and additional flags in the remaining 8 bits.
*/
bg: number;
/**
* "extended", aka "ext", stores extended attributes beyond those available in fg and bg. This
* data is optional on a cell and encodes less common data.
*/
extended: IExtendedAttrs;
clone(): IAttributeData;
// flags
isInverse(): number;
isBold(): number;
isUnderline(): number;
isBlink(): number;
isInvisible(): number;
isItalic(): number;
isDim(): number;
isStrikethrough(): number;
isProtected(): number;
isOverline(): number;
/**
* The color mode of the foreground color which determines how to decode {@link getFgColor},
* possible values include {@link Attributes.CM_DEFAULT}, {@link Attributes.CM_P16},
* {@link Attributes.CM_P256} and {@link Attributes.CM_RGB}.
*/
getFgColorMode(): number;
/**
* The color mode of the background color which determines how to decode {@link getBgColor},
* possible values include {@link Attributes.CM_DEFAULT}, {@link Attributes.CM_P16},
* {@link Attributes.CM_P256} and {@link Attributes.CM_RGB}.
*/
getBgColorMode(): number;
isFgRGB(): boolean;
isBgRGB(): boolean;
isFgPalette(): boolean;
isBgPalette(): boolean;
isFgDefault(): boolean;
isBgDefault(): boolean;
isAttributeDefault(): boolean;
/**
* Gets an integer representation of the foreground color, how to decode the color depends on the
* color mode {@link getFgColorMode}.
*/
getFgColor(): number;
/**
* Gets an integer representation of the background color, how to decode the color depends on the
* color mode {@link getBgColorMode}.
*/
getBgColor(): number;
// extended attrs
hasExtendedAttrs(): number;
updateExtended(): void;
getUnderlineColor(): number;
getUnderlineColorMode(): number;
isUnderlineColorRGB(): boolean;
isUnderlineColorPalette(): boolean;
isUnderlineColorDefault(): boolean;
getUnderlineStyle(): number;
getUnderlineVariantOffset(): number;
}
/** Cell data */
export interface ICellData extends IAttributeData {
content: number;
combinedData: string;
isCombined(): number;
getWidth(): number;
getChars(): string;
getCode(): number;
setFromCharData(value: CharData): void;
getAsCharData(): CharData;
}
/**
* Interface for a line in the terminal buffer.
*/
export interface IBufferLine {
length: number;
isWrapped: boolean;
get(index: number): CharData;
set(index: number, value: CharData): void;
loadCell(index: number, cell: ICellData): ICellData;
setCell(index: number, cell: ICellData): void;
setCellFromCodepoint(index: number, codePoint: number, width: number, attrs: IAttributeData): void;
addCodepointToCell(index: number, codePoint: number, width: number): void;
insertCells(pos: number, n: number, ch: ICellData): void;
deleteCells(pos: number, n: number, fill: ICellData): void;
replaceCells(start: number, end: number, fill: ICellData, respectProtect?: boolean): void;
resize(cols: number, fill: ICellData): boolean;
cleanupMemory(): number;
fill(fillCellData: ICellData, respectProtect?: boolean): void;
copyFrom(line: IBufferLine): void;
clone(): IBufferLine;
getTrimmedLength(): number;
getNoBgTrimmedLength(): number;
translateToString(trimRight?: boolean, startCol?: number, endCol?: number, outColumns?: number[]): string;
/* direct access to cell attrs */
getWidth(index: number): number;
hasWidth(index: number): number;
getFg(index: number): number;
getBg(index: number): number;
hasContent(index: number): number;
getCodePoint(index: number): number;
isCombined(index: number): number;
getString(index: number): string;
}
export interface IMarker extends IDisposable {
readonly id: number;
readonly isDisposed: boolean;
readonly line: number;
onDispose: IEvent<void>;
}
export interface IModes {
insertMode: boolean;
}
export interface IDecPrivateModes {
applicationCursorKeys: boolean;
applicationKeypad: boolean;
bracketedPasteMode: boolean;
colorSchemeUpdates: boolean;
cursorBlink: boolean | undefined;
cursorStyle: CursorStyle | undefined;
origin: boolean;
reverseWraparound: boolean;
sendFocus: boolean;
synchronizedOutput: boolean;
win32InputMode: boolean;
wraparound: boolean; // defaults: xterm - true, vt100 - false
}
/**
* Kitty keyboard protocol state.
* Maintains per-screen stacks of enhancement flags.
*/
export interface IKittyKeyboardState {
/** Current active enhancement flags (for current screen) */
flags: number;
/** Saved flags for main screen when alt is active */
mainFlags: number;
/** Saved flags for alternate screen when main is active */
altFlags: number;
/** Stack of flags for main screen */
mainStack: number[];
/** Stack of flags for alternate screen */
altStack: number[];
}
export interface IRowRange {
start: number;
end: number;
}
/**
* Interface for mouse events in the core.
*/
export const enum CoreMouseButton {
LEFT = 0,
MIDDLE = 1,
RIGHT = 2,
NONE = 3,
WHEEL = 4,
// additional buttons 1..8
// untested!
AUX1 = 8,
AUX2 = 9,
AUX3 = 10,
AUX4 = 11,
AUX5 = 12,
AUX6 = 13,
AUX7 = 14,
AUX8 = 15
}
export const enum CoreMouseAction {
UP = 0, // buttons, wheel
DOWN = 1, // buttons, wheel
LEFT = 2, // wheel only
RIGHT = 3, // wheel only
MOVE = 32 // buttons only
}
export interface ICoreMouseEvent {
/** column (zero based). */
col: number;
/** row (zero based). */
row: number;
/** xy pixel positions. */
x: number;
y: number;
/**
* Button the action occured. Due to restrictions of the tracking protocols
* it is not possible to report multiple buttons at once.
* Wheel is treated as a button.
* There are invalid combinations of buttons and actions possible
* (like move + wheel), those are silently ignored by the MouseStateService.
*/
button: CoreMouseButton;
action: CoreMouseAction;
/**
* Modifier states.
* Protocols will add/ignore those based on specific restrictions.
*/
ctrl?: boolean;
alt?: boolean;
shift?: boolean;
}
/**
* CoreMouseEventType
* To be reported to the browser component which events a mouse
* protocol wants to be catched and forwarded as an ICoreMouseEvent
* to MouseStateService.
*/
export const enum CoreMouseEventType {
NONE = 0,
/** any mousedown event */
DOWN = 1,
/** any mouseup event */
UP = 2,
/** any mousemove event while a button is held */
DRAG = 4,
/** any mousemove event without a button */
MOVE = 8,
/** any wheel event */
WHEEL = 16
}
/**
* Mouse protocol interface.
* A mouse protocol can be registered and activated at the MouseStateService.
* `events` should contain a list of needed events as a hint for the browser component
* to install/remove the appropriate event handlers.
* `restrict` applies further protocol specific restrictions like not allowed
* modifiers or filtering invalid event types.
*/
export interface ICoreMouseProtocol {
events: CoreMouseEventType;
restrict: (e: ICoreMouseEvent) => boolean;
}
/**
* CoreMouseEncoding
* The tracking encoding can be registered and activated at the MouseStateService.
* If a ICoreMouseEvent passes all procotol restrictions it will be encoded
* with the active encoding and sent out.
* Note: Returning an empty string will supress sending a mouse report,
* which can be used to skip creating falsey reports in limited encodings
* (DEFAULT only supports up to 223 1-based as coord value).
*/
export type CoreMouseEncoding = (event: ICoreMouseEvent) => string;
/**
* windowOptions
*/
export interface IWindowOptions {
restoreWin?: boolean;
minimizeWin?: boolean;
setWinPosition?: boolean;
setWinSizePixels?: boolean;
raiseWin?: boolean;
lowerWin?: boolean;
refreshWin?: boolean;
setWinSizeChars?: boolean;
maximizeWin?: boolean;
fullscreenWin?: boolean;
getWinState?: boolean;
getWinPosition?: boolean;
getWinSizePixels?: boolean;
getScreenSizePixels?: boolean;
getCellSizePixels?: boolean;
getWinSizeChars?: boolean;
getScreenSizeChars?: boolean;
getIconTitle?: boolean;
getWinTitle?: boolean;
pushTitle?: boolean;
popTitle?: boolean;
setWinLines?: boolean;
}
// color events from common, used for OSC 4/10/11/12 and 104/110/111/112
export const enum ColorRequestType {
REPORT = 0,
SET = 1,
RESTORE = 2
}
// IntRange from https://stackoverflow.com/a/39495173
type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N
? Acc[number]
: Enumerate<N, [...Acc, Acc['length']]>;
type IntRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
export type ColorIndex = IntRange<0, 256>; // number from 0 to 255
export type AllColorIndex = ColorIndex | SpecialColorIndex;
export const enum SpecialColorIndex {
FOREGROUND = 256,
BACKGROUND = 257,
CURSOR = 258
}
export interface IColorReportRequest {
type: ColorRequestType.REPORT;
index: AllColorIndex;
}
export interface IColorSetRequest {
type: ColorRequestType.SET;
index: AllColorIndex;
color: IColorRGB;
}
export interface IColorRestoreRequest {
type: ColorRequestType.RESTORE;
index?: AllColorIndex;
}
export type IColorEvent = (IColorReportRequest | IColorSetRequest | IColorRestoreRequest)[];
/**
* Calls the parser and handles actions generated by the parser.
*/
export interface IInputHandler {
onTitleChange: IEvent<string>;
parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise<boolean>;
print(data: Uint32Array, start: number, end: number): void;
registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable;
registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable;
registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable;
registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
registerApcHandler(id: IFunctionIdentifier, callback: (data: string) => boolean | Promise<boolean>): IDisposable;
/** C0 BEL */ bell(): boolean;
/** C0 LF */ lineFeed(): boolean;
/** C0 CR */ carriageReturn(): boolean;
/** C0 BS */ backspace(): boolean;
/** C0 HT */ tab(): boolean;
/** C0 SO */ shiftOut(): boolean;
/** C0 SI */ shiftIn(): boolean;
/** CSI @ */ insertChars(params: IParams): boolean;
/** CSI SP @ */ scrollLeft(params: IParams): boolean;
/** CSI A */ cursorUp(params: IParams): boolean;
/** CSI SP A */ scrollRight(params: IParams): boolean;
/** CSI B */ cursorDown(params: IParams): boolean;
/** CSI C */ cursorForward(params: IParams): boolean;
/** CSI D */ cursorBackward(params: IParams): boolean;
/** CSI E */ cursorNextLine(params: IParams): boolean;
/** CSI F */ cursorPrecedingLine(params: IParams): boolean;
/** CSI G */ cursorCharAbsolute(params: IParams): boolean;
/** CSI H */ cursorPosition(params: IParams): boolean;
/** CSI I */ cursorForwardTab(params: IParams): boolean;
/** CSI J */ eraseInDisplay(params: IParams): boolean;
/** CSI K */ eraseInLine(params: IParams): boolean;
/** CSI L */ insertLines(params: IParams): boolean;
/** CSI M */ deleteLines(params: IParams): boolean;
/** CSI P */ deleteChars(params: IParams): boolean;
/** CSI S */ scrollUp(params: IParams): boolean;
/** CSI T */ scrollDown(params: IParams, collect?: string): boolean;
/** CSI X */ eraseChars(params: IParams): boolean;
/** CSI Z */ cursorBackwardTab(params: IParams): boolean;
/** CSI ` */ charPosAbsolute(params: IParams): boolean;
/** CSI a */ hPositionRelative(params: IParams): boolean;
/** CSI b */ repeatPrecedingCharacter(params: IParams): boolean;
/** CSI c */ sendDeviceAttributesPrimary(params: IParams): boolean;
/** CSI > c */ sendDeviceAttributesSecondary(params: IParams): boolean;
/** CSI d */ linePosAbsolute(params: IParams): boolean;
/** CSI e */ vPositionRelative(params: IParams): boolean;
/** CSI f */ hVPosition(params: IParams): boolean;
/** CSI g */ tabClear(params: IParams): boolean;
/** CSI h */ setMode(params: IParams, collect?: string): boolean;
/** CSI l */ resetMode(params: IParams, collect?: string): boolean;
/** CSI m */ charAttributes(params: IParams): boolean;
/** CSI n */ deviceStatus(params: IParams, collect?: string): boolean;
/** CSI p */ softReset(params: IParams, collect?: string): boolean;
/** CSI q */ setCursorStyle(params: IParams, collect?: string): boolean;
/** CSI r */ setScrollRegion(params: IParams, collect?: string): boolean;
/** CSI s */ saveCursor(params: IParams): boolean;
/** CSI u */ restoreCursor(params: IParams): boolean;
/** CSI ' } */ insertColumns(params: IParams): boolean;
/** CSI ' ~ */ deleteColumns(params: IParams): boolean;
/** OSC 0 */
/** OSC 2 */ setTitle(data: string): boolean;
/** OSC 4 */ setOrReportIndexedColor(data: string): boolean;
/** OSC 10 */ setOrReportFgColor(data: string): boolean;
/** OSC 11 */ setOrReportBgColor(data: string): boolean;
/** OSC 12 */ setOrReportCursorColor(data: string): boolean;
/** OSC 104 */ restoreIndexedColor(data: string): boolean;
/** OSC 110 */ restoreFgColor(data: string): boolean;
/** OSC 111 */ restoreBgColor(data: string): boolean;
/** OSC 112 */ restoreCursorColor(data: string): boolean;
/** ESC E */ nextLine(): boolean;
/** ESC = */ keypadApplicationMode(): boolean;
/** ESC > */ keypadNumericMode(): boolean;
/** ESC % G */
/** ESC % @ */ selectDefaultCharset(): boolean;
/** ESC ( C */
/** ESC ) C */
/** ESC * C */
/** ESC + C */
/** ESC - C */
/** ESC . C */
/** ESC / C */ selectCharset(collectAndFlag: string): boolean;
/** ESC D */ index(): boolean;
/** ESC H */ tabSet(): boolean;
/** ESC M */ reverseIndex(): boolean;
/** ESC c */ fullReset(): boolean;
/** ESC n */
/** ESC o */
/** ESC | */
/** ESC } */
/** ESC ~ */ setgLevel(level: number): boolean;
/** ESC # 8 */ screenAlignmentPattern(): boolean;
}
export interface IParseStack {
paused: boolean;
cursorStartX: number;
cursorStartY: number;
decodedLength: number;
position: number;
}
+23
View File
@@ -0,0 +1,23 @@
import { IUnicodeService, IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services';
export declare class UnicodeService implements IUnicodeService {
serviceBrand: any;
private _providers;
private _active;
private _activeProvider;
private readonly _onChange;
readonly onChange: import("common/base/Event").IEvent<string>;
static extractShouldJoin(value: UnicodeCharProperties): boolean;
static extractWidth(value: UnicodeCharProperties): UnicodeCharWidth;
static extractCharKind(value: UnicodeCharProperties): number;
static createPropertyValue(state: number, width: number, shouldJoin?: boolean): UnicodeCharProperties;
constructor();
dispose(): void;
get versions(): string[];
get activeVersion(): string;
set activeVersion(version: string);
register(provider: IUnicodeVersionProvider): void;
wcwidth(num: number): UnicodeCharWidth;
getStringCellWidth(s: string): number;
charProperties(codepoint: number, preceding: UnicodeCharProperties): UnicodeCharProperties;
}
//# sourceMappingURL=UnicodeService.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"UnicodeService.d.ts","sourceRoot":"","sources":["UnicodeService.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAG7H,qBAAa,cAAe,YAAW,eAAe;IAC7C,YAAY,EAAE,GAAG,CAAC;IAEzB,OAAO,CAAC,UAAU,CAAiE;IACnF,OAAO,CAAC,OAAO,CAAc;IAC7B,OAAO,CAAC,eAAe,CAA0B;IAEjD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyB;IACnD,SAAgB,QAAQ,6CAAwB;IAEhD,OAAc,iBAAiB,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAErE;IACD,OAAc,YAAY,CAAC,KAAK,EAAE,qBAAqB,GAAG,gBAAgB,CAEzE;IACD,OAAc,eAAe,CAAC,KAAK,EAAE,qBAAqB,GAAG,MAAM,CAElE;IACD,OAAc,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,GAAE,OAAe,GAAG,qBAAqB,CAElH;IAED,cAKC;IAEM,OAAO,IAAI,IAAI,CAErB;IAED,IAAW,QAAQ,IAAI,MAAM,EAAE,CAE9B;IAED,IAAW,aAAa,IAAI,MAAM,CAEjC;IAED,IAAW,aAAa,CAAC,OAAO,EAAE,MAAM,EAOvC;IAEM,QAAQ,CAAC,QAAQ,EAAE,uBAAuB,GAAG,IAAI,CAEvD;IAKM,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,CAE5C;IAEM,kBAAkB,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAkC3C;IAEM,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,qBAAqB,GAAG,qBAAqB,CAEhG;CACF"}
+85
View File
@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnicodeService = void 0;
const UnicodeV6_1 = require("common/input/UnicodeV6");
const Event_1 = require("common/base/Event");
class UnicodeService {
static extractShouldJoin(value) {
return (value & 1) !== 0;
}
static extractWidth(value) {
return ((value >> 1) & 0x3);
}
static extractCharKind(value) {
return value >> 3;
}
static createPropertyValue(state, width, shouldJoin = false) {
return ((state & 0xffffff) << 3) | ((width & 3) << 1) | (shouldJoin ? 1 : 0);
}
constructor() {
this._providers = Object.create(null);
this._active = '';
this._onChange = new Event_1.Emitter();
this.onChange = this._onChange.event;
const defaultProvider = new UnicodeV6_1.UnicodeV6();
this.register(defaultProvider);
this._active = defaultProvider.version;
this._activeProvider = defaultProvider;
}
dispose() {
this._onChange.dispose();
}
get versions() {
return Object.keys(this._providers);
}
get activeVersion() {
return this._active;
}
set activeVersion(version) {
if (!this._providers[version]) {
throw new Error(`unknown Unicode version "${version}"`);
}
this._active = version;
this._activeProvider = this._providers[version];
this._onChange.fire(version);
}
register(provider) {
this._providers[provider.version] = provider;
}
wcwidth(num) {
return this._activeProvider.wcwidth(num);
}
getStringCellWidth(s) {
let result = 0;
let precedingInfo = 0;
const length = s.length;
for (let i = 0; i < length; ++i) {
let code = s.charCodeAt(i);
if (0xD800 <= code && code <= 0xDBFF) {
if (++i >= length) {
return result + this.wcwidth(code);
}
const second = s.charCodeAt(i);
if (0xDC00 <= second && second <= 0xDFFF) {
code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
else {
result += this.wcwidth(second);
}
}
const currentInfo = this.charProperties(code, precedingInfo);
let chWidth = UnicodeService.extractWidth(currentInfo);
if (UnicodeService.extractShouldJoin(currentInfo)) {
chWidth -= UnicodeService.extractWidth(precedingInfo);
}
result += chWidth;
precedingInfo = currentInfo;
}
return result;
}
charProperties(codepoint, preceding) {
return this._activeProvider.charProperties(codepoint, preceding);
}
}
exports.UnicodeService = UnicodeService;
//# sourceMappingURL=UnicodeService.js.map
@@ -0,0 +1 @@
{"version":3,"file":"UnicodeService.js","sourceRoot":"","sources":["UnicodeService.ts"],"names":[],"mappings":";;;AAKA,sDAAmD;AAEnD,6CAA4C;AAE5C;IAUS,MAAM,CAAC,iBAAiB,CAAC,KAA4B;QAC1D,OAAO,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACM,MAAM,CAAC,YAAY,CAAC,KAA4B;QACrD,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,GAAG,CAAqB,CAAC;IAClD,CAAC;IACM,MAAM,CAAC,eAAe,CAAC,KAA4B;QACxD,OAAO,KAAK,IAAI,CAAC,CAAC;IACpB,CAAC;IACM,MAAM,CAAC,mBAAmB,CAAC,KAAa,EAAE,KAAa,EAAE,UAAU,GAAY,KAAK;QACzF,OAAO,CAAC,CAAC,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,UAAU,CAAA,CAAC,CAAA,CAAC,CAAA,CAAC,CAAA,CAAC,CAAC,CAAC;IAC3E,CAAC;IAED;QApBQ,eAAU,GAA6C,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC3E,YAAO,GAAW,EAAE,CAAC;QAGZ,cAAS,GAAG,IAAI,eAAO,EAAU,CAAC;QACnC,aAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;QAgB9C,MAAM,eAAe,GAAG,IAAI,qBAAS,EAAE,CAAC;QACxC,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC;QACvC,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IACzC,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,IAAW,QAAQ;QACjB,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACtC,CAAC;IAED,IAAW,aAAa;QACtB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,IAAW,aAAa,CAAC,OAAe;QACtC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,KAAK,CAAC,4BAA4B,OAAO,GAAG,CAAC,CAAC;QAC1D,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAChD,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;IAEM,QAAQ,CAAC,QAAiC;QAC/C,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC;IAC/C,CAAC;IAKM,OAAO,CAAC,GAAW;QACxB,OAAO,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3C,CAAC;IAEM,kBAAkB,CAAC,CAAS;QACjC,IAAI,MAAM,GAAG,CAAC,CAAC;QACf,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;QACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;YAChC,IAAI,IAAI,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAE3B,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,IAAI,MAAM,EAAE,CAAC;gBACrC,IAAI,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC;oBAMlB,OAAO,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;gBACrC,CAAC;gBACD,MAAM,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;gBAG/B,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,EAAE,CAAC;oBACzC,IAAI,GAAG,CAAC,IAAI,GAAG,MAAM,CAAC,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;gBAC7D,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBACjC,CAAC;YACH,CAAC;YACD,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YAC7D,IAAI,OAAO,GAAG,cAAc,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC;YACvD,IAAI,cAAc,CAAC,iBAAiB,CAAC,WAAW,CAAC,EAAE,CAAC;gBAClD,OAAO,IAAI,cAAc,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;YACxD,CAAC;YACD,MAAM,IAAI,OAAO,CAAC;YAClB,aAAa,GAAG,WAAW,CAAC;QAC9B,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAEM,cAAc,CAAC,SAAiB,EAAE,SAAgC;QACvE,OAAO,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IACnE,CAAC;CACF"}
+1 -1
View File
@@ -5,7 +5,7 @@
import { UnicodeV6 } from 'common/input/UnicodeV6';
import { IUnicodeService, IUnicodeVersionProvider, UnicodeCharProperties, UnicodeCharWidth } from 'common/services/Services';
import { Emitter } from 'common/Event';
import { Emitter } from 'common/base/Event';
export class UnicodeService implements IUnicodeService {
public serviceBrand: any;
+8
View File
@@ -0,0 +1,8 @@
{
"extends": ["../tsconfig.json"],
"compilerOptions": {
"noEmit": true,
"rootDir": "."
},
"include": ["./**/*"]
}