Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

renderer.ts

404 lines13.2 KB

1import {
2 GHOSTTY_CELL_WIDE,
3 ghosttyColorsEqual,
4 type GhosttyCell,
5 type GhosttyColor,
6 type GhosttySnapshot,
7} from "./core";
8​
9export interface GhosttyCellMetrics {
10 readonly width: number;
11 readonly height: number;
12 readonly baseline: number;
14​
15export interface GhosttyCellRange {
16 readonly start: { readonly x: number; readonly y: number };
17 readonly end: { readonly x: number; readonly y: number };
19​
20const DEFAULT_SELECTION_BACKGROUND = "rgba(72, 122, 191, 0.35)";
21const POWERLINE_SOLID_RIGHT = "\ue0b0";
22const POWERLINE_SOLID_LEFT = "\ue0b2";
23const POWERLINE_ROUND_RIGHT = "\ue0b4";
24const POWERLINE_ROUND_LEFT = "\ue0b6";
25​
26function cssColor(color: GhosttyColor): string {
27 return `rgb(${color.r}, ${color.g}, ${color.b})`;
29​
30function sameTextStyle(left: GhosttyCell, right: GhosttyCell): boolean {
31 // Selection only tints the background; splitting text runs shifts glyph spacing when advances differ from cell width.
32 return (
33 ghosttyColorsEqual(left.foreground, right.foreground) &&
34 left.bold === right.bold &&
35 left.italic === right.italic &&
36 left.invisible === right.invisible
37 );
39​
40function isSolidPowerlineSeparator(text: string): boolean {
41 return (
42 text === POWERLINE_SOLID_RIGHT ||
43 text === POWERLINE_SOLID_LEFT ||
44 text === POWERLINE_ROUND_RIGHT ||
45 text === POWERLINE_ROUND_LEFT
46 );
48​
49// Fallback fonts inset or scale these private-use glyphs, leaving a gap where
50// the separator should meet the next cell. Fill the triangle or half-ellipse
51// from the cell's own edges instead, as native terminals do.
52function fillSolidPowerlineSeparator(
53 context: CanvasRenderingContext2D,
54 text: string,
55 left: number,
56 top: number,
57 width: number,
58 height: number,
59 seamOverlap: number,
60): void {
61 const right = left + width;
62 const middle = top + height / 2;
63 if (text === POWERLINE_ROUND_RIGHT || text === POWERLINE_ROUND_LEFT) {
64 const [base, start, inward] =
65 text === POWERLINE_ROUND_RIGHT ? [left, -Math.PI / 2, -1] : [right, Math.PI / 2, 1];
66 context.beginPath();
67 context.ellipse(base, middle, width, height / 2, 0, start, start + Math.PI);
68 context.closePath();
69 // Overlap the segment this cap closes so anti-aliasing at a fractional
70 // cell edge does not leave a hairline seam.
71 context.rect(Math.min(base, base + inward * seamOverlap), top, seamOverlap, height);
72 context.fill();
73 return;
74 }
75 const [base, point] = text === POWERLINE_SOLID_RIGHT ? [left, right] : [right, left];
76 context.beginPath();
77 context.moveTo(base, top);
78 context.lineTo(point, middle);
79 context.lineTo(base, top + height);
80 context.closePath();
81 context.fill();
83​
84function ghosttyTextRunEnd(
85 cells: readonly GhosttyCell[],
86 start: number,
87 sameStyle: (cell: GhosttyCell) => boolean,
88): number {
89 let end = start + 1;
90 while (end < cells.length) {
91 const next = cells[end];
92 if (!next) break;
93 if (next.wide === GHOSTTY_CELL_WIDE.spacerTail) {
94 end += 1;
95 continue;
96 }
97 if (next.text.length === 0 || isSolidPowerlineSeparator(next.text) || !sameStyle(next)) break;
98 end += 1;
99 }
100 return end;
102​
103// Snapshots decode `wide` only for empty cells, so a wide glyph is known by its spacer tail.
104function isWideGlyph(cells: readonly GhosttyCell[], index: number): boolean {
105 return cells[index + 1]?.wide === GHOSTTY_CELL_WIDE.spacerTail;
107​
108// Wide glyphs rarely advance exactly two cells, so each is centred in its own box
109// and the narrow text after it restarts at its own column instead of drifting.
110function fillGhosttyRunText(
111 context: CanvasRenderingContext2D,
112 cells: readonly GhosttyCell[],
113 start: number,
114 end: number,
115 text: string,
116 left: number,
117 baseline: number,
118 cellWidth: number,
119): void {
120 let segment = start;
121 while (segment < end) {
122 let segmentEnd = segment;
123 while (segmentEnd < end && !isWideGlyph(cells, segmentEnd)) segmentEnd += 1;
124 if (segmentEnd > segment) {
125 const segmentText =
126 segment === start && segmentEnd === end
127 ? text
128 : cells
129 .slice(segment, segmentEnd)
130 .map((cell) => cell.text)
131 .join("");
132 context.fillText(
133 segmentText,
134 left + (segment - start) * cellWidth,
135 baseline,
136 (segmentEnd - segment) * cellWidth,
137 );
138 }
139 if (segmentEnd === end) break;
140 context.textAlign = "center";
141 context.fillText(
142 cells[segmentEnd]?.text ?? "",
143 left + (segmentEnd - start + 1) * cellWidth,
144 baseline,
145 cellWidth * 2,
146 );
147 context.textAlign = "start";
148 segment = segmentEnd + 2;
149 }
151​
152function fontForCell(cell: GhosttyCell, fontSize: number, fontFamily: string): string {
153 const style = cell.italic ? "italic" : "normal";
154 const weight = cell.bold ? "700" : "400";
155 return `${style} ${weight} ${fontSize}px ${fontFamily}`;
157​
158export function measureGhosttyCell(
159 context: CanvasRenderingContext2D,
160 fontSize: number,
161 fontFamily: string,
162): GhosttyCellMetrics {
163 context.font = `normal 400 ${fontSize}px ${fontFamily}`;
164 const widthMeasurement = context.measureText("M");
165 const verticalMeasurement = context.measureText("Mg");
166 const ascent = verticalMeasurement.actualBoundingBoxAscent || fontSize;
167 const descent = verticalMeasurement.actualBoundingBoxDescent;
168 const glyphHeight = ascent + descent;
169 const height = Math.max(1, Math.round(fontSize * 1.35), Math.ceil(glyphHeight));
170 return {
171 width: Math.max(1, widthMeasurement.width),
172 height,
173 baseline: Math.round((height - glyphHeight) / 2 + ascent),
174 };
176​
177export function terminalGridSize(
178 width: number,
179 height: number,
180 metrics: GhosttyCellMetrics,
181 padding: number,
182): { cols: number; rows: number } {
183 return {
184 cols: Math.max(1, Math.floor((width - padding * 2) / metrics.width)),
185 rows: Math.max(1, Math.floor((height - padding * 2) / metrics.height)),
186 };
188​
189export function renderGhosttySnapshot(options: {
190 readonly context: CanvasRenderingContext2D;
191 readonly snapshot: GhosttySnapshot;
192 readonly metrics: GhosttyCellMetrics;
193 readonly fontSize: number;
194 readonly fontFamily: string;
195 readonly padding: number;
196 readonly forceFull: boolean;
197 readonly cursorOn: boolean;
198 readonly previousCursorY?: number | null;
199 readonly focused?: boolean;
200 readonly selectionBackground?: string;
201 readonly hoveredLinkRange?: GhosttyCellRange | null;
202 readonly originY?: number;
203}): void {
204 const {
205 context,
206 snapshot,
207 metrics,
208 fontSize,
209 fontFamily,
210 padding,
211 forceFull,
212 cursorOn,
213 previousCursorY,
214 } = options;
215 const focused = options.focused ?? true;
216 const selectionBackground = options.selectionBackground ?? DEFAULT_SELECTION_BACKGROUND;
217 const hoveredLinkRange = options.hoveredLinkRange ?? null;
218 const originY = options.originY ?? padding;
219 // Rows start on whole device pixels and clear the full canvas width, so repainting
220 // a row replaces every pixel the last frame drew in it, including a cursor's edges.
221 const transform = context.getTransform();
222 const rowTop = (row: number) =>
223 Math.round((originY + row * metrics.height) * transform.d) / transform.d;
224 const rowWidth = context.canvas.width / transform.a;
225 const rowsToDraw = forceFull
226 ? Array.from({ length: snapshot.rows }, (_, index) => index)
227 : [...snapshot.dirtyRows];
228 if (
229 previousCursorY !== null &&
230 previousCursorY !== undefined &&
231 previousCursorY >= 0 &&
232 !rowsToDraw.includes(previousCursorY)
233 ) {
234 rowsToDraw.push(previousCursorY);
235 }
236 if (snapshot.cursorVisible && snapshot.cursorY >= 0 && !rowsToDraw.includes(snapshot.cursorY)) {
237 rowsToDraw.push(snapshot.cursorY);
238 }
239​
240 if (forceFull) {
241 context.save();
242 context.resetTransform();
243 context.fillStyle = cssColor(snapshot.background);
244 context.fillRect(0, 0, context.canvas.width, context.canvas.height);
245 context.restore();
246 }
247​
248 context.textBaseline = "alphabetic";
249 for (const rowIndex of rowsToDraw) {
250 const row = snapshot.rowData[rowIndex];
251 if (!row) continue;
252 const top = rowTop(rowIndex);
253 const height = rowTop(rowIndex + 1) - top;
254​
255 context.fillStyle = cssColor(snapshot.background);
256 context.fillRect(0, top, rowWidth, height);
257​
258 let backgroundStart = 0;
259 while (backgroundStart < row.cells.length) {
260 const first = row.cells[backgroundStart];
261 if (!first) break;
262 let backgroundEnd = backgroundStart + 1;
263 while (backgroundEnd < row.cells.length) {
264 const next = row.cells[backgroundEnd];
265 if (
266 !next ||
267 next.selected !== first.selected ||
268 !ghosttyColorsEqual(next.background, first.background)
269 ) {
270 break;
271 }
272 backgroundEnd += 1;
273 }
274 if (first.selected || !ghosttyColorsEqual(first.background, snapshot.background)) {
275 const left = padding + backgroundStart * metrics.width;
276 const width = (backgroundEnd - backgroundStart) * metrics.width;
277 if (!ghosttyColorsEqual(first.background, snapshot.background)) {
278 context.fillStyle = cssColor(first.background);
279 context.fillRect(left, top, width, height);
280 }
281 if (first.selected) {
282 context.fillStyle = selectionBackground;
283 context.fillRect(left, top, width, height);
284 }
285 }
286 backgroundStart = backgroundEnd;
287 }
288​
289 let runStart = 0;
290 while (runStart < row.cells.length) {
291 const first = row.cells[runStart];
292 if (!first) break;
293 if (first.text.length === 0) {
294 runStart += 1;
295 continue;
296 }
297 if (isSolidPowerlineSeparator(first.text)) {
298 if (!first.invisible) {
299 context.fillStyle = cssColor(first.foreground);
300 fillSolidPowerlineSeparator(
301 context,
302 first.text,
303 padding + runStart * metrics.width,
304 top,
305 metrics.width,
306 height,
307 1,
308 );
309 }
310 runStart += 1;
311 continue;
312 }
313 const runEnd = ghosttyTextRunEnd(row.cells, runStart, (cell) => sameTextStyle(cell, first));
314 const text = row.cells
315 .slice(runStart, runEnd)
316 .map((cell) => cell.text)
317 .join("");
318 if (!first.invisible && text.trim().length > 0) {
319 context.save();
320 context.beginPath();
321 context.rect(
322 padding + runStart * metrics.width,
323 top,
324 (runEnd - runStart) * metrics.width,
325 height,
326 );
327 context.clip();
328 context.font = fontForCell(first, fontSize, fontFamily);
329 context.fillStyle = cssColor(first.foreground);
330 fillGhosttyRunText(
331 context,
332 row.cells,
333 runStart,
334 runEnd,
335 text,
336 padding + runStart * metrics.width,
337 top + metrics.baseline,
338 metrics.width,
339 );
340 context.restore();
341 }
342 runStart = runEnd;
343 }
344​
345 for (let column = 0; column < row.cells.length; column += 1) {
346 const cell = row.cells[column];
347 const hoveredLink =
348 hoveredLinkRange !== null &&
349 rowIndex >= hoveredLinkRange.start.y &&
350 rowIndex <= hoveredLinkRange.end.y &&
351 (rowIndex > hoveredLinkRange.start.y || column >= hoveredLinkRange.start.x) &&
352 (rowIndex < hoveredLinkRange.end.y || column <= hoveredLinkRange.end.x);
353 if (!cell || (!cell.underline && !cell.strikethrough && !cell.overline && !hoveredLink)) {
354 continue;
355 }
356 context.fillStyle = cssColor(cell.foreground);
357 const left = padding + column * metrics.width;
358 if (cell.underline || hoveredLink) {
359 context.fillRect(left, top + metrics.height - 2, metrics.width, 1);
360 }
361 if (cell.strikethrough) {
362 context.fillRect(left, top + Math.floor(metrics.height * 0.55), metrics.width, 1);
363 }
364 if (cell.overline) context.fillRect(left, top + 1, metrics.width, 1);
365 }
366 }
367​
368 if (cursorOn && snapshot.cursorVisible && snapshot.cursorX >= 0 && snapshot.cursorY >= 0) {
369 const left = padding + snapshot.cursorX * metrics.width;
370 const top = rowTop(snapshot.cursorY);
371 const height = rowTop(snapshot.cursorY + 1) - top;
372 const cells = snapshot.rowData[snapshot.cursorY]?.cells ?? [];
373 const wide = isWideGlyph(cells, snapshot.cursorX);
374 const width = wide ? metrics.width * 2 : metrics.width;
375 context.fillStyle = cssColor(snapshot.cursor);
376 if (!focused || snapshot.cursorStyle === 3) {
377 context.strokeStyle = cssColor(snapshot.cursor);
378 context.strokeRect(left + 0.5, top + 0.5, width - 1, height - 1);
379 } else if (snapshot.cursorStyle === 0) {
380 context.fillRect(left, top, 2, height);
381 } else if (snapshot.cursorStyle === 2) {
382 context.fillRect(left, top + height - 2, width, 2);
383 } else {
384 const cell = cells[snapshot.cursorX];
385 context.fillRect(left, top, width, height);
386 if (cell?.text) {
387 context.fillStyle = cssColor(snapshot.background);
388 if (isSolidPowerlineSeparator(cell.text)) {
389 fillSolidPowerlineSeparator(context, cell.text, left, top, metrics.width, height, 0);
390 } else {
391 context.font = fontForCell(cell, fontSize, fontFamily);
392 context.textAlign = wide ? "center" : "start";
393 context.fillText(
394 cell.text,
395 wide ? left + metrics.width : left,
396 top + metrics.baseline,
397 width,
398 );
399 context.textAlign = "start";
400 }
401 }
402 }
403 }