forked from coder/ghostty-web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.ts
More file actions
1002 lines (869 loc) · 33.4 KB
/
renderer.ts
File metadata and controls
1002 lines (869 loc) · 33.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Canvas Renderer for Terminal Display
*
* High-performance canvas-based renderer that draws the terminal using
* Ghostty's WASM terminal emulator. Features:
* - Font metrics measurement with DPI scaling
* - Full color support (256-color palette + RGB)
* - All text styles (bold, italic, underline, strikethrough, etc.)
* - Multiple cursor styles (block, underline, bar)
* - Dirty line optimization for 60 FPS
*/
import type { ITheme } from './interfaces';
import type { SelectionManager } from './selection-manager';
import type { GhosttyCell, ILink } from './types';
import { CellFlags } from './types';
// Interface for objects that can be rendered
export interface IRenderable {
getLine(y: number): GhosttyCell[] | null;
getCursor(): { x: number; y: number; visible: boolean };
getDimensions(): { cols: number; rows: number };
isRowDirty(y: number): boolean;
/** Returns true if a full redraw is needed (e.g., screen change) */
needsFullRedraw?(): boolean;
clearDirty(): void;
/**
* Get the full grapheme string for a cell at (row, col).
* For cells with grapheme_len > 0, this returns all codepoints combined.
* For simple cells, returns the single character.
*/
getGraphemeString?(row: number, col: number): string;
}
export interface IScrollbackProvider {
getScrollbackLine(offset: number): GhosttyCell[] | null;
getScrollbackLength(): number;
}
// ============================================================================
// Type Definitions
// ============================================================================
export interface RendererOptions {
fontSize?: number; // Default: 15
fontFamily?: string; // Default: 'monospace'
cursorStyle?: 'block' | 'underline' | 'bar'; // Default: 'block'
cursorBlink?: boolean; // Default: false
theme?: ITheme;
devicePixelRatio?: number; // Default: window.devicePixelRatio
}
export interface FontMetrics {
width: number; // Character cell width in CSS pixels
height: number; // Character cell height in CSS pixels
baseline: number; // Distance from top to text baseline
}
// ============================================================================
// Default Theme
// ============================================================================
export const DEFAULT_THEME: Required<ITheme> = {
foreground: '#d4d4d4',
background: '#1e1e1e',
cursor: '#ffffff',
cursorAccent: '#1e1e1e',
// Selection colors: solid colors that replace cell bg/fg when selected
// Using Ghostty's approach: selection bg = default fg, selection fg = default bg
selectionBackground: '#d4d4d4',
selectionForeground: '#1e1e1e',
black: '#000000',
red: '#cd3131',
green: '#0dbc79',
yellow: '#e5e510',
blue: '#2472c8',
magenta: '#bc3fbc',
cyan: '#11a8cd',
white: '#e5e5e5',
brightBlack: '#666666',
brightRed: '#f14c4c',
brightGreen: '#23d18b',
brightYellow: '#f5f543',
brightBlue: '#3b8eea',
brightMagenta: '#d670d6',
brightCyan: '#29b8db',
brightWhite: '#ffffff',
};
// ============================================================================
// CanvasRenderer Class
// ============================================================================
export class CanvasRenderer {
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D;
private fontSize: number;
private fontFamily: string;
private cursorStyle: 'block' | 'underline' | 'bar';
private cursorBlink: boolean;
private theme: Required<ITheme>;
private devicePixelRatio: number;
private metrics: FontMetrics;
private palette: string[];
// Cursor blinking state
private cursorVisible: boolean = true;
private cursorBlinkInterval?: number;
private lastCursorPosition: { x: number; y: number } = { x: 0, y: 0 };
// Viewport tracking (for scrolling)
private lastViewportY: number = 0;
// Current buffer being rendered (for grapheme lookups)
private currentBuffer: IRenderable | null = null;
// Selection manager (for rendering selection)
private selectionManager?: SelectionManager;
// Cached selection coordinates for current render pass (viewport-relative)
private currentSelectionCoords: {
startCol: number;
startRow: number;
endCol: number;
endRow: number;
} | null = null;
// Link rendering state
private hoveredHyperlinkId: number = 0;
private previousHoveredHyperlinkId: number = 0;
// Regex link hover tracking (for links without hyperlink_id)
private hoveredLinkRange: { startX: number; startY: number; endX: number; endY: number } | null =
null;
private previousHoveredLinkRange: {
startX: number;
startY: number;
endX: number;
endY: number;
} | null = null;
constructor(canvas: HTMLCanvasElement, options: RendererOptions = {}) {
this.canvas = canvas;
const ctx = canvas.getContext('2d', { alpha: true });
if (!ctx) {
throw new Error('Failed to get 2D rendering context');
}
this.ctx = ctx;
// Apply options
this.fontSize = options.fontSize ?? 15;
this.fontFamily = options.fontFamily ?? 'monospace';
this.cursorStyle = options.cursorStyle ?? 'block';
this.cursorBlink = options.cursorBlink ?? false;
this.theme = { ...DEFAULT_THEME, ...options.theme };
this.devicePixelRatio = options.devicePixelRatio ?? window.devicePixelRatio ?? 1;
// Build color palette (16 ANSI colors)
this.palette = [
this.theme.black,
this.theme.red,
this.theme.green,
this.theme.yellow,
this.theme.blue,
this.theme.magenta,
this.theme.cyan,
this.theme.white,
this.theme.brightBlack,
this.theme.brightRed,
this.theme.brightGreen,
this.theme.brightYellow,
this.theme.brightBlue,
this.theme.brightMagenta,
this.theme.brightCyan,
this.theme.brightWhite,
];
// Measure font metrics
this.metrics = this.measureFont();
// Setup cursor blinking if enabled
if (this.cursorBlink) {
this.startCursorBlink();
}
}
// ==========================================================================
// Font Metrics Measurement
// ==========================================================================
private measureFont(): FontMetrics {
// Use an offscreen canvas for measurement
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d')!;
// Set font (use actual pixel size for accurate measurement)
ctx.font = `${this.fontSize}px ${this.fontFamily}`;
// Measure width using 'M' (typically widest character)
const widthMetrics = ctx.measureText('M');
const width = Math.ceil(widthMetrics.width);
// Measure height using ascent + descent with padding for glyph overflow
const ascent = widthMetrics.actualBoundingBoxAscent || this.fontSize * 0.8;
const descent = widthMetrics.actualBoundingBoxDescent || this.fontSize * 0.2;
// Add 2px padding to height to account for glyphs that overflow (like 'f', 'd', 'g', 'p')
// and anti-aliasing pixels
const height = Math.ceil(ascent + descent) + 2;
const baseline = Math.ceil(ascent) + 1; // Offset baseline by half the padding
return { width, height, baseline };
}
/**
* Remeasure font metrics (call after font loads or changes)
*/
public remeasureFont(): void {
this.metrics = this.measureFont();
}
// ==========================================================================
// Color Conversion
// ==========================================================================
private rgbToCSS(r: number, g: number, b: number): string {
return `rgb(${r}, ${g}, ${b})`;
}
// ==========================================================================
// Canvas Sizing
// ==========================================================================
/**
* Resize canvas to fit terminal dimensions
*/
public resize(cols: number, rows: number): void {
const cssWidth = cols * this.metrics.width;
const cssHeight = rows * this.metrics.height;
// Set CSS size (what user sees)
this.canvas.style.width = `${cssWidth}px`;
this.canvas.style.height = `${cssHeight}px`;
this.canvas.style.cursor = 'text';
// Set actual canvas size (scaled for DPI)
this.canvas.width = cssWidth * this.devicePixelRatio;
this.canvas.height = cssHeight * this.devicePixelRatio;
// Scale context to match DPI (setting canvas.width/height resets the context)
this.ctx.scale(this.devicePixelRatio, this.devicePixelRatio);
// Set text rendering properties for crisp text
this.ctx.textBaseline = 'alphabetic';
this.ctx.textAlign = 'left';
// Fill background after resize
this.ctx.fillStyle = this.theme.background;
this.ctx.fillRect(0, 0, cssWidth, cssHeight);
}
// ==========================================================================
// Main Rendering
// ==========================================================================
/**
* Render the terminal buffer to canvas
*/
public render(
buffer: IRenderable,
forceAll: boolean = false,
viewportY: number = 0,
scrollbackProvider?: IScrollbackProvider,
scrollbarOpacity: number = 1
): void {
// Store buffer reference for grapheme lookups in renderCell
this.currentBuffer = buffer;
// getCursor() calls update() internally to ensure fresh state.
// Multiple update() calls are safe - dirty state persists until clearDirty().
const cursor = buffer.getCursor();
const dims = buffer.getDimensions();
const scrollbackLength = scrollbackProvider ? scrollbackProvider.getScrollbackLength() : 0;
// Check if buffer needs full redraw (e.g., screen change between normal/alternate)
if (buffer.needsFullRedraw?.()) {
forceAll = true;
}
// Resize canvas if dimensions changed
const needsResize =
this.canvas.width !== dims.cols * this.metrics.width * this.devicePixelRatio ||
this.canvas.height !== dims.rows * this.metrics.height * this.devicePixelRatio;
if (needsResize) {
this.resize(dims.cols, dims.rows);
forceAll = true; // Force full render after resize
}
// Force re-render when viewport changes (scrolling)
if (viewportY !== this.lastViewportY) {
forceAll = true;
this.lastViewportY = viewportY;
}
// Check if cursor position changed or if blinking (need to redraw cursor line)
const cursorMoved =
cursor.x !== this.lastCursorPosition.x || cursor.y !== this.lastCursorPosition.y;
if (cursorMoved || this.cursorBlink) {
// Mark cursor lines as needing redraw
if (!forceAll && !buffer.isRowDirty(cursor.y)) {
// Need to redraw cursor line
const line = buffer.getLine(cursor.y);
if (line) {
this.renderLine(line, cursor.y, dims.cols);
}
}
if (cursorMoved && this.lastCursorPosition.y !== cursor.y) {
// Also redraw old cursor line if cursor moved to different line
if (!forceAll && !buffer.isRowDirty(this.lastCursorPosition.y)) {
const line = buffer.getLine(this.lastCursorPosition.y);
if (line) {
this.renderLine(line, this.lastCursorPosition.y, dims.cols);
}
}
}
}
// Check if we need to redraw selection-related lines
const hasSelection = this.selectionManager && this.selectionManager.hasSelection();
const selectionRows = new Set<number>();
// Cache selection coordinates for use during cell rendering
// This is used by isInSelection() to determine if a cell needs selection colors
this.currentSelectionCoords = hasSelection ? this.selectionManager!.getSelectionCoords() : null;
// Mark current selection rows for redraw (includes programmatic selections)
if (this.currentSelectionCoords) {
const coords = this.currentSelectionCoords;
for (let row = coords.startRow; row <= coords.endRow; row++) {
selectionRows.add(row);
}
}
// Always mark dirty selection rows for redraw (to clear old overlay)
if (this.selectionManager) {
const dirtyRows = this.selectionManager.getDirtySelectionRows();
if (dirtyRows.size > 0) {
for (const row of dirtyRows) {
selectionRows.add(row);
}
// Clear the dirty rows tracking after marking for redraw
this.selectionManager.clearDirtySelectionRows();
}
}
// Track rows with hyperlinks that need redraw when hover changes
const hyperlinkRows = new Set<number>();
const hyperlinkChanged = this.hoveredHyperlinkId !== this.previousHoveredHyperlinkId;
const linkRangeChanged =
JSON.stringify(this.hoveredLinkRange) !== JSON.stringify(this.previousHoveredLinkRange);
if (hyperlinkChanged) {
// Find rows containing the old or new hovered hyperlink
// Must check the correct buffer based on viewportY (scrollback vs screen)
for (let y = 0; y < dims.rows; y++) {
let line: GhosttyCell[] | null = null;
// Same logic as rendering: fetch from scrollback or screen
if (viewportY > 0) {
if (y < viewportY && scrollbackProvider) {
// This row is from scrollback
// Floor viewportY for array access (handles fractional values during smooth scroll)
const scrollbackOffset = scrollbackLength - Math.floor(viewportY) + y;
line = scrollbackProvider.getScrollbackLine(scrollbackOffset);
} else {
// This row is from visible screen
const screenRow = y - Math.floor(viewportY);
line = buffer.getLine(screenRow);
}
} else {
// At bottom - fetch from visible screen
line = buffer.getLine(y);
}
if (line) {
for (const cell of line) {
if (
cell.hyperlink_id === this.hoveredHyperlinkId ||
cell.hyperlink_id === this.previousHoveredHyperlinkId
) {
hyperlinkRows.add(y);
break; // Found hyperlink in this row
}
}
}
}
// Update previous state
this.previousHoveredHyperlinkId = this.hoveredHyperlinkId;
}
// Track rows affected by link range changes (for regex URLs)
if (linkRangeChanged) {
// Add rows from old range
if (this.previousHoveredLinkRange) {
for (
let y = this.previousHoveredLinkRange.startY;
y <= this.previousHoveredLinkRange.endY;
y++
) {
hyperlinkRows.add(y);
}
}
// Add rows from new range
if (this.hoveredLinkRange) {
for (let y = this.hoveredLinkRange.startY; y <= this.hoveredLinkRange.endY; y++) {
hyperlinkRows.add(y);
}
}
this.previousHoveredLinkRange = this.hoveredLinkRange;
}
// Track if anything was actually rendered
let anyLinesRendered = false;
// Determine which rows need rendering.
// We also include adjacent rows (above and below) for each dirty row to handle
// glyph overflow - tall glyphs like Devanagari vowel signs can extend into
// adjacent rows' visual space.
const rowsToRender = new Set<number>();
for (let y = 0; y < dims.rows; y++) {
// When scrolled, always force render all lines since we're showing scrollback
const needsRender =
viewportY > 0
? true
: forceAll || buffer.isRowDirty(y) || selectionRows.has(y) || hyperlinkRows.has(y);
if (needsRender) {
rowsToRender.add(y);
// Include adjacent rows to handle glyph overflow
if (y > 0) rowsToRender.add(y - 1);
if (y < dims.rows - 1) rowsToRender.add(y + 1);
}
}
// Render each line
for (let y = 0; y < dims.rows; y++) {
if (!rowsToRender.has(y)) {
continue;
}
anyLinesRendered = true;
// Fetch line from scrollback or visible screen
let line: GhosttyCell[] | null = null;
if (viewportY > 0) {
// Scrolled up - need to fetch from scrollback + visible screen
// When scrolled up N lines, we want to show:
// - Scrollback lines (from the end) + visible screen lines
// Check if this row should come from scrollback or visible screen
if (y < viewportY && scrollbackProvider) {
// This row is from scrollback (upper part of viewport)
// Get from end of scrollback buffer
// Floor viewportY for array access (handles fractional values during smooth scroll)
const scrollbackOffset = scrollbackLength - Math.floor(viewportY) + y;
line = scrollbackProvider.getScrollbackLine(scrollbackOffset);
} else {
// This row is from visible screen (lower part of viewport)
const screenRow = viewportY > 0 ? y - Math.floor(viewportY) : y;
line = buffer.getLine(screenRow);
}
} else {
// At bottom - fetch from visible screen
line = buffer.getLine(y);
}
if (line) {
this.renderLine(line, y, dims.cols);
}
}
// Selection highlighting is now integrated into renderCellBackground/renderCellText
// No separate overlay pass needed - this fixes z-order issues with complex glyphs
// Link underlines are drawn during cell rendering (see renderCell)
// Render cursor (only if we're at the bottom, not scrolled)
if (viewportY === 0 && cursor.visible && this.cursorVisible) {
this.renderCursor(cursor.x, cursor.y);
}
// Render scrollbar if scrolled or scrollback exists (with opacity for fade effect)
if (scrollbackProvider && scrollbarOpacity > 0) {
this.renderScrollbar(viewportY, scrollbackLength, dims.rows, scrollbarOpacity);
}
// Update last cursor position
this.lastCursorPosition = { x: cursor.x, y: cursor.y };
// ALWAYS clear dirty flags after rendering, regardless of forceAll.
// This is critical - if we don't clear after a full redraw, the dirty
// state persists and the next frame might not detect new changes properly.
buffer.clearDirty();
}
/**
* Render a single line using two-pass approach:
* 1. First pass: Draw all cell backgrounds
* 2. Second pass: Draw all cell text and decorations
*
* This two-pass approach is necessary for proper rendering of complex scripts
* like Devanagari where diacritics (like vowel sign ि) can extend LEFT of the
* base character into the previous cell's visual area. If we draw backgrounds
* and text in a single pass (cell by cell), the background of cell N would
* cover any left-extending portions of graphemes from cell N-1.
*/
private renderLine(line: GhosttyCell[], y: number, cols: number): void {
const lineY = y * this.metrics.height;
const lineWidth = cols * this.metrics.width;
// Clear line background then fill with theme color.
// We clear just the cell area - glyph overflow is handled by also
// redrawing adjacent rows (see render() method).
// clearRect is needed because fillRect composites rather than replaces,
// so transparent/translucent backgrounds wouldn't clear previous content.
this.ctx.clearRect(0, lineY, lineWidth, this.metrics.height);
this.ctx.fillStyle = this.theme.background;
this.ctx.fillRect(0, lineY, lineWidth, this.metrics.height);
// PASS 1: Draw all cell backgrounds first
// This ensures all backgrounds are painted before any text, allowing text
// to "bleed" across cell boundaries without being covered by adjacent backgrounds
for (let x = 0; x < line.length; x++) {
const cell = line[x];
if (cell.width === 0) continue; // Skip spacer cells for wide characters
this.renderCellBackground(cell, x, y);
}
// PASS 2: Draw all cell text and decorations
// Now text can safely extend beyond cell boundaries (for complex scripts)
for (let x = 0; x < line.length; x++) {
const cell = line[x];
if (cell.width === 0) continue; // Skip spacer cells for wide characters
this.renderCellText(cell, x, y);
}
}
/**
* Render a cell's background only (Pass 1 of two-pass rendering)
* Selection highlighting is integrated here to avoid z-order issues with
* complex glyphs (like Devanagari) that extend outside their cell bounds.
*/
private renderCellBackground(cell: GhosttyCell, x: number, y: number): void {
const cellX = x * this.metrics.width;
const cellY = y * this.metrics.height;
const cellWidth = this.metrics.width * cell.width;
// Check if this cell is selected
const isSelected = this.isInSelection(x, y);
if (isSelected) {
// Draw selection background (solid color, not overlay)
this.ctx.fillStyle = this.theme.selectionBackground;
this.ctx.fillRect(cellX, cellY, cellWidth, this.metrics.height);
return; // Selection background replaces cell background
}
// Extract background color and handle inverse
let bg_r = cell.bg_r,
bg_g = cell.bg_g,
bg_b = cell.bg_b;
if (cell.flags & CellFlags.INVERSE) {
// When inverted, background becomes foreground
bg_r = cell.fg_r;
bg_g = cell.fg_g;
bg_b = cell.fg_b;
}
// Only draw cell background if it's different from the default (black)
// This lets the theme background (drawn earlier) show through for default cells
const isDefaultBg = bg_r === 0 && bg_g === 0 && bg_b === 0;
if (!isDefaultBg) {
this.ctx.fillStyle = this.rgbToCSS(bg_r, bg_g, bg_b);
this.ctx.fillRect(cellX, cellY, cellWidth, this.metrics.height);
}
}
/**
* Render a cell's text and decorations (Pass 2 of two-pass rendering)
* Selection foreground color is applied here to match the selection background.
*/
private renderCellText(cell: GhosttyCell, x: number, y: number, colorOverride?: string): void {
const cellX = x * this.metrics.width;
const cellY = y * this.metrics.height;
const cellWidth = this.metrics.width * cell.width;
// Skip rendering if invisible
if (cell.flags & CellFlags.INVISIBLE) {
return;
}
// Check if this cell is selected
const isSelected = this.isInSelection(x, y);
// Set text style
let fontStyle = '';
if (cell.flags & CellFlags.ITALIC) fontStyle += 'italic ';
if (cell.flags & CellFlags.BOLD) fontStyle += 'bold ';
this.ctx.font = `${fontStyle}${this.fontSize}px ${this.fontFamily}`;
// Set text color - use override, selection foreground, or normal color
if (colorOverride) {
this.ctx.fillStyle = colorOverride;
} else if (isSelected) {
this.ctx.fillStyle = this.theme.selectionForeground;
} else {
// Extract colors and handle inverse
let fg_r = cell.fg_r,
fg_g = cell.fg_g,
fg_b = cell.fg_b;
if (cell.flags & CellFlags.INVERSE) {
// When inverted, foreground becomes background
fg_r = cell.bg_r;
fg_g = cell.bg_g;
fg_b = cell.bg_b;
}
this.ctx.fillStyle = this.rgbToCSS(fg_r, fg_g, fg_b);
}
// Apply faint effect
if (cell.flags & CellFlags.FAINT) {
this.ctx.globalAlpha = 0.5;
}
// Draw text
const textX = cellX;
const textY = cellY + this.metrics.baseline;
// Get the character to render - use grapheme lookup for complex scripts
let char: string;
if (cell.grapheme_len > 0 && this.currentBuffer?.getGraphemeString) {
// Cell has additional codepoints - get full grapheme cluster
char = this.currentBuffer.getGraphemeString(y, x);
} else {
// Simple cell - single codepoint
char = String.fromCodePoint(cell.codepoint || 32); // Default to space if null
}
this.ctx.fillText(char, textX, textY);
// Reset alpha
if (cell.flags & CellFlags.FAINT) {
this.ctx.globalAlpha = 1.0;
}
// Draw underline
if (cell.flags & CellFlags.UNDERLINE) {
const underlineY = cellY + this.metrics.baseline + 2;
this.ctx.strokeStyle = this.ctx.fillStyle;
this.ctx.lineWidth = 1;
this.ctx.beginPath();
this.ctx.moveTo(cellX, underlineY);
this.ctx.lineTo(cellX + cellWidth, underlineY);
this.ctx.stroke();
}
// Draw strikethrough
if (cell.flags & CellFlags.STRIKETHROUGH) {
const strikeY = cellY + this.metrics.height / 2;
this.ctx.strokeStyle = this.ctx.fillStyle;
this.ctx.lineWidth = 1;
this.ctx.beginPath();
this.ctx.moveTo(cellX, strikeY);
this.ctx.lineTo(cellX + cellWidth, strikeY);
this.ctx.stroke();
}
// Draw hyperlink underline (for OSC8 hyperlinks)
if (cell.hyperlink_id > 0) {
const isHovered = cell.hyperlink_id === this.hoveredHyperlinkId;
// Only show underline when hovered (cleaner look)
if (isHovered) {
const underlineY = cellY + this.metrics.baseline + 2;
this.ctx.strokeStyle = '#4A90E2'; // Blue underline on hover
this.ctx.lineWidth = 1;
this.ctx.beginPath();
this.ctx.moveTo(cellX, underlineY);
this.ctx.lineTo(cellX + cellWidth, underlineY);
this.ctx.stroke();
}
}
// Draw regex link underline (for plain text URLs)
if (this.hoveredLinkRange) {
const range = this.hoveredLinkRange;
// Check if this cell is within the hovered link range
const isInRange =
(y === range.startY && x >= range.startX && (y < range.endY || x <= range.endX)) ||
(y > range.startY && y < range.endY) ||
(y === range.endY && x <= range.endX && (y > range.startY || x >= range.startX));
if (isInRange) {
const underlineY = cellY + this.metrics.baseline + 2;
this.ctx.strokeStyle = '#4A90E2'; // Blue underline on hover
this.ctx.lineWidth = 1;
this.ctx.beginPath();
this.ctx.moveTo(cellX, underlineY);
this.ctx.lineTo(cellX + cellWidth, underlineY);
this.ctx.stroke();
}
}
}
/**
* Render cursor
*/
private renderCursor(x: number, y: number): void {
const cursorX = x * this.metrics.width;
const cursorY = y * this.metrics.height;
this.ctx.fillStyle = this.theme.cursor;
switch (this.cursorStyle) {
case 'block':
// Full cell block
this.ctx.fillRect(cursorX, cursorY, this.metrics.width, this.metrics.height);
// Re-draw character under cursor with cursorAccent color
{
const line = this.currentBuffer?.getLine(y);
if (line?.[x]) {
this.ctx.save();
this.ctx.beginPath();
this.ctx.rect(cursorX, cursorY, this.metrics.width, this.metrics.height);
this.ctx.clip();
this.renderCellText(line[x], x, y, this.theme.cursorAccent);
this.ctx.restore();
}
}
break;
case 'underline':
// Underline at bottom of cell
const underlineHeight = Math.max(2, Math.floor(this.metrics.height * 0.15));
this.ctx.fillRect(
cursorX,
cursorY + this.metrics.height - underlineHeight,
this.metrics.width,
underlineHeight
);
break;
case 'bar':
// Vertical bar at left of cell
const barWidth = Math.max(2, Math.floor(this.metrics.width * 0.15));
this.ctx.fillRect(cursorX, cursorY, barWidth, this.metrics.height);
break;
}
}
// ==========================================================================
// Cursor Blinking
// ==========================================================================
private startCursorBlink(): void {
// xterm.js uses ~530ms blink interval
this.cursorBlinkInterval = window.setInterval(() => {
this.cursorVisible = !this.cursorVisible;
// Note: Render loop should redraw cursor line automatically
}, 530);
}
private stopCursorBlink(): void {
if (this.cursorBlinkInterval !== undefined) {
clearInterval(this.cursorBlinkInterval);
this.cursorBlinkInterval = undefined;
}
this.cursorVisible = true;
}
// ==========================================================================
// Public API
// ==========================================================================
/**
* Update theme colors
*/
public setTheme(theme: ITheme): void {
this.theme = { ...DEFAULT_THEME, ...theme };
// Rebuild palette
this.palette = [
this.theme.black,
this.theme.red,
this.theme.green,
this.theme.yellow,
this.theme.blue,
this.theme.magenta,
this.theme.cyan,
this.theme.white,
this.theme.brightBlack,
this.theme.brightRed,
this.theme.brightGreen,
this.theme.brightYellow,
this.theme.brightBlue,
this.theme.brightMagenta,
this.theme.brightCyan,
this.theme.brightWhite,
];
}
/**
* Update font size
*/
public setFontSize(size: number): void {
this.fontSize = size;
this.metrics = this.measureFont();
}
/**
* Update font family
*/
public setFontFamily(family: string): void {
this.fontFamily = family;
this.metrics = this.measureFont();
}
/**
* Update cursor style
*/
public setCursorStyle(style: 'block' | 'underline' | 'bar'): void {
this.cursorStyle = style;
}
/**
* Enable/disable cursor blinking
*/
public setCursorBlink(enabled: boolean): void {
if (enabled && !this.cursorBlink) {
this.cursorBlink = true;
this.startCursorBlink();
} else if (!enabled && this.cursorBlink) {
this.cursorBlink = false;
this.stopCursorBlink();
}
}
/**
* Get current font metrics
*/
/**
* Render scrollbar (Phase 2)
* Shows scroll position and allows click/drag interaction
* @param opacity Opacity level (0-1) for fade in/out effect
*/
private renderScrollbar(
viewportY: number,
scrollbackLength: number,
visibleRows: number,
opacity: number = 1
): void {
const ctx = this.ctx;
const canvasHeight = this.canvas.height / this.devicePixelRatio;
const canvasWidth = this.canvas.width / this.devicePixelRatio;
// Scrollbar dimensions
const scrollbarWidth = 8;
const scrollbarX = canvasWidth - scrollbarWidth - 4;
const scrollbarPadding = 4;
const scrollbarTrackHeight = canvasHeight - scrollbarPadding * 2;
// Always clear the scrollbar area first (fixes ghosting when fading out)
ctx.clearRect(scrollbarX - 2, 0, scrollbarWidth + 6, canvasHeight);
ctx.fillStyle = this.theme.background;
ctx.fillRect(scrollbarX - 2, 0, scrollbarWidth + 6, canvasHeight);
// Don't draw scrollbar if fully transparent or no scrollback
if (opacity <= 0 || scrollbackLength === 0) return;
// Calculate scrollbar thumb size and position
const totalLines = scrollbackLength + visibleRows;
const thumbHeight = Math.max(20, (visibleRows / totalLines) * scrollbarTrackHeight);
// Position: 0 = at bottom, scrollbackLength = at top
const scrollPosition = viewportY / scrollbackLength; // 0 to 1
const thumbY = scrollbarPadding + (scrollbarTrackHeight - thumbHeight) * (1 - scrollPosition);
// Draw scrollbar track (subtle background) with opacity
ctx.fillStyle = `rgba(128, 128, 128, ${0.1 * opacity})`;
ctx.fillRect(scrollbarX, scrollbarPadding, scrollbarWidth, scrollbarTrackHeight);
// Draw scrollbar thumb with opacity
const isScrolled = viewportY > 0;
const baseOpacity = isScrolled ? 0.5 : 0.3;
ctx.fillStyle = `rgba(128, 128, 128, ${baseOpacity * opacity})`;
ctx.fillRect(scrollbarX, thumbY, scrollbarWidth, thumbHeight);
}
public getMetrics(): FontMetrics {
return { ...this.metrics };
}
/**
* Get canvas element (needed by SelectionManager)
*/
public getCanvas(): HTMLCanvasElement {
return this.canvas;
}
/**
* Set selection manager (for rendering selection)
*/
public setSelectionManager(manager: SelectionManager): void {
this.selectionManager = manager;
}
/**
* Check if a cell at (x, y) is within the current selection.
* Uses cached selection coordinates for performance.
*/
private isInSelection(x: number, y: number): boolean {
const sel = this.currentSelectionCoords;
if (!sel) return false;
const { startCol, startRow, endCol, endRow } = sel;
// Single line selection
if (startRow === endRow) {
return y === startRow && x >= startCol && x <= endCol;
}
// Multi-line selection
if (y === startRow) {
// First line: from startCol to end of line
return x >= startCol;
} else if (y === endRow) {
// Last line: from start of line to endCol
return x <= endCol;
} else if (y > startRow && y < endRow) {
// Middle lines: entire line is selected
return true;
}
return false;
}
/**
* Set the currently hovered hyperlink ID for rendering underlines
*/
public setHoveredHyperlinkId(hyperlinkId: number): void {
this.hoveredHyperlinkId = hyperlinkId;
}
/**
* Set the currently hovered link range for rendering underlines (for regex-detected URLs)
* Pass null to clear the hover state
*/
public setHoveredLinkRange(
range: {
startX: number;
startY: number;
endX: number;
endY: number;
} | null
): void {
this.hoveredLinkRange = range;
}
/**
* Get character cell width (for coordinate conversion)
*/
public get charWidth(): number {
return this.metrics.width;
}
/**
* Get character cell height (for coordinate conversion)
*/
public get charHeight(): number {
return this.metrics.height;
}
/**
* Clear entire canvas
*/
public clear(): void {
// clearRect first because fillRect composites rather than replaces,
// so transparent/translucent backgrounds wouldn't clear previous content.
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.fillStyle = this.theme.background;
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
/**
* Cleanup resources
*/
public dispose(): void {
this.stopCursorBlink();