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

renderer.ts

314 lines10.5 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";
23​
24function cssColor(color: GhosttyColor): string {
25 return `rgb(${color.r}, ${color.g}, ${color.b})`;
27​
28function sameTextStyle(left: GhosttyCell, right: GhosttyCell): boolean {
29 // Selection deliberately does not participate: it only tints the background
30 // overlay, and splitting a text run at a selection boundary visibly shifts
31 // glyph spacing whenever the face's true advance differs from the 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 text === POWERLINE_SOLID_RIGHT || text === POWERLINE_SOLID_LEFT;
43​
44// Fallback fonts inset or scale these private-use glyphs, leaving a gap where
45// the separator should meet the next cell. Fill the triangle from the cell's
46// own edges instead, as native terminals do.
47function fillSolidPowerlineSeparator(
48 context: CanvasRenderingContext2D,
49 text: string,
50 left: number,
51 top: number,
52 metrics: GhosttyCellMetrics,
53): void {
54 const right = left + metrics.width;
55 const [base, point] = text === POWERLINE_SOLID_RIGHT ? [left, right] : [right, left];
56 context.beginPath();
57 context.moveTo(base, top);
58 context.lineTo(point, top + metrics.height / 2);
59 context.lineTo(base, top + metrics.height);
60 context.closePath();
61 context.fill();
63​
64function ghosttyTextRunEnd(
65 cells: readonly GhosttyCell[],
66 start: number,
67 sameStyle: (cell: GhosttyCell) => boolean,
68): number {
69 let end = start + 1;
70 while (end < cells.length) {
71 const next = cells[end];
72 if (!next) break;
73 if (next.wide === GHOSTTY_CELL_WIDE.spacerTail) {
74 end += 1;
75 continue;
76 }
77 if (next.text.length === 0 || isSolidPowerlineSeparator(next.text) || !sameStyle(next)) break;
78 end += 1;
79 }
80 return end;
82​
83function fontForCell(cell: GhosttyCell, fontSize: number, fontFamily: string): string {
84 const style = cell.italic ? "italic" : "normal";
85 const weight = cell.bold ? "700" : "400";
86 return `${style} ${weight} ${fontSize}px ${fontFamily}`;
88​
89export function measureGhosttyCell(
90 context: CanvasRenderingContext2D,
91 fontSize: number,
92 fontFamily: string,
93): GhosttyCellMetrics {
94 context.font = `normal 400 ${fontSize}px ${fontFamily}`;
95 const widthMeasurement = context.measureText("M");
96 const verticalMeasurement = context.measureText("Mg");
97 const ascent = verticalMeasurement.actualBoundingBoxAscent || fontSize;
98 const descent = verticalMeasurement.actualBoundingBoxDescent;
99 const glyphHeight = ascent + descent;
100 const height = Math.max(1, Math.round(fontSize * 1.35), Math.ceil(glyphHeight));
101 return {
102 width: Math.max(1, widthMeasurement.width),
103 height,
104 baseline: Math.round((height - glyphHeight) / 2 + ascent),
105 };
107​
108export function terminalGridSize(
109 width: number,
110 height: number,
111 metrics: GhosttyCellMetrics,
112 padding: number,
113): { cols: number; rows: number } {
114 return {
115 cols: Math.max(1, Math.floor((width - padding * 2) / metrics.width)),
116 rows: Math.max(1, Math.floor((height - padding * 2) / metrics.height)),
117 };
119​
120export function renderGhosttySnapshot(options: {
121 readonly context: CanvasRenderingContext2D;
122 readonly snapshot: GhosttySnapshot;
123 readonly metrics: GhosttyCellMetrics;
124 readonly fontSize: number;
125 readonly fontFamily: string;
126 readonly padding: number;
127 readonly forceFull: boolean;
128 readonly cursorOn: boolean;
129 readonly previousCursorY?: number | null;
130 readonly focused?: boolean;
131 readonly selectionBackground?: string;
132 readonly hoveredLinkRange?: GhosttyCellRange | null;
133 readonly originY?: number;
134}): void {
135 const {
136 context,
137 snapshot,
138 metrics,
139 fontSize,
140 fontFamily,
141 padding,
142 forceFull,
143 cursorOn,
144 previousCursorY,
145 } = options;
146 const focused = options.focused ?? true;
147 const selectionBackground = options.selectionBackground ?? DEFAULT_SELECTION_BACKGROUND;
148 const hoveredLinkRange = options.hoveredLinkRange ?? null;
149 const originY = options.originY ?? padding;
150 const rowsToDraw = forceFull
151 ? Array.from({ length: snapshot.rows }, (_, index) => index)
152 : [...snapshot.dirtyRows];
153 if (
154 previousCursorY !== null &&
155 previousCursorY !== undefined &&
156 previousCursorY >= 0 &&
157 !rowsToDraw.includes(previousCursorY)
158 ) {
159 rowsToDraw.push(previousCursorY);
160 }
161 if (snapshot.cursorVisible && snapshot.cursorY >= 0 && !rowsToDraw.includes(snapshot.cursorY)) {
162 rowsToDraw.push(snapshot.cursorY);
163 }
164​
165 if (forceFull) {
166 context.save();
167 context.resetTransform();
168 context.fillStyle = cssColor(snapshot.background);
169 context.fillRect(0, 0, context.canvas.width, context.canvas.height);
170 context.restore();
171 }
172​
173 context.textBaseline = "alphabetic";
174 for (const rowIndex of rowsToDraw) {
175 const row = snapshot.rowData[rowIndex];
176 if (!row) continue;
177 const top = originY + rowIndex * metrics.height;
178​
179 context.fillStyle = cssColor(snapshot.background);
180 context.fillRect(padding, top, snapshot.cols * metrics.width, metrics.height);
181​
182 let backgroundStart = 0;
183 while (backgroundStart < row.cells.length) {
184 const first = row.cells[backgroundStart];
185 if (!first) break;
186 let backgroundEnd = backgroundStart + 1;
187 while (backgroundEnd < row.cells.length) {
188 const next = row.cells[backgroundEnd];
189 if (
190 !next ||
191 next.selected !== first.selected ||
192 !ghosttyColorsEqual(next.background, first.background)
193 ) {
194 break;
195 }
196 backgroundEnd += 1;
197 }
198 if (first.selected || !ghosttyColorsEqual(first.background, snapshot.background)) {
199 const left = padding + backgroundStart * metrics.width;
200 const width = (backgroundEnd - backgroundStart) * metrics.width;
201 if (!ghosttyColorsEqual(first.background, snapshot.background)) {
202 context.fillStyle = cssColor(first.background);
203 context.fillRect(left, top, width, metrics.height);
204 }
205 if (first.selected) {
206 context.fillStyle = selectionBackground;
207 context.fillRect(left, top, width, metrics.height);
208 }
209 }
210 backgroundStart = backgroundEnd;
211 }
212​
213 let runStart = 0;
214 while (runStart < row.cells.length) {
215 const first = row.cells[runStart];
216 if (!first) break;
217 if (first.text.length === 0) {
218 runStart += 1;
219 continue;
220 }
221 if (isSolidPowerlineSeparator(first.text)) {
222 if (!first.invisible) {
223 context.fillStyle = cssColor(first.foreground);
224 fillSolidPowerlineSeparator(
225 context,
226 first.text,
227 padding + runStart * metrics.width,
228 top,
229 metrics,
230 );
231 }
232 runStart += 1;
233 continue;
234 }
235 const runEnd = ghosttyTextRunEnd(row.cells, runStart, (cell) => sameTextStyle(cell, first));
236 const text = row.cells
237 .slice(runStart, runEnd)
238 .map((cell) => cell.text)
239 .join("");
240 if (!first.invisible && text.trim().length > 0) {
241 context.save();
242 context.beginPath();
243 context.rect(
244 padding + runStart * metrics.width,
245 top,
246 (runEnd - runStart) * metrics.width,
247 metrics.height,
248 );
249 context.clip();
250 context.font = fontForCell(first, fontSize, fontFamily);
251 context.fillStyle = cssColor(first.foreground);
252 context.fillText(
253 text,
254 padding + runStart * metrics.width,
255 top + metrics.baseline,
256 (runEnd - runStart) * metrics.width,
257 );
258 context.restore();
259 }
260 runStart = runEnd;
261 }
262​
263 for (let column = 0; column < row.cells.length; column += 1) {
264 const cell = row.cells[column];
265 const hoveredLink =
266 hoveredLinkRange !== null &&
267 rowIndex >= hoveredLinkRange.start.y &&
268 rowIndex <= hoveredLinkRange.end.y &&
269 (rowIndex > hoveredLinkRange.start.y || column >= hoveredLinkRange.start.x) &&
270 (rowIndex < hoveredLinkRange.end.y || column <= hoveredLinkRange.end.x);
271 if (!cell || (!cell.underline && !cell.strikethrough && !cell.overline && !hoveredLink)) {
272 continue;
273 }
274 context.fillStyle = cssColor(cell.foreground);
275 const left = padding + column * metrics.width;
276 if (cell.underline || hoveredLink) {
277 context.fillRect(left, top + metrics.height - 2, metrics.width, 1);
278 }
279 if (cell.strikethrough) {
280 context.fillRect(left, top + Math.floor(metrics.height * 0.55), metrics.width, 1);
281 }
282 if (cell.overline) context.fillRect(left, top + 1, metrics.width, 1);
283 }
284 }
285​
286 if (cursorOn && snapshot.cursorVisible && snapshot.cursorX >= 0 && snapshot.cursorY >= 0) {
287 const left = padding + snapshot.cursorX * metrics.width;
288 const top = originY + snapshot.cursorY * metrics.height;
289 context.fillStyle = cssColor(snapshot.cursor);
290 if (!focused) {
291 context.strokeStyle = cssColor(snapshot.cursor);
292 context.strokeRect(left + 0.5, top + 0.5, metrics.width - 1, metrics.height - 1);
293 } else if (snapshot.cursorStyle === 0) {
294 context.fillRect(left, top, 2, metrics.height);
295 } else if (snapshot.cursorStyle === 2) {
296 context.fillRect(left, top + metrics.height - 2, metrics.width, 2);
297 } else if (snapshot.cursorStyle === 3) {
298 context.strokeStyle = cssColor(snapshot.cursor);
299 context.strokeRect(left + 0.5, top + 0.5, metrics.width - 1, metrics.height - 1);
300 } else {
301 context.fillRect(left, top, metrics.width, metrics.height);
302 const cell = snapshot.rowData[snapshot.cursorY]?.cells[snapshot.cursorX];
303 if (cell?.text) {
304 context.fillStyle = cssColor(snapshot.background);
305 if (isSolidPowerlineSeparator(cell.text)) {
306 fillSolidPowerlineSeparator(context, cell.text, left, top, metrics);
307 } else {
308 context.font = fontForCell(cell, fontSize, fontFamily);
309 context.fillText(cell.text, left, top + metrics.baseline, metrics.width);
310 }
311 }
312 }
313 }