@xterm/xterm 5.6.0-beta.13 → 5.6.0-beta.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +9 -3
  2. package/css/xterm.css +71 -4
  3. package/lib/xterm.js +1 -1
  4. package/lib/xterm.js.map +1 -1
  5. package/lib/xterm.mjs +53 -0
  6. package/lib/xterm.mjs.map +7 -0
  7. package/package.json +44 -33
  8. package/src/browser/AccessibilityManager.ts +54 -26
  9. package/src/browser/{Terminal.ts → CoreBrowserTerminal.ts} +159 -145
  10. package/src/browser/Linkifier.ts +26 -14
  11. package/src/browser/LocalizableStrings.ts +15 -4
  12. package/src/browser/{Types.d.ts → Types.ts} +67 -15
  13. package/src/browser/Viewport.ts +148 -370
  14. package/src/browser/decorations/BufferDecorationRenderer.ts +14 -9
  15. package/src/browser/decorations/OverviewRulerRenderer.ts +40 -44
  16. package/src/browser/input/CompositionHelper.ts +2 -1
  17. package/src/browser/input/MoveToCell.ts +3 -1
  18. package/src/browser/public/Terminal.ts +25 -19
  19. package/src/browser/renderer/dom/DomRenderer.ts +19 -14
  20. package/src/browser/renderer/dom/DomRendererRowFactory.ts +35 -15
  21. package/src/browser/renderer/shared/Constants.ts +0 -8
  22. package/src/browser/renderer/shared/Types.ts +84 -0
  23. package/src/browser/services/CharSizeService.ts +6 -6
  24. package/src/browser/services/CoreBrowserService.ts +15 -15
  25. package/src/browser/services/LinkProviderService.ts +2 -2
  26. package/src/browser/services/RenderService.ts +20 -20
  27. package/src/browser/services/SelectionService.ts +8 -8
  28. package/src/browser/services/Services.ts +13 -13
  29. package/src/browser/services/ThemeService.ts +19 -58
  30. package/src/browser/shared/Constants.ts +8 -0
  31. package/src/common/CircularList.ts +5 -5
  32. package/src/common/CoreTerminal.ts +35 -41
  33. package/src/common/InputHandler.ts +83 -56
  34. package/src/common/{Types.d.ts → Types.ts} +13 -17
  35. package/src/common/buffer/Buffer.ts +15 -7
  36. package/src/common/buffer/BufferReflow.ts +9 -6
  37. package/src/common/buffer/BufferSet.ts +5 -5
  38. package/src/common/buffer/Marker.ts +4 -4
  39. package/src/common/buffer/{Types.d.ts → Types.ts} +2 -2
  40. package/src/common/input/Keyboard.ts +0 -24
  41. package/src/common/input/WriteBuffer.ts +3 -3
  42. package/src/common/parser/EscapeSequenceParser.ts +4 -4
  43. package/src/common/public/BufferNamespaceApi.ts +3 -3
  44. package/src/common/services/BufferService.ts +10 -7
  45. package/src/common/services/CoreMouseService.ts +53 -6
  46. package/src/common/services/CoreService.ts +12 -8
  47. package/src/common/services/DecorationService.ts +8 -9
  48. package/src/common/services/InstantiationService.ts +1 -1
  49. package/src/common/services/LogService.ts +2 -2
  50. package/src/common/services/OptionsService.ts +8 -6
  51. package/src/common/services/ServiceRegistry.ts +1 -1
  52. package/src/common/services/Services.ts +32 -17
  53. package/src/common/services/UnicodeService.ts +2 -2
  54. package/src/vs/base/browser/browser.ts +141 -0
  55. package/src/vs/base/browser/canIUse.ts +49 -0
  56. package/src/vs/base/browser/dom.ts +2369 -0
  57. package/src/vs/base/browser/fastDomNode.ts +316 -0
  58. package/src/vs/base/browser/globalPointerMoveMonitor.ts +112 -0
  59. package/src/vs/base/browser/iframe.ts +135 -0
  60. package/src/vs/base/browser/keyboardEvent.ts +213 -0
  61. package/src/vs/base/browser/mouseEvent.ts +229 -0
  62. package/src/vs/base/browser/touch.ts +372 -0
  63. package/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts +303 -0
  64. package/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts +114 -0
  65. package/src/vs/base/browser/ui/scrollbar/scrollableElement.ts +720 -0
  66. package/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts +165 -0
  67. package/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts +114 -0
  68. package/src/vs/base/browser/ui/scrollbar/scrollbarState.ts +243 -0
  69. package/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts +118 -0
  70. package/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts +116 -0
  71. package/src/vs/base/browser/ui/widget.ts +57 -0
  72. package/src/vs/base/browser/window.ts +14 -0
  73. package/src/vs/base/common/arrays.ts +887 -0
  74. package/src/vs/base/common/arraysFind.ts +202 -0
  75. package/src/vs/base/common/assert.ts +71 -0
  76. package/src/vs/base/common/async.ts +1992 -0
  77. package/src/vs/base/common/cancellation.ts +148 -0
  78. package/src/vs/base/common/charCode.ts +450 -0
  79. package/src/vs/base/common/collections.ts +140 -0
  80. package/src/vs/base/common/decorators.ts +130 -0
  81. package/src/vs/base/common/equals.ts +146 -0
  82. package/src/vs/base/common/errors.ts +303 -0
  83. package/src/vs/base/common/event.ts +1778 -0
  84. package/src/vs/base/common/functional.ts +32 -0
  85. package/src/vs/base/common/hash.ts +316 -0
  86. package/src/vs/base/common/iterator.ts +159 -0
  87. package/src/vs/base/common/keyCodes.ts +526 -0
  88. package/src/vs/base/common/keybindings.ts +284 -0
  89. package/src/vs/base/common/lazy.ts +47 -0
  90. package/src/vs/base/common/lifecycle.ts +801 -0
  91. package/src/vs/base/common/linkedList.ts +142 -0
  92. package/src/vs/base/common/map.ts +202 -0
  93. package/src/vs/base/common/numbers.ts +98 -0
  94. package/src/vs/base/common/observable.ts +76 -0
  95. package/src/vs/base/common/observableInternal/api.ts +31 -0
  96. package/src/vs/base/common/observableInternal/autorun.ts +281 -0
  97. package/src/vs/base/common/observableInternal/base.ts +489 -0
  98. package/src/vs/base/common/observableInternal/debugName.ts +145 -0
  99. package/src/vs/base/common/observableInternal/derived.ts +428 -0
  100. package/src/vs/base/common/observableInternal/lazyObservableValue.ts +146 -0
  101. package/src/vs/base/common/observableInternal/logging.ts +328 -0
  102. package/src/vs/base/common/observableInternal/promise.ts +209 -0
  103. package/src/vs/base/common/observableInternal/utils.ts +610 -0
  104. package/src/vs/base/common/platform.ts +281 -0
  105. package/src/vs/base/common/scrollable.ts +522 -0
  106. package/src/vs/base/common/sequence.ts +34 -0
  107. package/src/vs/base/common/stopwatch.ts +43 -0
  108. package/src/vs/base/common/strings.ts +557 -0
  109. package/src/vs/base/common/symbols.ts +9 -0
  110. package/src/vs/base/common/uint.ts +59 -0
  111. package/src/vs/patches/nls.ts +90 -0
  112. package/src/vs/typings/base-common.d.ts +20 -0
  113. package/src/vs/typings/require.d.ts +42 -0
  114. package/src/vs/typings/vscode-globals-nls.d.ts +36 -0
  115. package/src/vs/typings/vscode-globals-product.d.ts +33 -0
  116. package/typings/xterm.d.ts +80 -14
  117. package/src/browser/Lifecycle.ts +0 -33
  118. package/src/browser/renderer/shared/CellColorResolver.ts +0 -236
  119. package/src/browser/renderer/shared/CharAtlasCache.ts +0 -96
  120. package/src/browser/renderer/shared/CharAtlasUtils.ts +0 -75
  121. package/src/browser/renderer/shared/CursorBlinkStateManager.ts +0 -146
  122. package/src/browser/renderer/shared/CustomGlyphs.ts +0 -687
  123. package/src/browser/renderer/shared/DevicePixelObserver.ts +0 -41
  124. package/src/browser/renderer/shared/TextureAtlas.ts +0 -1100
  125. package/src/browser/renderer/shared/Types.d.ts +0 -173
  126. package/src/common/EventEmitter.ts +0 -78
  127. package/src/common/Lifecycle.ts +0 -108
  128. /package/src/browser/selection/{Types.d.ts → Types.ts} +0 -0
  129. /package/src/common/parser/{Types.d.ts → Types.ts} +0 -0
@@ -1,1100 +0,0 @@
1
- /**
2
- * Copyright (c) 2017 The xterm.js authors. All rights reserved.
3
- * @license MIT
4
- */
5
-
6
- import { IColorContrastCache } from 'browser/Types';
7
- import { DIM_OPACITY, TEXT_BASELINE } from 'browser/renderer/shared/Constants';
8
- import { tryDrawCustomChar } from 'browser/renderer/shared/CustomGlyphs';
9
- import { computeNextVariantOffset, treatGlyphAsBackgroundColor, isPowerlineGlyph, isRestrictedPowerlineGlyph, throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
10
- import { IBoundingBox, ICharAtlasConfig, IRasterizedGlyph, ITextureAtlas } from 'browser/renderer/shared/Types';
11
- import { NULL_COLOR, channels, color, rgba } from 'common/Color';
12
- import { EventEmitter } from 'common/EventEmitter';
13
- import { FourKeyMap } from 'common/MultiKeyMap';
14
- import { IdleTaskQueue } from 'common/TaskQueue';
15
- import { IColor } from 'common/Types';
16
- import { AttributeData } from 'common/buffer/AttributeData';
17
- import { Attributes, DEFAULT_COLOR, DEFAULT_EXT, UnderlineStyle } from 'common/buffer/Constants';
18
- import { IUnicodeService } from 'common/services/Services';
19
-
20
- /**
21
- * A shared object which is used to draw nothing for a particular cell.
22
- */
23
- const NULL_RASTERIZED_GLYPH: IRasterizedGlyph = {
24
- texturePage: 0,
25
- texturePosition: { x: 0, y: 0 },
26
- texturePositionClipSpace: { x: 0, y: 0 },
27
- offset: { x: 0, y: 0 },
28
- size: { x: 0, y: 0 },
29
- sizeClipSpace: { x: 0, y: 0 }
30
- };
31
-
32
- const TMP_CANVAS_GLYPH_PADDING = 2;
33
-
34
- const enum Constants {
35
- /**
36
- * The amount of pixel padding to allow in each row. Setting this to zero would make the atlas
37
- * page pack as tightly as possible, but more pages would end up being created as a result.
38
- */
39
- ROW_PIXEL_THRESHOLD = 2,
40
- /**
41
- * The maximum texture size regardless of what the actual hardware maximum turns out to be. This
42
- * is enforced to ensure uploading the texture still finishes in a reasonable amount of time. A
43
- * 4096 squared image takes up 16MB of GPU memory.
44
- */
45
- FORCED_MAX_TEXTURE_SIZE = 4096
46
- }
47
-
48
- interface ICharAtlasActiveRow {
49
- x: number;
50
- y: number;
51
- height: number;
52
- }
53
-
54
- // Work variables to avoid garbage collection
55
- let $glyph = undefined;
56
-
57
- export class TextureAtlas implements ITextureAtlas {
58
- private _didWarmUp: boolean = false;
59
-
60
- private _cacheMap: FourKeyMap<number, number, number, number, IRasterizedGlyph> = new FourKeyMap();
61
- private _cacheMapCombined: FourKeyMap<string, number, number, number, IRasterizedGlyph> = new FourKeyMap();
62
-
63
- // The texture that the atlas is drawn to
64
- private _pages: AtlasPage[] = [];
65
- public get pages(): { canvas: HTMLCanvasElement, version: number }[] { return this._pages; }
66
-
67
- // The set of atlas pages that can be written to
68
- private _activePages: AtlasPage[] = [];
69
-
70
- private _tmpCanvas: HTMLCanvasElement;
71
- // A temporary context that glyphs are drawn to before being transfered to the atlas.
72
- private _tmpCtx: CanvasRenderingContext2D;
73
-
74
- private _workBoundingBox: IBoundingBox = { top: 0, left: 0, bottom: 0, right: 0 };
75
- private _workAttributeData: AttributeData = new AttributeData();
76
-
77
- private _textureSize: number = 512;
78
-
79
- public static maxAtlasPages: number | undefined;
80
- public static maxTextureSize: number | undefined;
81
-
82
- private readonly _onAddTextureAtlasCanvas = new EventEmitter<HTMLCanvasElement>();
83
- public readonly onAddTextureAtlasCanvas = this._onAddTextureAtlasCanvas.event;
84
- private readonly _onRemoveTextureAtlasCanvas = new EventEmitter<HTMLCanvasElement>();
85
- public readonly onRemoveTextureAtlasCanvas = this._onRemoveTextureAtlasCanvas.event;
86
-
87
- constructor(
88
- private readonly _document: Document,
89
- private readonly _config: ICharAtlasConfig,
90
- private readonly _unicodeService: IUnicodeService
91
- ) {
92
- this._createNewPage();
93
- this._tmpCanvas = createCanvas(
94
- _document,
95
- this._config.deviceCellWidth * 4 + TMP_CANVAS_GLYPH_PADDING * 2,
96
- this._config.deviceCellHeight + TMP_CANVAS_GLYPH_PADDING * 2
97
- );
98
- this._tmpCtx = throwIfFalsy(this._tmpCanvas.getContext('2d', {
99
- alpha: this._config.allowTransparency,
100
- willReadFrequently: true
101
- }));
102
- }
103
-
104
- public dispose(): void {
105
- for (const page of this.pages) {
106
- page.canvas.remove();
107
- }
108
- this._onAddTextureAtlasCanvas.dispose();
109
- }
110
-
111
- public warmUp(): void {
112
- if (!this._didWarmUp) {
113
- this._doWarmUp();
114
- this._didWarmUp = true;
115
- }
116
- }
117
-
118
- private _doWarmUp(): void {
119
- // Pre-fill with ASCII 33-126, this is not urgent and done in idle callbacks
120
- const queue = new IdleTaskQueue();
121
- for (let i = 33; i < 126; i++) {
122
- queue.enqueue(() => {
123
- if (!this._cacheMap.get(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT)) {
124
- const rasterizedGlyph = this._drawToCache(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT);
125
- this._cacheMap.set(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT, rasterizedGlyph);
126
- }
127
- });
128
- }
129
- }
130
-
131
- private _requestClearModel = false;
132
- public beginFrame(): boolean {
133
- return this._requestClearModel;
134
- }
135
-
136
- public clearTexture(): void {
137
- if (this._pages[0].currentRow.x === 0 && this._pages[0].currentRow.y === 0) {
138
- return;
139
- }
140
- for (const page of this._pages) {
141
- page.clear();
142
- }
143
- this._cacheMap.clear();
144
- this._cacheMapCombined.clear();
145
- this._didWarmUp = false;
146
- }
147
-
148
- private _createNewPage(): AtlasPage {
149
- // Try merge the set of the 4 most used pages of the largest size. This is is deferred to a
150
- // microtask to ensure it does not interrupt textures that will be rendered in the current
151
- // animation frame which would result in blank rendered areas. This is actually not that
152
- // expensive relative to drawing the glyphs, so there is no need to wait for an idle callback.
153
- if (TextureAtlas.maxAtlasPages && this._pages.length >= Math.max(4, TextureAtlas.maxAtlasPages)) {
154
- // Find the set of the largest 4 images, below the maximum size, with the highest
155
- // percentages used
156
- const pagesBySize = this._pages.filter(e => {
157
- return e.canvas.width * 2 <= (TextureAtlas.maxTextureSize || Constants.FORCED_MAX_TEXTURE_SIZE);
158
- }).sort((a, b) => {
159
- if (b.canvas.width !== a.canvas.width) {
160
- return b.canvas.width - a.canvas.width;
161
- }
162
- return b.percentageUsed - a.percentageUsed;
163
- });
164
- let sameSizeI = -1;
165
- let size = 0;
166
- for (let i = 0; i < pagesBySize.length; i++) {
167
- if (pagesBySize[i].canvas.width !== size) {
168
- sameSizeI = i;
169
- size = pagesBySize[i].canvas.width;
170
- } else if (i - sameSizeI === 3) {
171
- break;
172
- }
173
- }
174
-
175
- // Gather details of the merge
176
- const mergingPages = pagesBySize.slice(sameSizeI, sameSizeI + 4);
177
- const sortedMergingPagesIndexes = mergingPages.map(e => e.glyphs[0].texturePage).sort((a, b) => a > b ? 1 : -1);
178
- const mergedPageIndex = this.pages.length - mergingPages.length;
179
-
180
- // Merge into the new page
181
- const mergedPage = this._mergePages(mergingPages, mergedPageIndex);
182
- mergedPage.version++;
183
-
184
- // Delete the pages, shifting glyph texture pages as needed
185
- for (let i = sortedMergingPagesIndexes.length - 1; i >= 0; i--) {
186
- this._deletePage(sortedMergingPagesIndexes[i]);
187
- }
188
-
189
- // Add the new merged page to the end
190
- this.pages.push(mergedPage);
191
-
192
- // Request the model to be cleared to refresh all texture pages.
193
- this._requestClearModel = true;
194
- this._onAddTextureAtlasCanvas.fire(mergedPage.canvas);
195
- }
196
-
197
- // All new atlas pages are created small as they are highly dynamic
198
- const newPage = new AtlasPage(this._document, this._textureSize);
199
- this._pages.push(newPage);
200
- this._activePages.push(newPage);
201
- this._onAddTextureAtlasCanvas.fire(newPage.canvas);
202
- return newPage;
203
- }
204
-
205
- private _mergePages(mergingPages: AtlasPage[], mergedPageIndex: number): AtlasPage {
206
- const mergedSize = mergingPages[0].canvas.width * 2;
207
- const mergedPage = new AtlasPage(this._document, mergedSize, mergingPages);
208
- for (const [i, p] of mergingPages.entries()) {
209
- const xOffset = i * p.canvas.width % mergedSize;
210
- const yOffset = Math.floor(i / 2) * p.canvas.height;
211
- mergedPage.ctx.drawImage(p.canvas, xOffset, yOffset);
212
- for (const g of p.glyphs) {
213
- g.texturePage = mergedPageIndex;
214
- g.sizeClipSpace.x = g.size.x / mergedSize;
215
- g.sizeClipSpace.y = g.size.y / mergedSize;
216
- g.texturePosition.x += xOffset;
217
- g.texturePosition.y += yOffset;
218
- g.texturePositionClipSpace.x = g.texturePosition.x / mergedSize;
219
- g.texturePositionClipSpace.y = g.texturePosition.y / mergedSize;
220
- }
221
-
222
- this._onRemoveTextureAtlasCanvas.fire(p.canvas);
223
-
224
- // Remove the merging page from active pages if it was there
225
- const index = this._activePages.indexOf(p);
226
- if (index !== -1) {
227
- this._activePages.splice(index, 1);
228
- }
229
- }
230
- return mergedPage;
231
- }
232
-
233
- private _deletePage(pageIndex: number): void {
234
- this._pages.splice(pageIndex, 1);
235
- for (let j = pageIndex; j < this._pages.length; j++) {
236
- const adjustingPage = this._pages[j];
237
- for (const g of adjustingPage.glyphs) {
238
- g.texturePage--;
239
- }
240
- adjustingPage.version++;
241
- }
242
- }
243
-
244
- public getRasterizedGlyphCombinedChar(chars: string, bg: number, fg: number, ext: number, restrictToCellHeight: boolean): IRasterizedGlyph {
245
- return this._getFromCacheMap(this._cacheMapCombined, chars, bg, fg, ext, restrictToCellHeight);
246
- }
247
-
248
- public getRasterizedGlyph(code: number, bg: number, fg: number, ext: number, restrictToCellHeight: boolean): IRasterizedGlyph {
249
- return this._getFromCacheMap(this._cacheMap, code, bg, fg, ext, restrictToCellHeight);
250
- }
251
-
252
- /**
253
- * Gets the glyphs texture coords, drawing the texture if it's not already
254
- */
255
- private _getFromCacheMap(
256
- cacheMap: FourKeyMap<string | number, number, number, number, IRasterizedGlyph>,
257
- key: string | number,
258
- bg: number,
259
- fg: number,
260
- ext: number,
261
- restrictToCellHeight: boolean = false
262
- ): IRasterizedGlyph {
263
- $glyph = cacheMap.get(key, bg, fg, ext);
264
- if (!$glyph) {
265
- $glyph = this._drawToCache(key, bg, fg, ext, restrictToCellHeight);
266
- cacheMap.set(key, bg, fg, ext, $glyph);
267
- }
268
- return $glyph;
269
- }
270
-
271
- private _getColorFromAnsiIndex(idx: number): IColor {
272
- if (idx >= this._config.colors.ansi.length) {
273
- throw new Error('No color found for idx ' + idx);
274
- }
275
- return this._config.colors.ansi[idx];
276
- }
277
-
278
- private _getBackgroundColor(bgColorMode: number, bgColor: number, inverse: boolean, dim: boolean): IColor {
279
- if (this._config.allowTransparency) {
280
- // The background color might have some transparency, so we need to render it as fully
281
- // transparent in the atlas. Otherwise we'd end up drawing the transparent background twice
282
- // around the anti-aliased edges of the glyph, and it would look too dark.
283
- return NULL_COLOR;
284
- }
285
-
286
- let result: IColor;
287
- switch (bgColorMode) {
288
- case Attributes.CM_P16:
289
- case Attributes.CM_P256:
290
- result = this._getColorFromAnsiIndex(bgColor);
291
- break;
292
- case Attributes.CM_RGB:
293
- const arr = AttributeData.toColorRGB(bgColor);
294
- result = channels.toColor(arr[0], arr[1], arr[2]);
295
- break;
296
- case Attributes.CM_DEFAULT:
297
- default:
298
- if (inverse) {
299
- result = color.opaque(this._config.colors.foreground);
300
- } else {
301
- result = this._config.colors.background;
302
- }
303
- break;
304
- }
305
-
306
- return result;
307
- }
308
-
309
- private _getForegroundColor(bg: number, bgColorMode: number, bgColor: number, fg: number, fgColorMode: number, fgColor: number, inverse: boolean, dim: boolean, bold: boolean, excludeFromContrastRatioDemands: boolean): IColor {
310
- const minimumContrastColor = this._getMinimumContrastColor(bg, bgColorMode, bgColor, fg, fgColorMode, fgColor, inverse, bold, dim, excludeFromContrastRatioDemands);
311
- if (minimumContrastColor) {
312
- return minimumContrastColor;
313
- }
314
-
315
- let result: IColor;
316
- switch (fgColorMode) {
317
- case Attributes.CM_P16:
318
- case Attributes.CM_P256:
319
- if (this._config.drawBoldTextInBrightColors && bold && fgColor < 8) {
320
- fgColor += 8;
321
- }
322
- result = this._getColorFromAnsiIndex(fgColor);
323
- break;
324
- case Attributes.CM_RGB:
325
- const arr = AttributeData.toColorRGB(fgColor);
326
- result = channels.toColor(arr[0], arr[1], arr[2]);
327
- break;
328
- case Attributes.CM_DEFAULT:
329
- default:
330
- if (inverse) {
331
- result = this._config.colors.background;
332
- } else {
333
- result = this._config.colors.foreground;
334
- }
335
- }
336
-
337
- // Always use an opaque color regardless of allowTransparency
338
- if (this._config.allowTransparency) {
339
- result = color.opaque(result);
340
- }
341
-
342
- // Apply dim to the color, opacity is fine to use for the foreground color
343
- if (dim) {
344
- result = color.multiplyOpacity(result, DIM_OPACITY);
345
- }
346
-
347
- return result;
348
- }
349
-
350
- private _resolveBackgroundRgba(bgColorMode: number, bgColor: number, inverse: boolean): number {
351
- switch (bgColorMode) {
352
- case Attributes.CM_P16:
353
- case Attributes.CM_P256:
354
- return this._getColorFromAnsiIndex(bgColor).rgba;
355
- case Attributes.CM_RGB:
356
- return bgColor << 8;
357
- case Attributes.CM_DEFAULT:
358
- default:
359
- if (inverse) {
360
- return this._config.colors.foreground.rgba;
361
- }
362
- return this._config.colors.background.rgba;
363
- }
364
- }
365
-
366
- private _resolveForegroundRgba(fgColorMode: number, fgColor: number, inverse: boolean, bold: boolean): number {
367
- switch (fgColorMode) {
368
- case Attributes.CM_P16:
369
- case Attributes.CM_P256:
370
- if (this._config.drawBoldTextInBrightColors && bold && fgColor < 8) {
371
- fgColor += 8;
372
- }
373
- return this._getColorFromAnsiIndex(fgColor).rgba;
374
- case Attributes.CM_RGB:
375
- return fgColor << 8;
376
- case Attributes.CM_DEFAULT:
377
- default:
378
- if (inverse) {
379
- return this._config.colors.background.rgba;
380
- }
381
- return this._config.colors.foreground.rgba;
382
- }
383
- }
384
-
385
- private _getMinimumContrastColor(bg: number, bgColorMode: number, bgColor: number, fg: number, fgColorMode: number, fgColor: number, inverse: boolean, bold: boolean, dim: boolean, excludeFromContrastRatioDemands: boolean): IColor | undefined {
386
- if (this._config.minimumContrastRatio === 1 || excludeFromContrastRatioDemands) {
387
- return undefined;
388
- }
389
-
390
- // Try get from cache first
391
- const cache = this._getContrastCache(dim);
392
- const adjustedColor = cache.getColor(bg, fg);
393
- if (adjustedColor !== undefined) {
394
- return adjustedColor || undefined;
395
- }
396
-
397
- const bgRgba = this._resolveBackgroundRgba(bgColorMode, bgColor, inverse);
398
- const fgRgba = this._resolveForegroundRgba(fgColorMode, fgColor, inverse, bold);
399
- // Dim cells only require half the contrast, otherwise they wouldn't be distinguishable from
400
- // non-dim cells
401
- const result = rgba.ensureContrastRatio(bgRgba, fgRgba, this._config.minimumContrastRatio / (dim ? 2 : 1));
402
-
403
- if (!result) {
404
- cache.setColor(bg, fg, null);
405
- return undefined;
406
- }
407
-
408
- const color = channels.toColor(
409
- (result >> 24) & 0xFF,
410
- (result >> 16) & 0xFF,
411
- (result >> 8) & 0xFF
412
- );
413
- cache.setColor(bg, fg, color);
414
-
415
- return color;
416
- }
417
-
418
- private _getContrastCache(dim: boolean): IColorContrastCache {
419
- if (dim) {
420
- return this._config.colors.halfContrastCache;
421
- }
422
- return this._config.colors.contrastCache;
423
- }
424
-
425
- private _drawToCache(codeOrChars: number | string, bg: number, fg: number, ext: number, restrictToCellHeight: boolean = false): IRasterizedGlyph {
426
- const chars = typeof codeOrChars === 'number' ? String.fromCharCode(codeOrChars) : codeOrChars;
427
-
428
- // Uncomment for debugging
429
- // console.log(`draw to cache "${chars}"`, bg, fg, ext);
430
-
431
- // Allow 1 cell width per character, with a minimum of 2 (CJK), plus some padding. This is used
432
- // to draw the glyph to the canvas as well as to restrict the bounding box search to ensure
433
- // giant ligatures (eg. =====>) don't impact overall performance.
434
- const allowedWidth = Math.min(this._config.deviceCellWidth * Math.max(chars.length, 2) + TMP_CANVAS_GLYPH_PADDING * 2, this._textureSize);
435
- if (this._tmpCanvas.width < allowedWidth) {
436
- this._tmpCanvas.width = allowedWidth;
437
- }
438
- // Include line height when drawing glyphs
439
- const allowedHeight = Math.min(this._config.deviceCellHeight + TMP_CANVAS_GLYPH_PADDING * 4, this._textureSize);
440
- if (this._tmpCanvas.height < allowedHeight) {
441
- this._tmpCanvas.height = allowedHeight;
442
- }
443
- this._tmpCtx.save();
444
-
445
- this._workAttributeData.fg = fg;
446
- this._workAttributeData.bg = bg;
447
- this._workAttributeData.extended.ext = ext;
448
-
449
- const invisible = !!this._workAttributeData.isInvisible();
450
- if (invisible) {
451
- return NULL_RASTERIZED_GLYPH;
452
- }
453
-
454
- const bold = !!this._workAttributeData.isBold();
455
- const inverse = !!this._workAttributeData.isInverse();
456
- const dim = !!this._workAttributeData.isDim();
457
- const italic = !!this._workAttributeData.isItalic();
458
- const underline = !!this._workAttributeData.isUnderline();
459
- const strikethrough = !!this._workAttributeData.isStrikethrough();
460
- const overline = !!this._workAttributeData.isOverline();
461
- let fgColor = this._workAttributeData.getFgColor();
462
- let fgColorMode = this._workAttributeData.getFgColorMode();
463
- let bgColor = this._workAttributeData.getBgColor();
464
- let bgColorMode = this._workAttributeData.getBgColorMode();
465
- if (inverse) {
466
- const temp = fgColor;
467
- fgColor = bgColor;
468
- bgColor = temp;
469
- const temp2 = fgColorMode;
470
- fgColorMode = bgColorMode;
471
- bgColorMode = temp2;
472
- }
473
-
474
- // draw the background
475
- const backgroundColor = this._getBackgroundColor(bgColorMode, bgColor, inverse, dim);
476
- // Use a 'copy' composite operation to clear any existing glyph out of _tmpCtxWithAlpha,
477
- // regardless of transparency in backgroundColor
478
- this._tmpCtx.globalCompositeOperation = 'copy';
479
- this._tmpCtx.fillStyle = backgroundColor.css;
480
- this._tmpCtx.fillRect(0, 0, this._tmpCanvas.width, this._tmpCanvas.height);
481
- this._tmpCtx.globalCompositeOperation = 'source-over';
482
-
483
- // draw the foreground/glyph
484
- const fontWeight = bold ? this._config.fontWeightBold : this._config.fontWeight;
485
- const fontStyle = italic ? 'italic' : '';
486
- this._tmpCtx.font =
487
- `${fontStyle} ${fontWeight} ${this._config.fontSize * this._config.devicePixelRatio}px ${this._config.fontFamily}`;
488
- this._tmpCtx.textBaseline = TEXT_BASELINE;
489
-
490
- const powerlineGlyph = chars.length === 1 && isPowerlineGlyph(chars.charCodeAt(0));
491
- const restrictedPowerlineGlyph = chars.length === 1 && isRestrictedPowerlineGlyph(chars.charCodeAt(0));
492
- const foregroundColor = this._getForegroundColor(bg, bgColorMode, bgColor, fg, fgColorMode, fgColor, inverse, dim, bold, treatGlyphAsBackgroundColor(chars.charCodeAt(0)));
493
- this._tmpCtx.fillStyle = foregroundColor.css;
494
-
495
- // For powerline glyphs left/top padding is excluded (https://github.com/microsoft/vscode/issues/120129)
496
- const padding = restrictedPowerlineGlyph ? 0 : TMP_CANVAS_GLYPH_PADDING * 2;
497
-
498
- // Draw custom characters if applicable
499
- let customGlyph = false;
500
- if (this._config.customGlyphs !== false) {
501
- customGlyph = tryDrawCustomChar(this._tmpCtx, chars, padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight, this._config.fontSize, this._config.devicePixelRatio);
502
- }
503
-
504
- // Whether to clear pixels based on a threshold difference between the glyph color and the
505
- // background color. This should be disabled when the glyph contains multiple colors such as
506
- // underline colors to prevent important colors could get cleared.
507
- let enableClearThresholdCheck = !powerlineGlyph;
508
-
509
- let chWidth: number;
510
- if (typeof codeOrChars === 'number') {
511
- chWidth = this._unicodeService.wcwidth(codeOrChars);
512
- } else {
513
- chWidth = this._unicodeService.getStringCellWidth(codeOrChars);
514
- }
515
-
516
- // Draw underline
517
- if (underline) {
518
- this._tmpCtx.save();
519
- const lineWidth = Math.max(1, Math.floor(this._config.fontSize * this._config.devicePixelRatio / 15));
520
- // When the line width is odd, draw at a 0.5 position
521
- const yOffset = lineWidth % 2 === 1 ? 0.5 : 0;
522
- this._tmpCtx.lineWidth = lineWidth;
523
-
524
- // Underline color
525
- if (this._workAttributeData.isUnderlineColorDefault()) {
526
- this._tmpCtx.strokeStyle = this._tmpCtx.fillStyle;
527
- } else if (this._workAttributeData.isUnderlineColorRGB()) {
528
- enableClearThresholdCheck = false;
529
- this._tmpCtx.strokeStyle = `rgb(${AttributeData.toColorRGB(this._workAttributeData.getUnderlineColor()).join(',')})`;
530
- } else {
531
- enableClearThresholdCheck = false;
532
- let fg = this._workAttributeData.getUnderlineColor();
533
- if (this._config.drawBoldTextInBrightColors && this._workAttributeData.isBold() && fg < 8) {
534
- fg += 8;
535
- }
536
- this._tmpCtx.strokeStyle = this._getColorFromAnsiIndex(fg).css;
537
- }
538
-
539
- // Underline style/stroke
540
- this._tmpCtx.beginPath();
541
- const xLeft = padding;
542
- const yTop = Math.ceil(padding + this._config.deviceCharHeight) - yOffset - (restrictToCellHeight ? lineWidth * 2 : 0);
543
- const yMid = yTop + lineWidth;
544
- const yBot = yTop + lineWidth * 2;
545
- let nextOffset = this._workAttributeData.getUnderlineVariantOffset();
546
-
547
- for (let i = 0; i < chWidth; i++) {
548
- this._tmpCtx.save();
549
- const xChLeft = xLeft + i * this._config.deviceCellWidth;
550
- const xChRight = xLeft + (i + 1) * this._config.deviceCellWidth;
551
- const xChMid = xChLeft + this._config.deviceCellWidth / 2;
552
- switch (this._workAttributeData.extended.underlineStyle) {
553
- case UnderlineStyle.DOUBLE:
554
- this._tmpCtx.moveTo(xChLeft, yTop);
555
- this._tmpCtx.lineTo(xChRight, yTop);
556
- this._tmpCtx.moveTo(xChLeft, yBot);
557
- this._tmpCtx.lineTo(xChRight, yBot);
558
- break;
559
- case UnderlineStyle.CURLY:
560
- // Choose the bezier top and bottom based on the device pixel ratio, the curly line is
561
- // made taller when the line width is as otherwise it's not very clear otherwise.
562
- const yCurlyBot = lineWidth <= 1 ? yBot : Math.ceil(padding + this._config.deviceCharHeight - lineWidth / 2) - yOffset;
563
- const yCurlyTop = lineWidth <= 1 ? yTop : Math.ceil(padding + this._config.deviceCharHeight + lineWidth / 2) - yOffset;
564
- // Clip the left and right edges of the underline such that it can be drawn just outside
565
- // the edge of the cell to ensure a continuous stroke when there are multiple underlined
566
- // glyphs adjacent to one another.
567
- const clipRegion = new Path2D();
568
- clipRegion.rect(xChLeft, yTop, this._config.deviceCellWidth, yBot - yTop);
569
- this._tmpCtx.clip(clipRegion);
570
- // Start 1/2 cell before and end 1/2 cells after to ensure a smooth curve with other
571
- // cells
572
- this._tmpCtx.moveTo(xChLeft - this._config.deviceCellWidth / 2, yMid);
573
- this._tmpCtx.bezierCurveTo(
574
- xChLeft - this._config.deviceCellWidth / 2, yCurlyTop,
575
- xChLeft, yCurlyTop,
576
- xChLeft, yMid
577
- );
578
- this._tmpCtx.bezierCurveTo(
579
- xChLeft, yCurlyBot,
580
- xChMid, yCurlyBot,
581
- xChMid, yMid
582
- );
583
- this._tmpCtx.bezierCurveTo(
584
- xChMid, yCurlyTop,
585
- xChRight, yCurlyTop,
586
- xChRight, yMid
587
- );
588
- this._tmpCtx.bezierCurveTo(
589
- xChRight, yCurlyBot,
590
- xChRight + this._config.deviceCellWidth / 2, yCurlyBot,
591
- xChRight + this._config.deviceCellWidth / 2, yMid
592
- );
593
- break;
594
- case UnderlineStyle.DOTTED:
595
- const offsetWidth = nextOffset === 0 ? 0 :
596
- (nextOffset >= lineWidth ? lineWidth * 2 - nextOffset : lineWidth - nextOffset);
597
- // a line and a gap.
598
- const isLineStart = nextOffset >= lineWidth ? false : true;
599
- if (isLineStart === false || offsetWidth === 0) {
600
- this._tmpCtx.setLineDash([Math.round(lineWidth), Math.round(lineWidth)]);
601
- this._tmpCtx.moveTo(xChLeft + offsetWidth, yTop);
602
- this._tmpCtx.lineTo(xChRight, yTop);
603
- } else {
604
- this._tmpCtx.setLineDash([Math.round(lineWidth), Math.round(lineWidth)]);
605
- this._tmpCtx.moveTo(xChLeft, yTop);
606
- this._tmpCtx.lineTo(xChLeft + offsetWidth, yTop);
607
- this._tmpCtx.moveTo(xChLeft + offsetWidth + lineWidth, yTop);
608
- this._tmpCtx.lineTo(xChRight, yTop);
609
- }
610
- nextOffset = computeNextVariantOffset(xChRight - xChLeft, lineWidth, nextOffset);
611
- break;
612
- case UnderlineStyle.DASHED:
613
- const lineRatio = 0.6;
614
- const gapRatio = 0.3;
615
- // End line ratio is approximately equal to 0.1
616
- const xChWidth = xChRight - xChLeft;
617
- const line = Math.floor(lineRatio * xChWidth);
618
- const gap = Math.floor(gapRatio * xChWidth);
619
- const end = xChWidth - line - gap;
620
- this._tmpCtx.setLineDash([line, gap, end]);
621
- this._tmpCtx.moveTo(xChLeft, yTop);
622
- this._tmpCtx.lineTo(xChRight, yTop);
623
- break;
624
- case UnderlineStyle.SINGLE:
625
- default:
626
- this._tmpCtx.moveTo(xChLeft, yTop);
627
- this._tmpCtx.lineTo(xChRight, yTop);
628
- break;
629
- }
630
- this._tmpCtx.stroke();
631
- this._tmpCtx.restore();
632
- }
633
- this._tmpCtx.restore();
634
-
635
- // Draw stroke in the background color for non custom characters in order to give an outline
636
- // between the text and the underline. Only do this when font size is >= 12 as the underline
637
- // looks odd when the font size is too small
638
- if (!customGlyph && this._config.fontSize >= 12) {
639
- // This only works when transparency is disabled because it's not clear how to clear stroked
640
- // text
641
- if (!this._config.allowTransparency && chars !== ' ') {
642
- // Measure the text, only draw the stroke if there is a descent beyond an alphabetic text
643
- // baseline
644
- this._tmpCtx.save();
645
- this._tmpCtx.textBaseline = 'alphabetic';
646
- const metrics = this._tmpCtx.measureText(chars);
647
- this._tmpCtx.restore();
648
- if ('actualBoundingBoxDescent' in metrics && metrics.actualBoundingBoxDescent > 0) {
649
- // This translates to 1/2 the line width in either direction
650
- this._tmpCtx.save();
651
- // Clip the region to only draw in valid pixels near the underline to avoid a slight
652
- // outline around the whole glyph, as well as additional pixels in the glyph at the top
653
- // which would increase GPU memory demands
654
- const clipRegion = new Path2D();
655
- clipRegion.rect(xLeft, yTop - Math.ceil(lineWidth / 2), this._config.deviceCellWidth * chWidth, yBot - yTop + Math.ceil(lineWidth / 2));
656
- this._tmpCtx.clip(clipRegion);
657
- this._tmpCtx.lineWidth = this._config.devicePixelRatio * 3;
658
- this._tmpCtx.strokeStyle = backgroundColor.css;
659
- this._tmpCtx.strokeText(chars, padding, padding + this._config.deviceCharHeight);
660
- this._tmpCtx.restore();
661
- }
662
- }
663
- }
664
- }
665
-
666
- // Overline
667
- if (overline) {
668
- const lineWidth = Math.max(1, Math.floor(this._config.fontSize * this._config.devicePixelRatio / 15));
669
- const yOffset = lineWidth % 2 === 1 ? 0.5 : 0;
670
- this._tmpCtx.lineWidth = lineWidth;
671
- this._tmpCtx.strokeStyle = this._tmpCtx.fillStyle;
672
- this._tmpCtx.beginPath();
673
- this._tmpCtx.moveTo(padding, padding + yOffset);
674
- this._tmpCtx.lineTo(padding + this._config.deviceCharWidth * chWidth, padding + yOffset);
675
- this._tmpCtx.stroke();
676
- }
677
-
678
- // Draw the character
679
- if (!customGlyph) {
680
- this._tmpCtx.fillText(chars, padding, padding + this._config.deviceCharHeight);
681
- }
682
-
683
- // If this character is underscore and beyond the cell bounds, shift it up until it is visible
684
- // even on the bottom row, try for a maximum of 5 pixels.
685
- if (chars === '_' && !this._config.allowTransparency) {
686
- let isBeyondCellBounds = clearColor(this._tmpCtx.getImageData(padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight), backgroundColor, foregroundColor, enableClearThresholdCheck);
687
- if (isBeyondCellBounds) {
688
- for (let offset = 1; offset <= 5; offset++) {
689
- this._tmpCtx.save();
690
- this._tmpCtx.fillStyle = backgroundColor.css;
691
- this._tmpCtx.fillRect(0, 0, this._tmpCanvas.width, this._tmpCanvas.height);
692
- this._tmpCtx.restore();
693
- this._tmpCtx.fillText(chars, padding, padding + this._config.deviceCharHeight - offset);
694
- isBeyondCellBounds = clearColor(this._tmpCtx.getImageData(padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight), backgroundColor, foregroundColor, enableClearThresholdCheck);
695
- if (!isBeyondCellBounds) {
696
- break;
697
- }
698
- }
699
- }
700
- }
701
-
702
- // Draw strokethrough
703
- if (strikethrough) {
704
- const lineWidth = Math.max(1, Math.floor(this._config.fontSize * this._config.devicePixelRatio / 10));
705
- const yOffset = this._tmpCtx.lineWidth % 2 === 1 ? 0.5 : 0; // When the width is odd, draw at 0.5 position
706
- this._tmpCtx.lineWidth = lineWidth;
707
- this._tmpCtx.strokeStyle = this._tmpCtx.fillStyle;
708
- this._tmpCtx.beginPath();
709
- this._tmpCtx.moveTo(padding, padding + Math.floor(this._config.deviceCharHeight / 2) - yOffset);
710
- this._tmpCtx.lineTo(padding + this._config.deviceCharWidth * chWidth, padding + Math.floor(this._config.deviceCharHeight / 2) - yOffset);
711
- this._tmpCtx.stroke();
712
- }
713
-
714
- this._tmpCtx.restore();
715
-
716
- // clear the background from the character to avoid issues with drawing over the previous
717
- // character if it extends past it's bounds
718
- const imageData = this._tmpCtx.getImageData(
719
- 0, 0, this._tmpCanvas.width, this._tmpCanvas.height
720
- );
721
-
722
- // Clear out the background color and determine if the glyph is empty.
723
- let isEmpty: boolean;
724
- if (!this._config.allowTransparency) {
725
- isEmpty = clearColor(imageData, backgroundColor, foregroundColor, enableClearThresholdCheck);
726
- } else {
727
- isEmpty = checkCompletelyTransparent(imageData);
728
- }
729
-
730
- // Handle empty glyphs
731
- if (isEmpty) {
732
- return NULL_RASTERIZED_GLYPH;
733
- }
734
-
735
- const rasterizedGlyph = this._findGlyphBoundingBox(imageData, this._workBoundingBox, allowedWidth, restrictedPowerlineGlyph, customGlyph, padding);
736
-
737
- // Find the best atlas row to use
738
- let activePage: AtlasPage;
739
- let activeRow: ICharAtlasActiveRow;
740
- while (true) {
741
- // If there are no active pages (the last smallest 4 were merged), create a new one
742
- if (this._activePages.length === 0) {
743
- const newPage = this._createNewPage();
744
- activePage = newPage;
745
- activeRow = newPage.currentRow;
746
- activeRow.height = rasterizedGlyph.size.y;
747
- break;
748
- }
749
-
750
- // Get the best current row from all active pages
751
- activePage = this._activePages[this._activePages.length - 1];
752
- activeRow = activePage.currentRow;
753
- for (const p of this._activePages) {
754
- if (rasterizedGlyph.size.y <= p.currentRow.height) {
755
- activePage = p;
756
- activeRow = p.currentRow;
757
- }
758
- }
759
-
760
- // TODO: This algorithm could be simplified:
761
- // - Search for the page with ROW_PIXEL_THRESHOLD in mind
762
- // - Keep track of current/fixed rows in a Map
763
-
764
- // Replace the best current row with a fixed row if there is one at least as good as the
765
- // current row. Search in reverse to prioritize filling in older pages.
766
- for (let i = this._activePages.length - 1; i >= 0; i--) {
767
- for (const row of this._activePages[i].fixedRows) {
768
- if (row.height <= activeRow.height && rasterizedGlyph.size.y <= row.height) {
769
- activePage = this._activePages[i];
770
- activeRow = row;
771
- }
772
- }
773
- }
774
-
775
- // Create a new page if too much vertical space would be wasted or there is not enough room
776
- // left in the page. The previous active row will become fixed in the process as it now has a
777
- // fixed height
778
- if (activeRow.y + rasterizedGlyph.size.y >= activePage.canvas.height || activeRow.height > rasterizedGlyph.size.y + Constants.ROW_PIXEL_THRESHOLD) {
779
- // Create the new fixed height row, creating a new page if there isn't enough room on the
780
- // current page
781
- let wasPageAndRowFound = false;
782
- if (activePage.currentRow.y + activePage.currentRow.height + rasterizedGlyph.size.y >= activePage.canvas.height) {
783
- // Find the first page with room to create the new row on
784
- let candidatePage: AtlasPage | undefined;
785
- for (const p of this._activePages) {
786
- if (p.currentRow.y + p.currentRow.height + rasterizedGlyph.size.y < p.canvas.height) {
787
- candidatePage = p;
788
- break;
789
- }
790
- }
791
- if (candidatePage) {
792
- activePage = candidatePage;
793
- } else {
794
- // Before creating a new atlas page that would trigger a page merge, check if the
795
- // current active row is sufficient when ignoring the ROW_PIXEL_THRESHOLD. This will
796
- // improve texture utilization by using the available space before the page is merged
797
- // and becomes static.
798
- if (
799
- TextureAtlas.maxAtlasPages &&
800
- this._pages.length >= TextureAtlas.maxAtlasPages &&
801
- activeRow.y + rasterizedGlyph.size.y <= activePage.canvas.height &&
802
- activeRow.height >= rasterizedGlyph.size.y &&
803
- activeRow.x + rasterizedGlyph.size.x <= activePage.canvas.width
804
- ) {
805
- // activePage and activeRow is already valid
806
- wasPageAndRowFound = true;
807
- } else {
808
- // Create a new page if there is no room
809
- const newPage = this._createNewPage();
810
- activePage = newPage;
811
- activeRow = newPage.currentRow;
812
- activeRow.height = rasterizedGlyph.size.y;
813
- wasPageAndRowFound = true;
814
- }
815
- }
816
- }
817
- if (!wasPageAndRowFound) {
818
- // Fix the current row as the new row is being added below
819
- if (activePage.currentRow.height > 0) {
820
- activePage.fixedRows.push(activePage.currentRow);
821
- }
822
- activeRow = {
823
- x: 0,
824
- y: activePage.currentRow.y + activePage.currentRow.height,
825
- height: rasterizedGlyph.size.y
826
- };
827
- activePage.fixedRows.push(activeRow);
828
-
829
- // Create the new current row below the new fixed height row
830
- activePage.currentRow = {
831
- x: 0,
832
- y: activeRow.y + activeRow.height,
833
- height: 0
834
- };
835
- }
836
- // TODO: Remove pages from _activePages when all rows are filled
837
- }
838
-
839
- // Exit the loop if there is enough room in the row
840
- if (activeRow.x + rasterizedGlyph.size.x <= activePage.canvas.width) {
841
- break;
842
- }
843
-
844
- // If there is not enough room in the current row, finish it and try again
845
- if (activeRow === activePage.currentRow) {
846
- activeRow.x = 0;
847
- activeRow.y += activeRow.height;
848
- activeRow.height = 0;
849
- } else {
850
- activePage.fixedRows.splice(activePage.fixedRows.indexOf(activeRow), 1);
851
- }
852
- }
853
-
854
- // Record texture position
855
- rasterizedGlyph.texturePage = this._pages.indexOf(activePage);
856
- rasterizedGlyph.texturePosition.x = activeRow.x;
857
- rasterizedGlyph.texturePosition.y = activeRow.y;
858
- rasterizedGlyph.texturePositionClipSpace.x = activeRow.x / activePage.canvas.width;
859
- rasterizedGlyph.texturePositionClipSpace.y = activeRow.y / activePage.canvas.height;
860
-
861
- // Fix the clipspace position as pages may be of differing size
862
- rasterizedGlyph.sizeClipSpace.x /= activePage.canvas.width;
863
- rasterizedGlyph.sizeClipSpace.y /= activePage.canvas.height;
864
-
865
- // Update atlas current row, for fixed rows the glyph height will never be larger than the row
866
- // height
867
- activeRow.height = Math.max(activeRow.height, rasterizedGlyph.size.y);
868
- activeRow.x += rasterizedGlyph.size.x;
869
-
870
- // putImageData doesn't do any blending, so it will overwrite any existing cache entry for us
871
- activePage.ctx.putImageData(
872
- imageData,
873
- rasterizedGlyph.texturePosition.x - this._workBoundingBox.left,
874
- rasterizedGlyph.texturePosition.y - this._workBoundingBox.top,
875
- this._workBoundingBox.left,
876
- this._workBoundingBox.top,
877
- rasterizedGlyph.size.x,
878
- rasterizedGlyph.size.y
879
- );
880
- activePage.addGlyph(rasterizedGlyph);
881
- activePage.version++;
882
-
883
- return rasterizedGlyph;
884
- }
885
-
886
- /**
887
- * Given an ImageData object, find the bounding box of the non-transparent
888
- * portion of the texture and return an IRasterizedGlyph with these
889
- * dimensions.
890
- * @param imageData The image data to read.
891
- * @param boundingBox An IBoundingBox to put the clipped bounding box values.
892
- */
893
- private _findGlyphBoundingBox(imageData: ImageData, boundingBox: IBoundingBox, allowedWidth: number, restrictedGlyph: boolean, customGlyph: boolean, padding: number): IRasterizedGlyph {
894
- boundingBox.top = 0;
895
- const height = restrictedGlyph ? this._config.deviceCellHeight : this._tmpCanvas.height;
896
- const width = restrictedGlyph ? this._config.deviceCellWidth : allowedWidth;
897
- let found = false;
898
- for (let y = 0; y < height; y++) {
899
- for (let x = 0; x < width; x++) {
900
- const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
901
- if (imageData.data[alphaOffset] !== 0) {
902
- boundingBox.top = y;
903
- found = true;
904
- break;
905
- }
906
- }
907
- if (found) {
908
- break;
909
- }
910
- }
911
- boundingBox.left = 0;
912
- found = false;
913
- for (let x = 0; x < padding + width; x++) {
914
- for (let y = 0; y < height; y++) {
915
- const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
916
- if (imageData.data[alphaOffset] !== 0) {
917
- boundingBox.left = x;
918
- found = true;
919
- break;
920
- }
921
- }
922
- if (found) {
923
- break;
924
- }
925
- }
926
- boundingBox.right = width;
927
- found = false;
928
- for (let x = padding + width - 1; x >= padding; x--) {
929
- for (let y = 0; y < height; y++) {
930
- const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
931
- if (imageData.data[alphaOffset] !== 0) {
932
- boundingBox.right = x;
933
- found = true;
934
- break;
935
- }
936
- }
937
- if (found) {
938
- break;
939
- }
940
- }
941
- boundingBox.bottom = height;
942
- found = false;
943
- for (let y = height - 1; y >= 0; y--) {
944
- for (let x = 0; x < width; x++) {
945
- const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3;
946
- if (imageData.data[alphaOffset] !== 0) {
947
- boundingBox.bottom = y;
948
- found = true;
949
- break;
950
- }
951
- }
952
- if (found) {
953
- break;
954
- }
955
- }
956
- return {
957
- texturePage: 0,
958
- texturePosition: { x: 0, y: 0 },
959
- texturePositionClipSpace: { x: 0, y: 0 },
960
- size: {
961
- x: boundingBox.right - boundingBox.left + 1,
962
- y: boundingBox.bottom - boundingBox.top + 1
963
- },
964
- sizeClipSpace: {
965
- x: (boundingBox.right - boundingBox.left + 1),
966
- y: (boundingBox.bottom - boundingBox.top + 1)
967
- },
968
- offset: {
969
- x: -boundingBox.left + padding + ((restrictedGlyph || customGlyph) ? Math.floor((this._config.deviceCellWidth - this._config.deviceCharWidth) / 2) : 0),
970
- y: -boundingBox.top + padding + ((restrictedGlyph || customGlyph) ? this._config.lineHeight === 1 ? 0 : Math.round((this._config.deviceCellHeight - this._config.deviceCharHeight) / 2) : 0)
971
- }
972
- };
973
- }
974
- }
975
-
976
- class AtlasPage {
977
- public readonly canvas: HTMLCanvasElement;
978
- public readonly ctx: CanvasRenderingContext2D;
979
-
980
- private _usedPixels: number = 0;
981
- public get percentageUsed(): number { return this._usedPixels / (this.canvas.width * this.canvas.height); }
982
-
983
- private readonly _glyphs: IRasterizedGlyph[] = [];
984
- public get glyphs(): ReadonlyArray<IRasterizedGlyph> { return this._glyphs; }
985
- public addGlyph(glyph: IRasterizedGlyph): void {
986
- this._glyphs.push(glyph);
987
- this._usedPixels += glyph.size.x * glyph.size.y;
988
- }
989
-
990
- /**
991
- * Used to check whether the canvas of the atlas page has changed.
992
- */
993
- public version = 0;
994
-
995
- // Texture atlas current positioning data. The texture packing strategy used is to fill from
996
- // left-to-right and top-to-bottom. When the glyph being written is less than half of the current
997
- // row's height, the following happens:
998
- //
999
- // - The current row becomes the fixed height row A
1000
- // - A new fixed height row B the exact size of the glyph is created below the current row
1001
- // - A new dynamic height current row is created below B
1002
- //
1003
- // This strategy does a good job preventing space being wasted for very short glyphs such as
1004
- // underscores, hyphens etc. or those with underlines rendered.
1005
- public currentRow: ICharAtlasActiveRow = {
1006
- x: 0,
1007
- y: 0,
1008
- height: 0
1009
- };
1010
- public readonly fixedRows: ICharAtlasActiveRow[] = [];
1011
-
1012
- constructor(
1013
- document: Document,
1014
- size: number,
1015
- sourcePages?: AtlasPage[]
1016
- ) {
1017
- if (sourcePages) {
1018
- for (const p of sourcePages) {
1019
- this._glyphs.push(...p.glyphs);
1020
- this._usedPixels += p._usedPixels;
1021
- }
1022
- }
1023
- this.canvas = createCanvas(document, size, size);
1024
- // The canvas needs alpha because we use clearColor to convert the background color to alpha.
1025
- // It might also contain some characters with transparent backgrounds if allowTransparency is
1026
- // set.
1027
- this.ctx = throwIfFalsy(this.canvas.getContext('2d', { alpha: true }));
1028
- }
1029
-
1030
- public clear(): void {
1031
- this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
1032
- this.currentRow.x = 0;
1033
- this.currentRow.y = 0;
1034
- this.currentRow.height = 0;
1035
- this.fixedRows.length = 0;
1036
- this.version++;
1037
- }
1038
- }
1039
-
1040
- /**
1041
- * Makes a particular rgb color and colors that are nearly the same in an ImageData completely
1042
- * transparent.
1043
- * @returns True if the result is "empty", meaning all pixels are fully transparent.
1044
- */
1045
- function clearColor(imageData: ImageData, bg: IColor, fg: IColor, enableThresholdCheck: boolean): boolean {
1046
- // Get color channels
1047
- const r = bg.rgba >>> 24;
1048
- const g = bg.rgba >>> 16 & 0xFF;
1049
- const b = bg.rgba >>> 8 & 0xFF;
1050
- const fgR = fg.rgba >>> 24;
1051
- const fgG = fg.rgba >>> 16 & 0xFF;
1052
- const fgB = fg.rgba >>> 8 & 0xFF;
1053
-
1054
- // Calculate a threshold that when below a color will be treated as transpart when the sum of
1055
- // channel value differs. This helps improve rendering when glyphs overlap with others. This
1056
- // threshold is calculated relative to the difference between the background and foreground to
1057
- // ensure important details of the glyph are always shown, even when the contrast ratio is low.
1058
- // The number 12 is largely arbitrary to ensure the pixels that escape the cell in the test case
1059
- // were covered (fg=#8ae234, bg=#c4a000).
1060
- const threshold = Math.floor((Math.abs(r - fgR) + Math.abs(g - fgG) + Math.abs(b - fgB)) / 12);
1061
-
1062
- // Set alpha channel of relevent pixels to 0
1063
- let isEmpty = true;
1064
- for (let offset = 0; offset < imageData.data.length; offset += 4) {
1065
- // Check exact match
1066
- if (imageData.data[offset] === r &&
1067
- imageData.data[offset + 1] === g &&
1068
- imageData.data[offset + 2] === b) {
1069
- imageData.data[offset + 3] = 0;
1070
- } else {
1071
- // Check the threshold based difference
1072
- if (enableThresholdCheck &&
1073
- (Math.abs(imageData.data[offset] - r) +
1074
- Math.abs(imageData.data[offset + 1] - g) +
1075
- Math.abs(imageData.data[offset + 2] - b)) < threshold) {
1076
- imageData.data[offset + 3] = 0;
1077
- } else {
1078
- isEmpty = false;
1079
- }
1080
- }
1081
- }
1082
-
1083
- return isEmpty;
1084
- }
1085
-
1086
- function checkCompletelyTransparent(imageData: ImageData): boolean {
1087
- for (let offset = 0; offset < imageData.data.length; offset += 4) {
1088
- if (imageData.data[offset + 3] > 0) {
1089
- return false;
1090
- }
1091
- }
1092
- return true;
1093
- }
1094
-
1095
- function createCanvas(document: Document, width: number, height: number): HTMLCanvasElement {
1096
- const canvas = document.createElement('canvas');
1097
- canvas.width = width;
1098
- canvas.height = height;
1099
- return canvas;
1100
- }