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

renderer.ts

470 lines15.3 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_LINE_WIDTH = 1;
22​
23type CellPoint = readonly [x: number, y: number];
24type PowerlineShape =
25 | { readonly kind: "fill"; readonly points: readonly CellPoint[] }
26 | { readonly kind: "stroke"; readonly points: readonly CellPoint[] }
27 | { readonly kind: "cap"; readonly flatEdge: "left" | "right"; readonly filled: boolean };
28​
29// prettier-ignore
30const POWERLINE_SHAPES: ReadonlyMap<string, PowerlineShape> = new Map([
31 ["\ue0b0", { kind: "fill", points: [[0, 0], [1, 0.5], [0, 1]] }],
32 ["\ue0b1", { kind: "stroke", points: [[0, 0], [1, 0.5], [0, 1]] }],
33 ["\ue0b2", { kind: "fill", points: [[1, 0], [0, 0.5], [1, 1]] }],
34 ["\ue0b3", { kind: "stroke", points: [[1, 0], [0, 0.5], [1, 1]] }],
35 ["\ue0b4", { kind: "cap", flatEdge: "left", filled: true }],
36 ["\ue0b5", { kind: "cap", flatEdge: "left", filled: false }],
37 ["\ue0b6", { kind: "cap", flatEdge: "right", filled: true }],
38 ["\ue0b7", { kind: "cap", flatEdge: "right", filled: false }],
39 ["\ue0b8", { kind: "fill", points: [[0, 0], [1, 1], [0, 1]] }],
40 ["\ue0b9", { kind: "stroke", points: [[0, 0], [1, 1]] }],
41 ["\ue0ba", { kind: "fill", points: [[1, 0], [1, 1], [0, 1]] }],
42 ["\ue0bb", { kind: "stroke", points: [[1, 0], [0, 1]] }],
43 ["\ue0bc", { kind: "fill", points: [[0, 0], [1, 0], [0, 1]] }],
44 ["\ue0bd", { kind: "stroke", points: [[1, 0], [0, 1]] }],
45 ["\ue0be", { kind: "fill", points: [[0, 0], [1, 0], [1, 1]] }],
46 ["\ue0bf", { kind: "stroke", points: [[0, 0], [1, 1]] }],
47]);
48​
49function cssColor(color: GhosttyColor): string {
50 return `rgb(${color.r}, ${color.g}, ${color.b})`;
52​
53function sameTextStyle(left: GhosttyCell, right: GhosttyCell): boolean {
54 // Selection only tints the background; splitting text runs shifts glyph spacing when advances differ from cell width.
55 return (
56 ghosttyColorsEqual(left.foreground, right.foreground) &&
57 left.bold === right.bold &&
58 left.italic === right.italic &&
59 left.invisible === right.invisible
60 );
62​
63// Fonts inset or scale these private-use glyphs, leaving gaps where they should
64// meet the neighboring cells. Draw them from the cell's own edges, as Ghostty does.
65function drawPowerlineShape(
66 context: CanvasRenderingContext2D,
67 shape: PowerlineShape,
68 color: string,
69 left: number,
70 top: number,
71 width: number,
72 height: number,
73 seamOverlap: number,
74): void {
75 const filled = shape.kind === "fill" || (shape.kind === "cap" && shape.filled);
76 context.save();
77 if (!filled) {
78 context.beginPath();
79 context.rect(left, top, width, height);
80 context.clip();
81 }
82 context.beginPath();
83 if (shape.kind === "cap") {
84 const inset = filled ? 0 : POWERLINE_LINE_WIDTH / 2;
85 const [base, start] =
86 shape.flatEdge === "left" ? [left, -Math.PI / 2] : [left + width, Math.PI / 2];
87 context.ellipse(
88 base,
89 top + height / 2,
90 width - inset,
91 height / 2 - inset,
92 0,
93 start,
94 start + Math.PI,
95 );
96 if (filled) {
97 context.closePath();
98 // Overlap the segment this cap closes so anti-aliasing at a fractional
99 // cell edge does not leave a hairline seam.
100 const inward = shape.flatEdge === "left" ? -1 : 1;
101 context.rect(Math.min(base, base + inward * seamOverlap), top, seamOverlap, height);
102 }
103 } else {
104 for (const [x, y] of shape.points) context.lineTo(left + x * width, top + y * height);
105 }
106 if (filled) {
107 context.fillStyle = color;
108 context.fill();
109 } else {
110 context.strokeStyle = color;
111 context.lineWidth = POWERLINE_LINE_WIDTH;
112 context.lineCap = "butt";
113 context.stroke();
114 }
115 context.restore();
117​
118function ghosttyTextRunEnd(
119 cells: readonly GhosttyCell[],
120 start: number,
121 sameStyle: (cell: GhosttyCell) => boolean,
122): number {
123 let end = start + 1;
124 while (end < cells.length) {
125 const next = cells[end];
126 if (!next) break;
127 if (next.wide === GHOSTTY_CELL_WIDE.spacerTail) {
128 end += 1;
129 continue;
130 }
131 if (next.text.length === 0 || POWERLINE_SHAPES.has(next.text) || !sameStyle(next)) break;
132 end += 1;
133 }
134 return end;
136​
137// Snapshots decode `wide` only for empty cells, so a wide glyph is known by its spacer tail.
138function isWideGlyph(cells: readonly GhosttyCell[], index: number): boolean {
139 return cells[index + 1]?.wide === GHOSTTY_CELL_WIDE.spacerTail;
141​
142// Wide glyphs rarely advance exactly two cells, so each is centred in its own box
143// and the narrow text after it restarts at its own column instead of drifting.
144function fillGhosttyRunText(
145 context: CanvasRenderingContext2D,
146 cells: readonly GhosttyCell[],
147 start: number,
148 end: number,
149 text: string,
150 left: number,
151 baseline: number,
152 cellWidth: number,
153): void {
154 let segment = start;
155 while (segment < end) {
156 let segmentEnd = segment;
157 while (segmentEnd < end && !isWideGlyph(cells, segmentEnd)) segmentEnd += 1;
158 if (segmentEnd > segment) {
159 const segmentText =
160 segment === start && segmentEnd === end
161 ? text
162 : cells
163 .slice(segment, segmentEnd)
164 .map((cell) => cell.text)
165 .join("");
166 context.fillText(
167 segmentText,
168 left + (segment - start) * cellWidth,
169 baseline,
170 (segmentEnd - segment) * cellWidth,
171 );
172 }
173 if (segmentEnd === end) break;
174 context.textAlign = "center";
175 context.fillText(
176 cells[segmentEnd]?.text ?? "",
177 left + (segmentEnd - start + 1) * cellWidth,
178 baseline,
179 cellWidth * 2,
180 );
181 context.textAlign = "start";
182 segment = segmentEnd + 2;
183 }
185​
186// Draws in the current fill style, so a block cursor can redraw them in its text colour.
187function fillCellDecorations(
188 context: CanvasRenderingContext2D,
189 cell: GhosttyCell,
190 underline: boolean,
191 left: number,
192 top: number,
193 width: number,
194 metrics: GhosttyCellMetrics,
195): void {
196 if (underline) context.fillRect(left, top + metrics.height - 2, width, 1);
197 if (cell.strikethrough) {
198 context.fillRect(left, top + Math.floor(metrics.height * 0.55), width, 1);
199 }
200 if (cell.overline) context.fillRect(left, top + 1, width, 1);
202​
203function fontForCell(cell: GhosttyCell, fontSize: number, fontFamily: string): string {
204 const style = cell.italic ? "italic" : "normal";
205 const weight = cell.bold ? "700" : "400";
206 return `${style} ${weight} ${fontSize}px ${fontFamily}`;
208​
209export function measureGhosttyCell(
210 context: CanvasRenderingContext2D,
211 fontSize: number,
212 fontFamily: string,
213): GhosttyCellMetrics {
214 context.font = `normal 400 ${fontSize}px ${fontFamily}`;
215 const widthMeasurement = context.measureText("M");
216 const verticalMeasurement = context.measureText("Mg");
217 const ascent = verticalMeasurement.actualBoundingBoxAscent || fontSize;
218 const descent = verticalMeasurement.actualBoundingBoxDescent;
219 const glyphHeight = ascent + descent;
220 const height = Math.max(1, Math.round(fontSize * 1.35), Math.ceil(glyphHeight));
221 return {
222 width: Math.max(1, widthMeasurement.width),
223 height,
224 baseline: Math.round((height - glyphHeight) / 2 + ascent),
225 };
227​
228export function terminalGridSize(
229 width: number,
230 height: number,
231 metrics: GhosttyCellMetrics,
232 padding: number,
233): { cols: number; rows: number } {
234 return {
235 cols: Math.max(1, Math.floor((width - padding * 2) / metrics.width)),
236 rows: Math.max(1, Math.floor((height - padding * 2) / metrics.height)),
237 };
239​
240export function renderGhosttySnapshot(options: {
241 readonly context: CanvasRenderingContext2D;
242 readonly snapshot: GhosttySnapshot;
243 readonly metrics: GhosttyCellMetrics;
244 readonly fontSize: number;
245 readonly fontFamily: string;
246 readonly padding: number;
247 readonly forceFull: boolean;
248 readonly cursorOn: boolean;
249 readonly previousCursorY?: number | null;
250 readonly focused?: boolean;
251 readonly selectionBackground?: string;
252 readonly hoveredLinkRange?: GhosttyCellRange | null;
253 readonly originY?: number;
254}): void {
255 const {
256 context,
257 snapshot,
258 metrics,
259 fontSize,
260 fontFamily,
261 padding,
262 forceFull,
263 cursorOn,
264 previousCursorY,
265 } = options;
266 const focused = options.focused ?? true;
267 const selectionBackground = options.selectionBackground ?? DEFAULT_SELECTION_BACKGROUND;
268 const hoveredLinkRange = options.hoveredLinkRange ?? null;
269 const originY = options.originY ?? padding;
270 // Rows start on whole device pixels and clear the full canvas width, so repainting
271 // a row replaces every pixel the last frame drew in it, including a cursor's edges.
272 const transform = context.getTransform();
273 const rowTop = (row: number) =>
274 Math.round((originY + row * metrics.height) * transform.d) / transform.d;
275 const rowWidth = context.canvas.width / transform.a;
276 const rowsToDraw = forceFull
277 ? Array.from({ length: snapshot.rows }, (_, index) => index)
278 : [...snapshot.dirtyRows];
279 if (
280 previousCursorY !== null &&
281 previousCursorY !== undefined &&
282 previousCursorY >= 0 &&
283 !rowsToDraw.includes(previousCursorY)
284 ) {
285 rowsToDraw.push(previousCursorY);
286 }
287 if (snapshot.cursorVisible && snapshot.cursorY >= 0 && !rowsToDraw.includes(snapshot.cursorY)) {
288 rowsToDraw.push(snapshot.cursorY);
289 }
290​
291 if (forceFull) {
292 context.save();
293 context.resetTransform();
294 context.fillStyle = cssColor(snapshot.background);
295 context.fillRect(0, 0, context.canvas.width, context.canvas.height);
296 context.restore();
297 }
298​
299 context.textBaseline = "alphabetic";
300 for (const rowIndex of rowsToDraw) {
301 const row = snapshot.rowData[rowIndex];
302 if (!row) continue;
303 const top = rowTop(rowIndex);
304 const height = rowTop(rowIndex + 1) - top;
305​
306 context.fillStyle = cssColor(snapshot.background);
307 context.fillRect(0, top, rowWidth, height);
308​
309 let backgroundStart = 0;
310 while (backgroundStart < row.cells.length) {
311 const first = row.cells[backgroundStart];
312 if (!first) break;
313 let backgroundEnd = backgroundStart + 1;
314 while (backgroundEnd < row.cells.length) {
315 const next = row.cells[backgroundEnd];
316 if (
317 !next ||
318 next.selected !== first.selected ||
319 !ghosttyColorsEqual(next.background, first.background)
320 ) {
321 break;
322 }
323 backgroundEnd += 1;
324 }
325 if (first.selected || !ghosttyColorsEqual(first.background, snapshot.background)) {
326 const left = padding + backgroundStart * metrics.width;
327 const width = (backgroundEnd - backgroundStart) * metrics.width;
328 if (!ghosttyColorsEqual(first.background, snapshot.background)) {
329 context.fillStyle = cssColor(first.background);
330 context.fillRect(left, top, width, height);
331 }
332 if (first.selected) {
333 context.fillStyle = selectionBackground;
334 context.fillRect(left, top, width, height);
335 }
336 }
337 backgroundStart = backgroundEnd;
338 }
339​
340 let runStart = 0;
341 while (runStart < row.cells.length) {
342 const first = row.cells[runStart];
343 if (!first) break;
344 if (first.text.length === 0) {
345 runStart += 1;
346 continue;
347 }
348 const powerlineShape = POWERLINE_SHAPES.get(first.text);
349 if (powerlineShape) {
350 if (!first.invisible) {
351 drawPowerlineShape(
352 context,
353 powerlineShape,
354 cssColor(first.foreground),
355 padding + runStart * metrics.width,
356 top,
357 metrics.width,
358 height,
359 1,
360 );
361 }
362 runStart += 1;
363 continue;
364 }
365 const runEnd = ghosttyTextRunEnd(row.cells, runStart, (cell) => sameTextStyle(cell, first));
366 const text = row.cells
367 .slice(runStart, runEnd)
368 .map((cell) => cell.text)
369 .join("");
370 if (!first.invisible && text.trim().length > 0) {
371 context.save();
372 context.beginPath();
373 context.rect(
374 padding + runStart * metrics.width,
375 top,
376 (runEnd - runStart) * metrics.width,
377 height,
378 );
379 context.clip();
380 context.font = fontForCell(first, fontSize, fontFamily);
381 context.fillStyle = cssColor(first.foreground);
382 fillGhosttyRunText(
383 context,
384 row.cells,
385 runStart,
386 runEnd,
387 text,
388 padding + runStart * metrics.width,
389 top + metrics.baseline,
390 metrics.width,
391 );
392 context.restore();
393 }
394 runStart = runEnd;
395 }
396​
397 for (let column = 0; column < row.cells.length; column += 1) {
398 const cell = row.cells[column];
399 if (!cell || cell.invisible) continue;
400 const hoveredLink =
401 hoveredLinkRange !== null &&
402 rowIndex >= hoveredLinkRange.start.y &&
403 rowIndex <= hoveredLinkRange.end.y &&
404 (rowIndex > hoveredLinkRange.start.y || column >= hoveredLinkRange.start.x) &&
405 (rowIndex < hoveredLinkRange.end.y || column <= hoveredLinkRange.end.x);
406 if (!cell.underline && !cell.strikethrough && !cell.overline && !hoveredLink) continue;
407 context.fillStyle = cssColor(cell.foreground);
408 const left = padding + column * metrics.width;
409 fillCellDecorations(
410 context,
411 cell,
412 cell.underline || hoveredLink,
413 left,
414 top,
415 metrics.width,
416 metrics,
417 );
418 }
419 }
420​
421 if (cursorOn && snapshot.cursorVisible && snapshot.cursorX >= 0 && snapshot.cursorY >= 0) {
422 const left = padding + snapshot.cursorX * metrics.width;
423 const top = rowTop(snapshot.cursorY);
424 const height = rowTop(snapshot.cursorY + 1) - top;
425 const cells = snapshot.rowData[snapshot.cursorY]?.cells ?? [];
426 const wide = isWideGlyph(cells, snapshot.cursorX);
427 const width = wide ? metrics.width * 2 : metrics.width;
428 context.fillStyle = cssColor(snapshot.cursor);
429 if (!focused || snapshot.cursorStyle === 3) {
430 context.strokeStyle = cssColor(snapshot.cursor);
431 context.strokeRect(left + 0.5, top + 0.5, width - 1, height - 1);
432 } else if (snapshot.cursorStyle === 0) {
433 context.fillRect(left, top, 2, height);
434 } else if (snapshot.cursorStyle === 2) {
435 context.fillRect(left, top + height - 2, width, 2);
436 } else {
437 const cell = cells[snapshot.cursorX];
438 context.fillRect(left, top, width, height);
439 context.fillStyle = cssColor(snapshot.background);
440 if (cell?.text && !cell.invisible) {
441 const powerlineShape = POWERLINE_SHAPES.get(cell.text);
442 if (powerlineShape) {
443 drawPowerlineShape(
444 context,
445 powerlineShape,
446 cssColor(snapshot.background),
447 left,
448 top,
449 metrics.width,
450 height,
451 0,
452 );
453 } else {
454 context.font = fontForCell(cell, fontSize, fontFamily);
455 context.textAlign = wide ? "center" : "start";
456 context.fillText(
457 cell.text,
458 wide ? left + metrics.width : left,
459 top + metrics.baseline,
460 width,
461 );
462 context.textAlign = "start";
463 }
464 }
465 if (cell && !cell.invisible) {
466 fillCellDecorations(context, cell, cell.underline, left, top, width, metrics);
467 }
468 }
469 }