Debian Codegraph @

node/@xterm/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts

raw
1 /**
2 * Copyright (c) 2018, 2023 The xterm.js authors. All rights reserved.
3 * @license MIT
4 */
5
6 import { IBufferLine, ICellData, IColor } from 'common/Types';
7 import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/shared/Constants';
8 import { WHITESPACE_CELL_CHAR, Attributes } from 'common/buffer/Constants';
9 import { CellData } from 'common/buffer/CellData';
10 import { ICoreService, IDecorationService, IOptionsService } from 'common/services/Services';
11 import { channels, color } from 'common/Color';
12 import { ICharacterJoinerService, ICoreBrowserService, IThemeService } from 'browser/services/Services';
13 import { JoinedCellData } from 'browser/services/CharacterJoinerService';
14 import { treatGlyphAsBackgroundColor } from 'browser/renderer/shared/RendererUtils';
15 import { AttributeData } from 'common/buffer/AttributeData';
16 import { WidthCache } from 'browser/renderer/dom/WidthCache';
17 import { IColorContrastCache } from 'browser/Types';
18
19
20 export const enum RowCss {
21 BOLD_CLASS = 'xterm-bold',
22 DIM_CLASS = 'xterm-dim',
23 ITALIC_CLASS = 'xterm-italic',
24 UNDERLINE_CLASS = 'xterm-underline',
25 OVERLINE_CLASS = 'xterm-overline',
26 STRIKETHROUGH_CLASS = 'xterm-strikethrough',
27 CURSOR_CLASS = 'xterm-cursor',
28 CURSOR_BLINK_CLASS = 'xterm-cursor-blink',
29 CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block',
30 CURSOR_STYLE_OUTLINE_CLASS = 'xterm-cursor-outline',
31 CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar',
32 CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline'
33 }
34
35
36 export class DomRendererRowFactory {
37 private _workCell: CellData = new CellData();
38
39 private _selectionStart: [number, number] | undefined;
40 private _selectionEnd: [number, number] | undefined;
41 private _columnSelectMode: boolean = false;
42
43 public defaultSpacing = 0;
44
45 constructor(
46 private readonly _document: Document,
47 @ICharacterJoinerService private readonly _characterJoinerService: ICharacterJoinerService,
48 @IOptionsService private readonly _optionsService: IOptionsService,
49 @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService,
50 @ICoreService private readonly _coreService: ICoreService,
51 @IDecorationService private readonly _decorationService: IDecorationService,
52 @IThemeService private readonly _themeService: IThemeService
53 ) {}
54
55 public handleSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void {
56 this._selectionStart = start;
57 this._selectionEnd = end;
58 this._columnSelectMode = columnSelectMode;
59 }
60
61 public createRow(
62 lineData: IBufferLine,
63 row: number,
64 isCursorRow: boolean,
65 cursorStyle: string | undefined,
66 cursorInactiveStyle: string | undefined,
67 cursorX: number,
68 cursorBlink: boolean,
69 cellWidth: number,
70 widthCache: WidthCache,
71 linkStart: number,
72 linkEnd: number
73 ): HTMLSpanElement[] {
74
75 const elements: HTMLSpanElement[] = [];
76 const joinedRanges = this._characterJoinerService.getJoinedCharacters(row);
77 const colors = this._themeService.colors;
78
79 let lineLength = lineData.getNoBgTrimmedLength();
80 if (isCursorRow && lineLength < cursorX + 1) {
81 lineLength = cursorX + 1;
82 }
83
84 let charElement: HTMLSpanElement | undefined;
85 let cellAmount = 0;
86 let text = '';
87 let i = 0;
88 let oldBg = 0;
89 let oldFg = 0;
90 let oldExt = 0;
91 let oldLinkHover: number | boolean = false;
92 let oldSpacing = 0;
93 let oldIsInSelection: boolean = false;
94 let spacing = 0;
95 let skipJoinedCheckUntilX = 0;
96 const classes: string[] = [];
97
98 const hasHover = linkStart !== -1 && linkEnd !== -1;
99
100 for (let x = 0; x < lineLength; x++) {
101 lineData.loadCell(x, this._workCell);
102 let width = this._workCell.getWidth();
103
104 // The character to the left is a wide character, drawing is owned by the char at x-1
105 if (width === 0) {
106 continue;
107 }
108
109 // If true, indicates that the current character(s) to draw were joined.
110 let isJoined = false;
111
112 // Indicates whether this cell is part of a joined range that should be ignored as it cannot
113 // be rendered entirely, like the selection state differs across the range.
114 let isValidJoinRange = (x >= skipJoinedCheckUntilX);
115
116 let lastCharX = x;
117
118 // Process any joined character ranges as needed. Because of how the
119 // ranges are produced, we know that they are valid for the characters
120 // and attributes of our input.
121 let cell = this._workCell;
122 if (joinedRanges.length > 0 && x === joinedRanges[0][0] && isValidJoinRange) {
123 const range = joinedRanges.shift()!;
124 // If the ligature's selection state is not consistent, don't join it. This helps the
125 // selection render correctly regardless whether they should be joined.
126 const firstSelectionState = this._isCellInSelection(range[0], row);
127 for (i = range[0] + 1; i < range[1]; i++) {
128 isValidJoinRange &&= (firstSelectionState === this._isCellInSelection(i, row));
129 }
130 // Similarly, if the cursor is in the ligature, don't join it.
131 isValidJoinRange &&= !isCursorRow || cursorX < range[0] || cursorX >= range[1];
132 if (!isValidJoinRange) {
133 skipJoinedCheckUntilX = range[1];
134 } else {
135 isJoined = true;
136
137 // We already know the exact start and end column of the joined range,
138 // so we get the string and width representing it directly
139 cell = new JoinedCellData(
140 this._workCell,
141 lineData.translateToString(true, range[0], range[1]),
142 range[1] - range[0]
143 );
144
145 // Skip over the cells occupied by this range in the loop
146 lastCharX = range[1] - 1;
147
148 // Recalculate width
149 width = cell.getWidth();
150 }
151 }
152
153 const isInSelection = this._isCellInSelection(x, row);
154 const isCursorCell = isCursorRow && x === cursorX;
155 const isLinkHover = hasHover && x >= linkStart && x <= linkEnd;
156
157 let isDecorated = false;
158 this._decorationService.forEachDecorationAtCell(x, row, undefined, d => {
159 isDecorated = true;
160 });
161
162 // get chars to render for this cell
163 let chars = cell.getChars() || WHITESPACE_CELL_CHAR;
164 if (chars === ' ' && (cell.isUnderline() || cell.isOverline())) {
165 chars = '\xa0';
166 }
167
168 // lookup char render width and calc spacing
169 spacing = width * cellWidth - widthCache.get(chars, cell.isBold(), cell.isItalic());
170
171 if (!charElement) {
172 charElement = this._document.createElement('span');
173 } else {
174 /**
175 * chars can only be merged on existing span if:
176 * - existing span only contains mergeable chars (cellAmount != 0)
177 * - bg did not change (or both are in selection)
178 * - fg did not change (or both are in selection and selection fg is set)
179 * - ext did not change
180 * - underline from hover state did not change
181 * - cell content renders to same letter-spacing
182 * - cell is not cursor
183 */
184 if (
185 cellAmount
186 && (
187 (isInSelection && oldIsInSelection)
188 || (!isInSelection && !oldIsInSelection && cell.bg === oldBg)
189 )
190 && (
191 (isInSelection && oldIsInSelection && colors.selectionForeground)
192 || cell.fg === oldFg
193 )
194 && cell.extended.ext === oldExt
195 && isLinkHover === oldLinkHover
196 && spacing === oldSpacing
197 && !isCursorCell
198 && !isJoined
199 && !isDecorated
200 && isValidJoinRange
201 ) {
202 // no span alterations, thus only account chars skipping all code below
203 if (cell.isInvisible()) {
204 text += WHITESPACE_CELL_CHAR;
205 } else {
206 text += chars;
207 }
208 cellAmount++;
209 continue;
210 } else {
211 /**
212 * cannot merge:
213 * - apply left-over text to old span
214 * - create new span, reset state holders cellAmount & text
215 */
216 if (cellAmount) {
217 charElement.textContent = text;
218 }
219 charElement = this._document.createElement('span');
220 cellAmount = 0;
221 text = '';
222 }
223 }
224 // preserve conditions for next merger eval round
225 oldBg = cell.bg;
226 oldFg = cell.fg;
227 oldExt = cell.extended.ext;
228 oldLinkHover = isLinkHover;
229 oldSpacing = spacing;
230 oldIsInSelection = isInSelection;
231
232 if (isJoined) {
233 // The DOM renderer colors the background of the cursor but for ligatures all cells are
234 // joined. The workaround here is to show a cursor around the whole ligature so it shows up,
235 // the cursor looks the same when on any character of the ligature though
236 if (cursorX >= x && cursorX <= lastCharX) {
237 cursorX = x;
238 }
239 }
240
241 if (!this._coreService.isCursorHidden && isCursorCell && this._coreService.isCursorInitialized) {
242 classes.push(RowCss.CURSOR_CLASS);
243 if (this._coreBrowserService.isFocused) {
244 if (cursorBlink) {
245 classes.push(RowCss.CURSOR_BLINK_CLASS);
246 }
247 classes.push(
248 cursorStyle === 'bar'
249 ? RowCss.CURSOR_STYLE_BAR_CLASS
250 : cursorStyle === 'underline'
251 ? RowCss.CURSOR_STYLE_UNDERLINE_CLASS
252 : RowCss.CURSOR_STYLE_BLOCK_CLASS
253 );
254 } else {
255 if (cursorInactiveStyle) {
256 switch (cursorInactiveStyle) {
257 case 'outline':
258 classes.push(RowCss.CURSOR_STYLE_OUTLINE_CLASS);
259 break;
260 case 'block':
261 classes.push(RowCss.CURSOR_STYLE_BLOCK_CLASS);
262 break;
263 case 'bar':
264 classes.push(RowCss.CURSOR_STYLE_BAR_CLASS);
265 break;
266 case 'underline':
267 classes.push(RowCss.CURSOR_STYLE_UNDERLINE_CLASS);
268 break;
269 default:
270 break;
271 }
272 }
273 }
274 }
275
276 if (cell.isBold()) {
277 classes.push(RowCss.BOLD_CLASS);
278 }
279
280 if (cell.isItalic()) {
281 classes.push(RowCss.ITALIC_CLASS);
282 }
283
284 if (cell.isDim()) {
285 classes.push(RowCss.DIM_CLASS);
286 }
287
288 if (cell.isInvisible()) {
289 text = WHITESPACE_CELL_CHAR;
290 } else {
291 text = cell.getChars() || WHITESPACE_CELL_CHAR;
292 }
293
294 if (cell.isUnderline()) {
295 classes.push(`${RowCss.UNDERLINE_CLASS}-${cell.extended.underlineStyle}`);
296 if (text === ' ') {
297 text = '\xa0'; // = &nbsp;
298 }
299 if (!cell.isUnderlineColorDefault()) {
300 if (cell.isUnderlineColorRGB()) {
301 charElement.style.textDecorationColor = `rgb(${AttributeData.toColorRGB(cell.getUnderlineColor()).join(',')})`;
302 } else {
303 let fg = cell.getUnderlineColor();
304 if (this._optionsService.rawOptions.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {
305 fg += 8;
306 }
307 charElement.style.textDecorationColor = colors.ansi[fg].css;
308 }
309 }
310 }
311
312 if (cell.isOverline()) {
313 classes.push(RowCss.OVERLINE_CLASS);
314 if (text === ' ') {
315 text = '\xa0'; // = &nbsp;
316 }
317 }
318
319 if (cell.isStrikethrough()) {
320 classes.push(RowCss.STRIKETHROUGH_CLASS);
321 }
322
323 // apply link hover underline late, effectively overrides any previous text-decoration
324 // settings
325 if (isLinkHover) {
326 charElement.style.textDecoration = 'underline';
327 }
328
329 let fg = cell.getFgColor();
330 let fgColorMode = cell.getFgColorMode();
331 let bg = cell.getBgColor();
332 let bgColorMode = cell.getBgColorMode();
333 const isInverse = !!cell.isInverse();
334 if (isInverse) {
335 const temp = fg;
336 fg = bg;
337 bg = temp;
338 const temp2 = fgColorMode;
339 fgColorMode = bgColorMode;
340 bgColorMode = temp2;
341 }
342
343 // Apply any decoration foreground/background overrides, this must happen after inverse has
344 // been applied
345 let bgOverride: IColor | undefined;
346 let fgOverride: IColor | undefined;
347 let isTop = false;
348 this._decorationService.forEachDecorationAtCell(x, row, undefined, d => {
349 if (d.options.layer !== 'top' && isTop) {
350 return;
351 }
352 if (d.backgroundColorRGB) {
353 bgColorMode = Attributes.CM_RGB;
354 bg = d.backgroundColorRGB.rgba >> 8 & 0xFFFFFF;
355 bgOverride = d.backgroundColorRGB;
356 }
357 if (d.foregroundColorRGB) {
358 fgColorMode = Attributes.CM_RGB;
359 fg = d.foregroundColorRGB.rgba >> 8 & 0xFFFFFF;
360 fgOverride = d.foregroundColorRGB;
361 }
362 isTop = d.options.layer === 'top';
363 });
364
365 // Apply selection
366 if (!isTop && isInSelection) {
367 // If in the selection, force the element to be above the selection to improve contrast and
368 // support opaque selections. The applies background is not actually needed here as
369 // selection is drawn in a seperate container, the main purpose of this to ensuring minimum
370 // contrast ratio
371 bgOverride = this._coreBrowserService.isFocused ? colors.selectionBackgroundOpaque : colors.selectionInactiveBackgroundOpaque;
372 bg = bgOverride.rgba >> 8 & 0xFFFFFF;
373 bgColorMode = Attributes.CM_RGB;
374 // Since an opaque selection is being rendered, the selection pretends to be a decoration to
375 // ensure text is drawn above the selection.
376 isTop = true;
377 // Apply selection foreground if applicable
378 if (colors.selectionForeground) {
379 fgColorMode = Attributes.CM_RGB;
380 fg = colors.selectionForeground.rgba >> 8 & 0xFFFFFF;
381 fgOverride = colors.selectionForeground;
382 }
383 }
384
385 // If it's a top decoration, render above the selection
386 if (isTop) {
387 classes.push('xterm-decoration-top');
388 }
389
390 // Background
391 let resolvedBg: IColor;
392 switch (bgColorMode) {
393 case Attributes.CM_P16:
394 case Attributes.CM_P256:
395 resolvedBg = colors.ansi[bg];
396 classes.push(`xterm-bg-${bg}`);
397 break;
398 case Attributes.CM_RGB:
399 resolvedBg = channels.toColor(bg >> 16, bg >> 8 & 0xFF, bg & 0xFF);
400 this._addStyle(charElement, `background-color:#${padStart((bg >>> 0).toString(16), '0', 6)}`);
401 break;
402 case Attributes.CM_DEFAULT:
403 default:
404 if (isInverse) {
405 resolvedBg = colors.foreground;
406 classes.push(`xterm-bg-${INVERTED_DEFAULT_COLOR}`);
407 } else {
408 resolvedBg = colors.background;
409 }
410 }
411
412 // If there is no background override by now it's the original color, so apply dim if needed
413 if (!bgOverride) {
414 if (cell.isDim()) {
415 bgOverride = color.multiplyOpacity(resolvedBg, 0.5);
416 }
417 }
418
419 // Foreground
420 switch (fgColorMode) {
421 case Attributes.CM_P16:
422 case Attributes.CM_P256:
423 if (cell.isBold() && fg < 8 && this._optionsService.rawOptions.drawBoldTextInBrightColors) {
424 fg += 8;
425 }
426 if (!this._applyMinimumContrast(charElement, resolvedBg, colors.ansi[fg], cell, bgOverride, undefined)) {
427 classes.push(`xterm-fg-${fg}`);
428 }
429 break;
430 case Attributes.CM_RGB:
431 const color = channels.toColor(
432 (fg >> 16) & 0xFF,
433 (fg >> 8) & 0xFF,
434 (fg ) & 0xFF
435 );
436 if (!this._applyMinimumContrast(charElement, resolvedBg, color, cell, bgOverride, fgOverride)) {
437 this._addStyle(charElement, `color:#${padStart(fg.toString(16), '0', 6)}`);
438 }
439 break;
440 case Attributes.CM_DEFAULT:
441 default:
442 if (!this._applyMinimumContrast(charElement, resolvedBg, colors.foreground, cell, bgOverride, fgOverride)) {
443 if (isInverse) {
444 classes.push(`xterm-fg-${INVERTED_DEFAULT_COLOR}`);
445 }
446 }
447 }
448
449 // apply CSS classes
450 // slightly faster than using classList by omitting
451 // checks for doubled entries (code above should not have doublets)
452 if (classes.length) {
453 charElement.className = classes.join(' ');
454 classes.length = 0;
455 }
456
457 // exclude conditions for cell merging - never merge these
458 if (!isCursorCell && !isJoined && !isDecorated && isValidJoinRange) {
459 cellAmount++;
460 } else {
461 charElement.textContent = text;
462 }
463 // apply letter-spacing rule
464 if (spacing !== this.defaultSpacing) {
465 charElement.style.letterSpacing = `${spacing}px`;
466 }
467
468 elements.push(charElement);
469 x = lastCharX;
470 }
471
472 // postfix text of last merged span
473 if (charElement && cellAmount) {
474 charElement.textContent = text;
475 }
476
477 return elements;
478 }
479
480 private _applyMinimumContrast(element: HTMLElement, bg: IColor, fg: IColor, cell: ICellData, bgOverride: IColor | undefined, fgOverride: IColor | undefined): boolean {
481 if (this._optionsService.rawOptions.minimumContrastRatio === 1 || treatGlyphAsBackgroundColor(cell.getCode())) {
482 return false;
483 }
484
485 // Try get from cache first, only use the cache when there are no decoration overrides
486 const cache = this._getContrastCache(cell);
487 let adjustedColor: IColor | undefined | null = undefined;
488 if (!bgOverride && !fgOverride) {
489 adjustedColor = cache.getColor(bg.rgba, fg.rgba);
490 }
491
492 // Calculate and store in cache
493 if (adjustedColor === undefined) {
494 // Dim cells only require half the contrast, otherwise they wouldn't be distinguishable from
495 // non-dim cells
496 const ratio = this._optionsService.rawOptions.minimumContrastRatio / (cell.isDim() ? 2 : 1);
497 adjustedColor = color.ensureContrastRatio(bgOverride || bg, fgOverride || fg, ratio);
498 cache.setColor((bgOverride || bg).rgba, (fgOverride || fg).rgba, adjustedColor ?? null);
499 }
500
501 if (adjustedColor) {
502 this._addStyle(element, `color:${adjustedColor.css}`);
503 return true;
504 }
505
506 return false;
507 }
508
509 private _getContrastCache(cell: ICellData): IColorContrastCache {
510 if (cell.isDim()) {
511 return this._themeService.colors.halfContrastCache;
512 }
513 return this._themeService.colors.contrastCache;
514 }
515
516 private _addStyle(element: HTMLElement, style: string): void {
517 element.setAttribute('style', `${element.getAttribute('style') || ''}${style};`);
518 }
519
520 private _isCellInSelection(x: number, y: number): boolean {
521 const start = this._selectionStart;
522 const end = this._selectionEnd;
523 if (!start || !end) {
524 return false;
525 }
526 if (this._columnSelectMode) {
527 if (start[0] <= end[0]) {
528 return x >= start[0] && y >= start[1] &&
529 x < end[0] && y <= end[1];
530 }
531 return x < start[0] && y >= start[1] &&
532 x >= end[0] && y <= end[1];
533 }
534 return (y > start[1] && y < end[1]) ||
535 (start[1] === end[1] && y === start[1] && x >= start[0] && x < end[0]) ||
536 (start[1] < end[1] && y === end[1] && x < end[0]) ||
537 (start[1] < end[1] && y === start[1] && x >= start[0]);
538 }
539 }
540
541 function padStart(text: string, padChar: string, length: number): string {
542 while (text.length < length) {
543 text = padChar + text;
544 }
545 return text;
546 }