Debian Codegraph @

node/@xterm/addon-webgl/src/WebglRenderer.ts

raw
1 /**
2 * Copyright (c) 2018 The xterm.js authors. All rights reserved.
3 * @license MIT
4 */
5
6 import { ITerminal } from 'browser/Types';
7 import { CellColorResolver } from './CellColorResolver';
8 import { acquireTextureAtlas, removeTerminalFromCache } from './CharAtlasCache';
9 import { CursorBlinkStateManager } from './CursorBlinkStateManager';
10 import { observeDevicePixelDimensions } from './DevicePixelObserver';
11 import { IRenderDimensions, IRenderer, IRequestRedrawEvent } from 'browser/renderer/shared/Types';
12 import { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, IThemeService } from 'browser/services/Services';
13 import { CharData, IBufferLine, ICellData } from 'common/Types';
14 import { AttributeData } from 'common/buffer/AttributeData';
15 import { CellData } from 'common/buffer/CellData';
16 import { Attributes, Content, NULL_CELL_CHAR, NULL_CELL_CODE } from 'common/buffer/Constants';
17 import { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';
18 import { Terminal } from '@xterm/xterm';
19 import { GlyphRenderer } from './GlyphRenderer';
20 import { RectangleRenderer } from './RectangleRenderer';
21 import { COMBINED_CHAR_BIT_MASK, RENDER_MODEL_BG_OFFSET, RENDER_MODEL_EXT_OFFSET, RENDER_MODEL_FG_OFFSET, RENDER_MODEL_INDICIES_PER_CELL, RenderModel } from './RenderModel';
22 import { IWebGL2RenderingContext, type ITextureAtlas } from './Types';
23 import { LinkRenderLayer } from './renderLayer/LinkRenderLayer';
24 import { IRenderLayer } from './renderLayer/Types';
25 import { Emitter, Event } from 'vs/base/common/event';
26 import { addDisposableListener } from 'vs/base/browser/dom';
27 import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
28 import { createRenderDimensions } from 'browser/renderer/shared/RendererUtils';
29
30 export class WebglRenderer extends Disposable implements IRenderer {
31 private _renderLayers: IRenderLayer[];
32 private _cursorBlinkStateManager: MutableDisposable<CursorBlinkStateManager> = new MutableDisposable();
33 private _charAtlasDisposable = this._register(new MutableDisposable());
34 private _charAtlas: ITextureAtlas | undefined;
35 private _devicePixelRatio: number;
36 private _deviceMaxTextureSize: number;
37 private _observerDisposable = this._register(new MutableDisposable());
38
39 private _model: RenderModel = new RenderModel();
40 private _workCell: ICellData = new CellData();
41 private _workCell2: ICellData = new CellData();
42 private _cellColorResolver: CellColorResolver;
43
44 private _canvas: HTMLCanvasElement;
45 private _gl: IWebGL2RenderingContext;
46 private _rectangleRenderer: MutableDisposable<RectangleRenderer> = this._register(new MutableDisposable());
47 private _glyphRenderer: MutableDisposable<GlyphRenderer> = this._register(new MutableDisposable());
48
49 public readonly dimensions: IRenderDimensions;
50
51 private _core: ITerminal;
52 private _isAttached: boolean;
53 private _contextRestorationTimeout: number | undefined;
54
55 private readonly _onChangeTextureAtlas = this._register(new Emitter<HTMLCanvasElement>());
56 public readonly onChangeTextureAtlas = this._onChangeTextureAtlas.event;
57 private readonly _onAddTextureAtlasCanvas = this._register(new Emitter<HTMLCanvasElement>());
58 public readonly onAddTextureAtlasCanvas = this._onAddTextureAtlasCanvas.event;
59 private readonly _onRemoveTextureAtlasCanvas = this._register(new Emitter<HTMLCanvasElement>());
60 public readonly onRemoveTextureAtlasCanvas = this._onRemoveTextureAtlasCanvas.event;
61 private readonly _onRequestRedraw = this._register(new Emitter<IRequestRedrawEvent>());
62 public readonly onRequestRedraw = this._onRequestRedraw.event;
63 private readonly _onContextLoss = this._register(new Emitter<void>());
64 public readonly onContextLoss = this._onContextLoss.event;
65
66 constructor(
67 private _terminal: Terminal,
68 private readonly _characterJoinerService: ICharacterJoinerService,
69 private readonly _charSizeService: ICharSizeService,
70 private readonly _coreBrowserService: ICoreBrowserService,
71 private readonly _coreService: ICoreService,
72 private readonly _decorationService: IDecorationService,
73 private readonly _optionsService: IOptionsService,
74 private readonly _themeService: IThemeService,
75 preserveDrawingBuffer?: boolean
76 ) {
77 super();
78
79 // IMPORTANT: Canvas initialization and fetching of the context must be first in order to
80 // prevent possible listeners leaking and continuing to operate after the WebglRenderer has been
81 // discarded.
82 this._canvas = this._coreBrowserService.mainDocument.createElement('canvas');
83 const contextAttributes = {
84 antialias: false,
85 depth: false,
86 preserveDrawingBuffer
87 };
88 this._gl = this._canvas.getContext('webgl2', contextAttributes) as IWebGL2RenderingContext;
89 if (!this._gl) {
90 throw new Error('WebGL2 not supported ' + this._gl);
91 }
92
93 this._register(this._themeService.onChangeColors(() => this._handleColorChange()));
94
95 this._cellColorResolver = new CellColorResolver(this._terminal, this._optionsService, this._model.selection, this._decorationService, this._coreBrowserService, this._themeService);
96
97 this._core = (this._terminal as any)._core;
98
99 this._renderLayers = [
100 new LinkRenderLayer(this._core.screenElement!, 2, this._terminal, this._core.linkifier!, this._coreBrowserService, _optionsService, this._themeService)
101 ];
102 this.dimensions = createRenderDimensions();
103 this._devicePixelRatio = this._coreBrowserService.dpr;
104 this._updateDimensions();
105 this._updateCursorBlink();
106 this._register(_optionsService.onOptionChange(() => this._handleOptionsChanged()));
107
108 this._deviceMaxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
109
110 this._register(addDisposableListener(this._canvas, 'webglcontextlost', (e) => {
111 console.log('webglcontextlost event received');
112 // Prevent the default behavior in order to enable WebGL context restoration.
113 e.preventDefault();
114 // Wait a few seconds to see if the 'webglcontextrestored' event is fired.
115 // If not, dispatch the onContextLoss notification to observers.
116 this._contextRestorationTimeout = setTimeout(() => {
117 this._contextRestorationTimeout = undefined;
118 console.warn('webgl context not restored; firing onContextLoss');
119 this._onContextLoss.fire(e);
120 }, 3000 /* ms */);
121 }));
122 this._register(addDisposableListener(this._canvas, 'webglcontextrestored', (e) => {
123 console.warn('webglcontextrestored event received');
124 clearTimeout(this._contextRestorationTimeout);
125 this._contextRestorationTimeout = undefined;
126 // The texture atlas and glyph renderer must be fully reinitialized
127 // because their contents have been lost.
128 removeTerminalFromCache(this._terminal);
129 this._initializeWebGLState();
130 this._requestRedrawViewport();
131 }));
132
133 this._observerDisposable.value = observeDevicePixelDimensions(this._canvas, this._coreBrowserService.window, (w, h) => this._setCanvasDevicePixelDimensions(w, h));
134 this._register(this._coreBrowserService.onWindowChange(w => {
135 this._observerDisposable.value = observeDevicePixelDimensions(this._canvas, w, (w, h) => this._setCanvasDevicePixelDimensions(w, h));
136 }));
137
138 this._core.screenElement!.appendChild(this._canvas);
139
140 [this._rectangleRenderer.value, this._glyphRenderer.value] = this._initializeWebGLState();
141
142 this._isAttached = this._core.screenElement!.isConnected;
143
144 this._register(toDisposable(() => {
145 for (const l of this._renderLayers) {
146 l.dispose();
147 }
148 this._canvas.parentElement?.removeChild(this._canvas);
149 removeTerminalFromCache(this._terminal);
150 }));
151 }
152
153 public get textureAtlas(): HTMLCanvasElement | undefined {
154 return this._charAtlas?.pages[0].canvas;
155 }
156
157 private _handleColorChange(): void {
158 this._refreshCharAtlas();
159
160 // Force a full refresh
161 this._clearModel(true);
162 }
163
164 public handleDevicePixelRatioChange(): void {
165 // If the device pixel ratio changed, the char atlas needs to be regenerated
166 // and the terminal needs to refreshed
167 if (this._devicePixelRatio !== this._coreBrowserService.dpr) {
168 this._devicePixelRatio = this._coreBrowserService.dpr;
169 this.handleResize(this._terminal.cols, this._terminal.rows);
170 }
171 }
172
173 public handleResize(cols: number, rows: number): void {
174 // Update character and canvas dimensions
175 this._updateDimensions();
176
177 this._model.resize(this._terminal.cols, this._terminal.rows);
178
179 // Resize all render layers
180 for (const l of this._renderLayers) {
181 l.resize(this._terminal, this.dimensions);
182 }
183
184 // Resize the canvas
185 this._canvas.width = this.dimensions.device.canvas.width;
186 this._canvas.height = this.dimensions.device.canvas.height;
187 this._canvas.style.width = `${this.dimensions.css.canvas.width}px`;
188 this._canvas.style.height = `${this.dimensions.css.canvas.height}px`;
189
190 // Resize the screen
191 this._core.screenElement!.style.width = `${this.dimensions.css.canvas.width}px`;
192 this._core.screenElement!.style.height = `${this.dimensions.css.canvas.height}px`;
193
194 this._rectangleRenderer.value?.setDimensions(this.dimensions);
195 this._rectangleRenderer.value?.handleResize();
196 this._glyphRenderer.value?.setDimensions(this.dimensions);
197 this._glyphRenderer.value?.handleResize();
198
199 this._refreshCharAtlas();
200
201 // Force a full refresh. Resizing `_glyphRenderer` should clear it already,
202 // so there is no need to clear it again here.
203 this._clearModel(false);
204 }
205
206 public handleCharSizeChanged(): void {
207 this.handleResize(this._terminal.cols, this._terminal.rows);
208 }
209
210 public handleBlur(): void {
211 for (const l of this._renderLayers) {
212 l.handleBlur(this._terminal);
213 }
214 this._cursorBlinkStateManager.value?.pause();
215 // Request a redraw for active/inactive selection background
216 this._requestRedrawViewport();
217 }
218
219 public handleFocus(): void {
220 for (const l of this._renderLayers) {
221 l.handleFocus(this._terminal);
222 }
223 this._cursorBlinkStateManager.value?.resume();
224 // Request a redraw for active/inactive selection background
225 this._requestRedrawViewport();
226 }
227
228 public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
229 for (const l of this._renderLayers) {
230 l.handleSelectionChanged(this._terminal, start, end, columnSelectMode);
231 }
232 this._model.selection.update(this._core, start, end, columnSelectMode);
233 this._requestRedrawViewport();
234 }
235
236 public handleCursorMove(): void {
237 for (const l of this._renderLayers) {
238 l.handleCursorMove(this._terminal);
239 }
240 this._cursorBlinkStateManager.value?.restartBlinkAnimation();
241 }
242
243 private _handleOptionsChanged(): void {
244 this._updateDimensions();
245 this._refreshCharAtlas();
246 this._updateCursorBlink();
247 }
248
249 /**
250 * Initializes members dependent on WebGL context state.
251 */
252 private _initializeWebGLState(): [RectangleRenderer, GlyphRenderer] {
253 this._rectangleRenderer.value = new RectangleRenderer(this._terminal, this._gl, this.dimensions, this._themeService);
254 this._glyphRenderer.value = new GlyphRenderer(this._terminal, this._gl, this.dimensions, this._optionsService);
255
256 // Update dimensions and acquire char atlas
257 this.handleCharSizeChanged();
258
259 return [this._rectangleRenderer.value, this._glyphRenderer.value];
260 }
261
262 /**
263 * Refreshes the char atlas, aquiring a new one if necessary.
264 */
265 private _refreshCharAtlas(): void {
266 if (this.dimensions.device.char.width <= 0 && this.dimensions.device.char.height <= 0) {
267 // Mark as not attached so char atlas gets refreshed on next render
268 this._isAttached = false;
269 return;
270 }
271
272 const atlas = acquireTextureAtlas(
273 this._terminal,
274 this._optionsService.rawOptions,
275 this._themeService.colors,
276 this.dimensions.device.cell.width,
277 this.dimensions.device.cell.height,
278 this.dimensions.device.char.width,
279 this.dimensions.device.char.height,
280 this._coreBrowserService.dpr,
281 this._deviceMaxTextureSize
282 );
283 if (this._charAtlas !== atlas) {
284 this._onChangeTextureAtlas.fire(atlas.pages[0].canvas);
285 this._charAtlasDisposable.value = combinedDisposable(
286 Event.forward(atlas.onAddTextureAtlasCanvas, this._onAddTextureAtlasCanvas),
287 Event.forward(atlas.onRemoveTextureAtlasCanvas, this._onRemoveTextureAtlasCanvas)
288 );
289 }
290 this._charAtlas = atlas;
291 this._charAtlas.warmUp();
292 this._glyphRenderer.value?.setAtlas(this._charAtlas);
293 }
294
295 /**
296 * Clear the model.
297 * @param clearGlyphRenderer Whether to also clear the glyph renderer. This
298 * should be true generally to make sure it is in the same state as the model.
299 */
300 private _clearModel(clearGlyphRenderer: boolean): void {
301 this._model.clear();
302 if (clearGlyphRenderer) {
303 this._glyphRenderer.value?.clear();
304 }
305 }
306
307 public clearTextureAtlas(): void {
308 this._charAtlas?.clearTexture();
309 this._clearModel(true);
310 this._requestRedrawViewport();
311 }
312
313 public clear(): void {
314 this._clearModel(true);
315 for (const l of this._renderLayers) {
316 l.reset(this._terminal);
317 }
318
319 this._cursorBlinkStateManager.value?.restartBlinkAnimation();
320 this._updateCursorBlink();
321 }
322
323 public renderRows(start: number, end: number): void {
324 if (!this._isAttached) {
325 if (this._core.screenElement?.isConnected && this._charSizeService.width && this._charSizeService.height) {
326 this._updateDimensions();
327 this._refreshCharAtlas();
328 this._isAttached = true;
329 } else {
330 return;
331 }
332 }
333
334 // Update render layers
335 for (const l of this._renderLayers) {
336 l.handleGridChanged(this._terminal, start, end);
337 }
338
339 if (!this._glyphRenderer.value || !this._rectangleRenderer.value) {
340 return;
341 }
342
343 // Tell renderer the frame is beginning
344 // upon a model clear also refresh the full viewport model
345 // (also triggered by an atlas page merge, part of #4480)
346 if (this._glyphRenderer.value.beginFrame()) {
347 this._clearModel(true);
348 this._updateModel(0, this._terminal.rows - 1);
349 } else {
350 // just update changed lines to draw
351 this._updateModel(start, end);
352 }
353
354 // Render
355 this._rectangleRenderer.value.renderBackgrounds();
356 this._glyphRenderer.value.render(this._model);
357 if (!this._cursorBlinkStateManager.value || this._cursorBlinkStateManager.value.isCursorVisible) {
358 this._rectangleRenderer.value.renderCursor();
359 }
360 }
361
362 private _updateCursorBlink(): void {
363 if (this._coreService.decPrivateModes.cursorBlink ?? this._terminal.options.cursorBlink) {
364 this._cursorBlinkStateManager.value = new CursorBlinkStateManager(() => {
365 this._requestRedrawCursor();
366 }, this._coreBrowserService);
367 } else {
368 this._cursorBlinkStateManager.clear();
369 }
370 // Request a refresh from the terminal as management of rendering is being
371 // moved back to the terminal
372 this._requestRedrawCursor();
373 }
374
375 private _updateModel(start: number, end: number): void {
376 const terminal = this._core;
377 let cell: ICellData = this._workCell;
378
379 // Declare variable ahead of time to avoid garbage collection
380 let lastBg: number;
381 let y: number;
382 let row: number;
383 let line: IBufferLine;
384 let joinedRanges: [number, number][];
385 let isJoined: boolean;
386 let skipJoinedCheckUntilX: number = 0;
387 let isValidJoinRange: boolean = true;
388 let lastCharX: number;
389 let range: [number, number];
390 let isCursorRow: boolean;
391 let chars: string;
392 let code: number;
393 let width: number;
394 let i: number;
395 let x: number;
396 let j: number;
397 start = clamp(start, terminal.rows - 1, 0);
398 end = clamp(end, terminal.rows - 1, 0);
399 const cursorStyle = this._coreService.decPrivateModes.cursorStyle ?? terminal.options.cursorStyle ?? 'block';
400
401 const cursorY = this._terminal.buffer.active.baseY + this._terminal.buffer.active.cursorY;
402 const viewportRelativeCursorY = cursorY - terminal.buffer.ydisp;
403 // in case cursor.x == cols adjust visual cursor to cols - 1
404 const cursorX = Math.min(this._terminal.buffer.active.cursorX, terminal.cols - 1);
405 let lastCursorX = -1;
406 const isCursorVisible =
407 this._coreService.isCursorInitialized &&
408 !this._coreService.isCursorHidden &&
409 (!this._cursorBlinkStateManager.value || this._cursorBlinkStateManager.value.isCursorVisible);
410 this._model.cursor = undefined;
411 let modelUpdated = false;
412
413 for (y = start; y <= end; y++) {
414 row = y + terminal.buffer.ydisp;
415 line = terminal.buffer.lines.get(row)!;
416 this._model.lineLengths[y] = 0;
417 isCursorRow = cursorY === row;
418 skipJoinedCheckUntilX = 0;
419 joinedRanges = this._characterJoinerService.getJoinedCharacters(row);
420 for (x = 0; x < terminal.cols; x++) {
421 lastBg = this._cellColorResolver.result.bg;
422 line.loadCell(x, cell);
423
424 if (x === 0) {
425 lastBg = this._cellColorResolver.result.bg;
426 }
427
428 // If true, indicates that the current character(s) to draw were joined.
429 isJoined = false;
430
431 // Indicates whether this cell is part of a joined range that should be ignored as it cannot
432 // be rendered entirely, like the selection state differs across the range.
433 isValidJoinRange = (x >= skipJoinedCheckUntilX);
434
435 lastCharX = x;
436
437 // Process any joined character ranges as needed. Because of how the
438 // ranges are produced, we know that they are valid for the characters
439 // and attributes of our input.
440 if (joinedRanges.length > 0 && x === joinedRanges[0][0] && isValidJoinRange) {
441 range = joinedRanges.shift()!;
442
443 // If the ligature's selection state is not consistent, don't join it. This helps the
444 // selection render correctly regardless whether they should be joined.
445 const firstSelectionState = this._model.selection.isCellSelected(this._terminal, range[0], row);
446 for (i = range[0] + 1; i < range[1]; i++) {
447 isValidJoinRange &&= (firstSelectionState === this._model.selection.isCellSelected(this._terminal, i, row));
448 }
449 // Similarly, if the cursor is in the ligature, don't join it.
450 isValidJoinRange &&= !isCursorRow || cursorX < range[0] || cursorX >= range[1];
451 if (!isValidJoinRange) {
452 skipJoinedCheckUntilX = range[1];
453 } else {
454 isJoined = true;
455
456 // We already know the exact start and end column of the joined range,
457 // so we get the string and width representing it directly.
458 cell = new JoinedCellData(
459 cell,
460 line!.translateToString(true, range[0], range[1]),
461 range[1] - range[0]
462 );
463
464 // Skip over the cells occupied by this range in the loop
465 lastCharX = range[1] - 1;
466 }
467 }
468
469 chars = cell.getChars();
470 code = cell.getCode();
471 i = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
472
473 // Load colors/resolve overrides into work colors
474 this._cellColorResolver.resolve(cell, x, row, this.dimensions.device.cell.width);
475
476 // Override colors for cursor cell
477 if (isCursorVisible && row === cursorY) {
478 if (x === cursorX) {
479 this._model.cursor = {
480 x: cursorX,
481 y: viewportRelativeCursorY,
482 width: cell.getWidth(),
483 style: this._coreBrowserService.isFocused ? cursorStyle : terminal.options.cursorInactiveStyle,
484 cursorWidth: terminal.options.cursorWidth,
485 dpr: this._devicePixelRatio
486 };
487 lastCursorX = cursorX + cell.getWidth() - 1;
488 }
489 if (x >= cursorX && x <= lastCursorX &&
490 ((this._coreBrowserService.isFocused &&
491 cursorStyle === 'block') ||
492 (this._coreBrowserService.isFocused === false &&
493 terminal.options.cursorInactiveStyle === 'block'))
494 ) {
495 this._cellColorResolver.result.fg =
496 Attributes.CM_RGB | (this._themeService.colors.cursorAccent.rgba >> 8 & Attributes.RGB_MASK);
497 this._cellColorResolver.result.bg =
498 Attributes.CM_RGB | (this._themeService.colors.cursor.rgba >> 8 & Attributes.RGB_MASK);
499 }
500 }
501
502 if (code !== NULL_CELL_CODE) {
503 this._model.lineLengths[y] = x + 1;
504 }
505
506 // Nothing has changed, no updates needed
507 if (this._model.cells[i] === code &&
508 this._model.cells[i + RENDER_MODEL_BG_OFFSET] === this._cellColorResolver.result.bg &&
509 this._model.cells[i + RENDER_MODEL_FG_OFFSET] === this._cellColorResolver.result.fg &&
510 this._model.cells[i + RENDER_MODEL_EXT_OFFSET] === this._cellColorResolver.result.ext) {
511 continue;
512 }
513
514 modelUpdated = true;
515
516 // Flag combined chars with a bit mask so they're easily identifiable
517 if (chars.length > 1) {
518 code |= COMBINED_CHAR_BIT_MASK;
519 }
520
521 // Cache the results in the model
522 this._model.cells[i] = code;
523 this._model.cells[i + RENDER_MODEL_BG_OFFSET] = this._cellColorResolver.result.bg;
524 this._model.cells[i + RENDER_MODEL_FG_OFFSET] = this._cellColorResolver.result.fg;
525 this._model.cells[i + RENDER_MODEL_EXT_OFFSET] = this._cellColorResolver.result.ext;
526
527 width = cell.getWidth();
528 this._glyphRenderer.value!.updateCell(x, y, code, this._cellColorResolver.result.bg, this._cellColorResolver.result.fg, this._cellColorResolver.result.ext, chars, width, lastBg);
529
530 if (isJoined) {
531 // Restore work cell
532 cell = this._workCell;
533
534 // Null out non-first cells
535 for (x++; x <= lastCharX; x++) {
536 j = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL;
537 this._glyphRenderer.value!.updateCell(x, y, NULL_CELL_CODE, 0, 0, 0, NULL_CELL_CHAR, 0, 0);
538 this._model.cells[j] = NULL_CELL_CODE;
539 // Don't re-resolve the cell color since multi-colored ligature backgrounds are not
540 // supported
541 this._model.cells[j + RENDER_MODEL_BG_OFFSET] = this._cellColorResolver.result.bg;
542 this._model.cells[j + RENDER_MODEL_FG_OFFSET] = this._cellColorResolver.result.fg;
543 this._model.cells[j + RENDER_MODEL_EXT_OFFSET] = this._cellColorResolver.result.ext;
544 }
545 x--; // Go back to the previous update cell for next iteration
546 }
547 }
548 }
549 if (modelUpdated) {
550 this._rectangleRenderer.value!.updateBackgrounds(this._model);
551 }
552 this._rectangleRenderer.value!.updateCursor(this._model);
553 }
554
555 /**
556 * Recalculates the character and canvas dimensions.
557 */
558 private _updateDimensions(): void {
559 // Perform a new measure if the CharMeasure dimensions are not yet available
560 if (!this._charSizeService.width || !this._charSizeService.height) {
561 return;
562 }
563
564 // Calculate the device character width. Width is floored as it must be drawn to an integer grid
565 // in order for the char atlas glyphs to not be blurry.
566 this.dimensions.device.char.width = Math.floor(this._charSizeService.width * this._devicePixelRatio);
567
568 // Calculate the device character height. Height is ceiled in case devicePixelRatio is a
569 // floating point number in order to ensure there is enough space to draw the character to the
570 // cell.
571 this.dimensions.device.char.height = Math.ceil(this._charSizeService.height * this._devicePixelRatio);
572
573 // Calculate the device cell height, if lineHeight is _not_ 1, the resulting value will be
574 // floored since lineHeight can never be lower then 1, this guarentees the device cell height
575 // will always be larger than device char height.
576 this.dimensions.device.cell.height = Math.floor(this.dimensions.device.char.height * this._optionsService.rawOptions.lineHeight);
577
578 // Calculate the y offset within a cell that glyph should draw at in order for it to be centered
579 // correctly within the cell.
580 this.dimensions.device.char.top = this._optionsService.rawOptions.lineHeight === 1 ? 0 : Math.round((this.dimensions.device.cell.height - this.dimensions.device.char.height) / 2);
581
582 // Calculate the device cell width, taking the letterSpacing into account.
583 this.dimensions.device.cell.width = this.dimensions.device.char.width + Math.round(this._optionsService.rawOptions.letterSpacing);
584
585 // Calculate the x offset with a cell that text should draw from in order for it to be centered
586 // correctly within the cell.
587 this.dimensions.device.char.left = Math.floor(this._optionsService.rawOptions.letterSpacing / 2);
588
589 // Recalculate the canvas dimensions, the device dimensions define the actual number of pixel in
590 // the canvas
591 this.dimensions.device.canvas.height = this._terminal.rows * this.dimensions.device.cell.height;
592 this.dimensions.device.canvas.width = this._terminal.cols * this.dimensions.device.cell.width;
593
594 // The the size of the canvas on the page. It's important that this rounds to nearest integer
595 // and not ceils as browsers often have floating point precision issues where
596 // `window.devicePixelRatio` ends up being something like `1.100000023841858` for example, when
597 // it's actually 1.1. Ceiling may causes blurriness as the backing canvas image is 1 pixel too
598 // large for the canvas element size.
599 this.dimensions.css.canvas.height = Math.round(this.dimensions.device.canvas.height / this._devicePixelRatio);
600 this.dimensions.css.canvas.width = Math.round(this.dimensions.device.canvas.width / this._devicePixelRatio);
601
602 // Get the CSS dimensions of an individual cell. This needs to be derived from the calculated
603 // device pixel canvas value above. CharMeasure.width/height by itself is insufficient when the
604 // page is not at 100% zoom level as CharMeasure is measured in CSS pixels, but the actual char
605 // size on the canvas can differ.
606 this.dimensions.css.cell.height = this.dimensions.device.cell.height / this._devicePixelRatio;
607 this.dimensions.css.cell.width = this.dimensions.device.cell.width / this._devicePixelRatio;
608 }
609
610 private _setCanvasDevicePixelDimensions(width: number, height: number): void {
611 if (this._canvas.width === width && this._canvas.height === height) {
612 return;
613 }
614 // While the actual canvas size has changed, keep device canvas dimensions as the value before
615 // the change as it's an exact multiple of the cell sizes.
616 this._canvas.width = width;
617 this._canvas.height = height;
618 this._requestRedrawViewport();
619 }
620
621 private _requestRedrawViewport(): void {
622 this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1 });
623 }
624
625 private _requestRedrawCursor(): void {
626 const cursorY = this._terminal.buffer.active.cursorY;
627 this._onRequestRedraw.fire({ start: cursorY, end: cursorY });
628 }
629 }
630
631 // TODO: Share impl with core
632 export class JoinedCellData extends AttributeData implements ICellData {
633 private _width: number;
634 // .content carries no meaning for joined CellData, simply nullify it
635 // thus we have to overload all other .content accessors
636 public content: number = 0;
637 public fg: number;
638 public bg: number;
639 public combinedData: string = '';
640
641 constructor(firstCell: ICellData, chars: string, width: number) {
642 super();
643 this.fg = firstCell.fg;
644 this.bg = firstCell.bg;
645 this.combinedData = chars;
646 this._width = width;
647 }
648
649 public isCombined(): number {
650 // always mark joined cell data as combined
651 return Content.IS_COMBINED_MASK;
652 }
653
654 public getWidth(): number {
655 return this._width;
656 }
657
658 public getChars(): string {
659 return this.combinedData;
660 }
661
662 public getCode(): number {
663 // code always gets the highest possible fake codepoint (read as -1)
664 // this is needed as code is used by caches as identifier
665 return 0x1FFFFF;
666 }
667
668 public setFromCharData(value: CharData): void {
669 throw new Error('not implemented');
670 }
671
672 public getAsCharData(): CharData {
673 return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
674 }
675 }
676
677 function clamp(value: number, max: number, min: number = 0): number {
678 return Math.max(Math.min(value, max), min);
679 }