@xterm/xterm 5.4.0-beta.1

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